Browse Source

Merge branch 'refactoring' into develop

feature/souke
Guillaume 1 year ago
parent
commit
732ddadd0e
100 changed files with 4243 additions and 4059 deletions
  1. +2
    -2
      backend/config/main.php
  2. +65
    -78
      backend/controllers/AccessController.php
  3. +62
    -37
      backend/controllers/BackendController.php
  4. +69
    -76
      backend/controllers/CommunicateAdminController.php
  5. +61
    -61
      backend/controllers/CommunicateController.php
  6. +84
    -81
      backend/controllers/CronController.php
  7. +48
    -47
      backend/controllers/DeliveryNoteController.php
  8. +64
    -69
      backend/controllers/DevelopmentController.php
  9. +222
    -195
      backend/controllers/DistributionController.php
  10. +127
    -114
      backend/controllers/DocumentController.php
  11. +55
    -55
      backend/controllers/InvoiceController.php
  12. +195
    -233
      backend/controllers/OrderController.php
  13. +119
    -127
      backend/controllers/PointSaleController.php
  14. +102
    -167
      backend/controllers/ProducerAdminController.php
  15. +18
    -39
      backend/controllers/ProducerController.php
  16. +92
    -103
      backend/controllers/ProducerPriceRangeAdminController.php
  17. +117
    -140
      backend/controllers/ProductCategoryController.php
  18. +226
    -87
      backend/controllers/ProductController.php
  19. +65
    -61
      backend/controllers/QuotationController.php
  20. +107
    -115
      backend/controllers/ReportController.php
  21. +22
    -92
      backend/controllers/SiteController.php
  22. +99
    -107
      backend/controllers/StatsController.php
  23. +158
    -182
      backend/controllers/SubscriptionController.php
  24. +81
    -115
      backend/controllers/TaxRateAdminController.php
  25. +120
    -128
      backend/controllers/UserController.php
  26. +100
    -121
      backend/controllers/UserGroupController.php
  27. +36
    -0
      backend/forms/ProductPriceUploadForm.php
  28. +4
    -8
      backend/models/AccessUserProducerForm.php
  29. +23
    -18
      backend/models/CreditForm.php
  30. +13
    -6
      backend/models/MailForm.php
  31. +3
    -1
      backend/views/access/index.php
  32. +104
    -103
      backend/views/delivery-note/index.php
  33. +4
    -4
      backend/views/development/_form.php
  34. +11
    -11
      backend/views/development/development.php
  35. +1
    -1
      backend/views/development/index.php
  36. +17
    -7
      backend/views/distribution/index.php
  37. +20
    -16
      backend/views/distribution/report-bourlingue.php
  38. +113
    -104
      backend/views/distribution/report-grid.php
  39. +33
    -30
      backend/views/distribution/report.php
  40. +15
    -4
      backend/views/document/_download_product_line.php
  41. +18
    -12
      backend/views/document/_form.php
  42. +29
    -20
      backend/views/document/download.php
  43. +109
    -110
      backend/views/invoice/index.php
  44. +4
    -1
      backend/views/layouts/content.php
  45. +14
    -15
      backend/views/layouts/header.php
  46. +36
    -30
      backend/views/layouts/left.php
  47. +0
    -298
      backend/views/layouts/main-old.php
  48. +12
    -9
      backend/views/order/report.php
  49. +11
    -11
      backend/views/point-sale/_form.php
  50. +8
    -11
      backend/views/point-sale/index.php
  51. +1
    -0
      backend/views/producer-admin/_form.php
  52. +1
    -1
      backend/views/producer-admin/billing.php
  53. +0
    -5
      backend/views/producer-admin/create.php
  54. +16
    -15
      backend/views/producer-admin/index.php
  55. +0
    -5
      backend/views/producer-admin/update.php
  56. +0
    -2
      backend/views/producer-price-range-admin/create.php
  57. +1
    -3
      backend/views/producer-price-range-admin/index.php
  58. +0
    -2
      backend/views/producer-price-range-admin/update.php
  59. +7
    -10
      backend/views/producer/billing.php
  60. +7
    -4
      backend/views/producer/update.php
  61. +0
    -7
      backend/views/product-category/_form.php
  62. +2
    -2
      backend/views/product-category/update.php
  63. +8
    -6
      backend/views/product/_form.php
  64. +6
    -7
      backend/views/product/index.php
  65. +68
    -0
      backend/views/product/price_import.php
  66. +10
    -1
      backend/views/product/update/prices/_base_price.php
  67. +10
    -14
      backend/views/product/update/prices/_form.php
  68. +112
    -196
      backend/views/product/update/prices/list.php
  69. +1
    -5
      backend/views/product/update/update.php
  70. +96
    -91
      backend/views/quotation/index.php
  71. +13
    -7
      backend/views/site/index.php
  72. +9
    -8
      backend/views/subscription/_form.php
  73. +12
    -7
      backend/views/subscription/index.php
  74. +0
    -2
      backend/views/tax-rate-admin/create.php
  75. +0
    -3
      backend/views/tax-rate-admin/index.php
  76. +0
    -2
      backend/views/tax-rate-admin/update.php
  77. +0
    -5
      backend/views/user-group/_form.php
  78. +7
    -4
      backend/views/user/_form.php
  79. +2
    -0
      backend/views/user/_menu.php
  80. +21
    -18
      backend/views/user/credit.php
  81. +10
    -7
      backend/views/user/index.php
  82. +16
    -12
      backend/views/user/orders.php
  83. +22
    -12
      backend/web/css/screen.css
  84. +15
    -14
      backend/web/js/vuejs/distribution-index.js
  85. +9
    -0
      backend/web/sass/distribution/_index.scss
  86. +15
    -6
      common/components/ActiveRecordCommon.php
  87. +82
    -0
      common/components/BusinessLogic.php
  88. +319
    -0
      common/components/BusinessLogicTrait.php
  89. +26
    -4
      common/components/View.php
  90. +11
    -0
      common/components/ViewBackend.php
  91. +11
    -0
      common/components/ViewFrontend.php
  92. +84
    -79
      common/config/main.php
  93. +50
    -2
      common/controllers/CommonController.php
  94. +7
    -7
      common/forms/ContactForm.php
  95. +4
    -3
      common/forms/LoginForm.php
  96. +9
    -8
      common/forms/SubscriptionForm.php
  97. +4
    -3
      common/helpers/CSV.php
  98. +17
    -4
      common/helpers/GlobalParam.php
  99. +1
    -1
      common/helpers/Mail.php
  100. +3
    -3
      common/helpers/Mailjet.php

+ 2
- 2
backend/config/main.php View File



return [ return [
'id' => 'app-backend', 'id' => 'app-backend',
'name' => 'distrib',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'name' => 'distrib',
'controllerNamespace' => 'backend\controllers', 'controllerNamespace' => 'backend\controllers',
'defaultRoute' => 'site/index', 'defaultRoute' => 'site/index',
'bootstrap' => ['log'], 'bootstrap' => ['log'],
], ],
], ],
'view' => [ 'view' => [
'class' => 'common\components\MyView',
'class' => 'common\components\ViewBackend',
], ],
], ],
'params' => $params, 'params' => $params,

+ 65
- 78
backend/controllers/AccessController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam;
use common\models\Producer ;
use common\models\User ;
use common\models\UserSearch ;
use backend\models\AccessUserProducerForm ;
use backend\models\AccessUserProducerForm;
use common\logic\User\User\Model\UserSearch;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
class AccessController extends BackendController
class AccessController extends BackendController
{ {


public function behaviors() {
public function behaviors()
{
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],
/** /**
* Affiche les utilisateurs ayant accès à l'administration de ce producteur. * Affiche les utilisateurs ayant accès à l'administration de ce producteur.
* Gestion du formulaire permettant d'en ajouter de nouveaux. * Gestion du formulaire permettant d'en ajouter de nouveaux.
*
*
* @return string * @return string
*/ */
public function actionIndex()
public function actionIndex()
{ {
$userSearch = new UserSearch ;
$usersArray = $userSearch->search()->query->all() ;
$modelAccessUserProducerForm = new AccessUserProducerForm ;
if($modelAccessUserProducerForm->load(Yii::$app->request->post()) && $modelAccessUserProducerForm->save()) {
Yii::$app->getSession()->setFlash('success', 'Droits ajoutés à l\'utilisateur');
$userSearch = new UserSearch();
$usersArray = $userSearch->search()->query->all();
$modelAccessUserProducerForm = new AccessUserProducerForm;
if ($modelAccessUserProducerForm->load(\Yii::$app->request->post()) && $modelAccessUserProducerForm->save()) {
$this->setFlash('success', 'Droits ajoutés à l\'utilisateur');
} }
$usersAccessArray = User::find()
->where([
'id_producer' => GlobalParam::getCurrentProducerId(),
'status' => User::STATUS_PRODUCER
])
->all() ;
$producer = Producer::searchOne() ;

$producer = $this->getProducerCurrent();
$usersAccessArray = $this->getUserManager()->findUsersByProducer($producer);


return $this->render('index', [ return $this->render('index', [
'usersArray' => $usersArray, 'usersArray' => $usersArray,
]); ]);
} }


/**
*
*/
public function actionDelete($idUser)
public function actionDelete($idUser)
{ {
$user = User::searchOne([
'id' => $idUser
]) ;
if($user) {
$user->id_producer = 0 ;
$user->status = User::STATUS_ACTIVE ;
$user->save() ;
Yii::$app->getSession()->setFlash('success', 'Droits de l\'utilisateur supprimé.');
$userManager = $this->getUserManager();
$user = $userManager->findOneUserById($idUser);

if ($user) {
$userManager->deleteAccess($user);
$this->setFlash('success', 'Droits de l\'utilisateur supprimé.');
} }
return $this->redirect(['index']) ;

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

+ 62
- 37
backend/controllers/BackendController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\models\Producer ;
use common\controllers\CommonController;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Product\Product\Model\Product;


class BackendController extends \common\controllers\CommonController
class BackendController extends CommonController
{ {
public function beforeAction($event)
{
$producerCurrent = $this->getProducerCurrent();

// Contexte producteur
if($producerCurrent) {
$this->getLogic()->setProducerContext($producerCurrent);
}

// Pas de producteur défini
if(!$producerCurrent) {
$this->redirect(\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/index']));
return false;
}

return parent::beforeAction($event);
}

/** /**
* Vérifie si l'utilisateur a au moins saisi un produit et un point de vente. * Vérifie si l'utilisateur a au moins saisi un produit et un point de vente.
* Si ce n'est pas le cas : redirection vers le tableau de bord. * Si ce n'est pas le cas : redirection vers le tableau de bord.
} }
} }


public function getProducerCurrent(): ?Producer
{
return Producer::searchOne();
}
} }


?> ?>

+ 69
- 76
backend/controllers/CommunicateAdminController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use backend\models\MailForm ;
use yii\web\NotFoundHttpException ;
use common\models\User ;
use backend\models\MailForm;
use common\logic\User\User\Model\User;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
class CommunicateAdminController extends BackendController
class CommunicateAdminController extends BackendController
{ {


public function behaviors()
public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['post'], 'delete' => ['post'],
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == USER::STATUS_ADMIN;
return $this->getUserManager()->isCurrentAdmin();
} }
] ]
], ],
]; ];
} }


/**
*
*
* @return mixed
*/
public function actionIndex($section = 'producers')
public function actionIndex($section = 'producers')
{ {
if($section == 'producers') {
$producers = Producer::find()->where(['producer.active' => 1])->with(['contact'])->all() ;
$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();

if ($section == 'producers') {
$producers = $producerManager->findProducersActive();
$usersArray = []; $usersArray = [];
$users = [] ;
$users = [];
foreach ($producers as $producer) { foreach ($producers as $producer) {
if (isset($producer->contact) && is_array($producer->contact)) { if (isset($producer->contact) && is_array($producer->contact)) {
foreach($producer->contact as $contact) {
$usersArray[] = $contact->email ;
foreach ($producer->contact as $contact) {
$usersArray[] = $contact->email;
$users[] = [ $users[] = [
'email' => $contact->email, 'email' => $contact->email,
'name' => $contact->name, 'name' => $contact->name,
'lastname' => $contact->lastname, 'lastname' => $contact->lastname,
] ;
];
} }
} }
} }
}
elseif($section == 'users') {
$users = User::find()
->where([
'user.status' => User::STATUS_ACTIVE
])
->all() ;
} elseif ($section == 'users') {
$users = $userManager->findUsersByStatus(User::STATUS_ACTIVE);
$usersArray = []; $usersArray = [];
foreach ($users as $user) { foreach ($users as $user) {
if (isset($user['email']) && strlen($user['email'])) { if (isset($user['email']) && strlen($user['email'])) {
$usersArray[] = $user['email']; $usersArray[] = $user['email'];
} }
} }
}
else {
} else {
throw new NotFoundHttpException('Requête incorrecte.'); throw new NotFoundHttpException('Requête incorrecte.');
} }
$mailForm = new MailForm() ;
if ($mailForm->load(Yii::$app->request->post()) && $mailForm->validate()) {
$resultSendEmail = $mailForm->sendEmail($users, false) ;
if($resultSendEmail) {
Yii::$app->getSession()->setFlash('success', 'Votre email a bien été envoyé.');
}
else {
Yii::$app->getSession()->setFlash('error', 'Un problème est survenu lors de l\'envoi de votre email.');

$mailForm = new MailForm();
if ($mailForm->load(\Yii::$app->request->post()) && $mailForm->validate()) {
$resultSendEmail = $mailForm->sendEmail($users, false);
if ($resultSendEmail) {
$this->setFlash('success', 'Votre email a bien été envoyé.');
} else {
$this->setFlash('error', 'Un problème est survenu lors de l\'envoi de votre email.');
} }
$mailForm->subject = '' ;
$mailForm->message = '' ;
$mailForm->subject = '';
$mailForm->message = '';
} }
return $this->render('index', [ return $this->render('index', [
'section' => $section, 'section' => $section,
'usersArray' => $usersArray, 'usersArray' => $usersArray,

+ 61
- 61
backend/controllers/CommunicateController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\models\Producer ;
use common\models\User ;
use kartik\mpdf\Pdf;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
class CommunicateController extends BackendController
class CommunicateController extends BackendController
{ {


public function behaviors() {
public function behaviors()
{
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['post'], 'delete' => ['post'],
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],
/** /**
* Affiche la page d'accueil de la section avec un aperçu du mpde d'emploi * Affiche la page d'accueil de la section avec un aperçu du mpde d'emploi
* à imprimer. * à imprimer.
*
* @return string
*/ */
public function actionIndex()
public function actionIndex()
{ {
$producer = Producer::searchOne() ;
$pointsSaleArray = PointSale::searchAll() ;
$producer = $this->getProducerCurrent();
$pointsSaleArray = $this->getPointSaleManager()->findPointSales();
return $this->render('index', [ return $this->render('index', [
'producer' => $producer, 'producer' => $producer,
'pointsSaleArray' => $pointsSaleArray, 'pointsSaleArray' => $pointsSaleArray,
/** /**
* Génére un PDF contenant le mode d'emploi d'utilisation de la plateforme * Génére un PDF contenant le mode d'emploi d'utilisation de la plateforme
* à destination des clients des producteurs. * à destination des clients des producteurs.
*
*
* @return string * @return string
*/ */
public function actionInstructions()
public function actionInstructions()
{ {
$producer = Producer::searchOne() ;
$producer = $this->getProducerCurrent();


// 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', [
// enhanced bootstrap css built by Krajee for mPDF formatting // enhanced bootstrap css built by Krajee for mPDF formatting
//'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css', //'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssFile' => '@app/web/css/screen.css', 'cssFile' => '@app/web/css/screen.css',
// any css to be embedded if required
//'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
//'options' => ['title' => 'Krajee Report Title'],
// call mPDF methods on the fly
/* 'methods' => [
'SetHeader'=>['Commandes du '.$date_str],
'SetFooter'=>['{PAGENO}'],
] */
// any css to be embedded if required
//'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
//'options' => ['title' => 'Krajee Report Title'],
// call mPDF methods on the fly
/* 'methods' => [
'SetHeader'=>['Commandes du '.$date_str],
'SetFooter'=>['{PAGENO}'],
] */
]); ]);


// return the pdf output as per the destination setting // return the pdf output as per the destination setting

+ 84
- 81
backend/controllers/CronController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\helpers\MeanPayment;
use common\logic\Order\Order\Model\Order;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\logic\User\User\Model\User;
use Yii; use Yii;
use common\models\User;
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.
public function behaviors() public function behaviors()
{ {
return [ return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'delete' => ['post'],
], ],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['pay-orders'],
'allow' => true,
'roles' => ['@']
],
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['pay-orders'],
'allow' => true,
'roles' => ['@']
],
], ],
],
]; ];
} }


public function actionInitDemo($key = '') public function actionInitDemo($key = '')
{ {
if ($key == '45432df6e842ac71aa0b5bb6b9f25d44') { if ($key == '45432df6e842ac71aa0b5bb6b9f25d44') {
$producer = Producer::getDemoAccount();

$producerManager = $this->getProducerManager();
$distributionManager = $this->getDistributionManager();

$producer = $producerManager->findOneProducerDemoAccount();
$producerManager->setProducerContext($producer);
$distributionManager->setProducerContext($producer);


if ($producer) { if ($producer) {
// initialisation de la distribution à J+7 // initialisation de la distribution à J+7
} }


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


return [ return [
'return' => 'success',
'alert' => [
'type' => 'success',
'message' => 'Commandes payées.'
]
'return' => 'success',
'alert' => [
'type' => 'success',
'message' => 'Commandes payées.'
]
]; ];
} }


*/ */
public function actionProcessOrders($key = '', $forceDate = '') public function actionProcessOrders($key = '', $forceDate = '')
{ {
$producerManager = $this->getProducerManager();
$distributionManager = $this->getDistributionManager();
$orderManager = $this->getOrderManager();
$creditHistoryManager = $this->getCreditHistoryManager();
$userManager = $this->getUserManager();

if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') { if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
ini_set('memory_limit', '-1'); ini_set('memory_limit', '-1');
set_time_limit(0); set_time_limit(0);
ini_set('display_startup_errors', 1); ini_set('display_startup_errors', 1);
error_reporting(E_ALL); error_reporting(E_ALL);


Yii::error('Cron process orders', 'log-cron');
$hour = 20; $hour = 20;
if (strlen($forceDate)) { if (strlen($forceDate)) {
$date = $forceDate; $date = $forceDate;
$date = date('Y-m-d', time() + 24 * 60 * 60); $date = date('Y-m-d', time() + 24 * 60 * 60);
} }
} }

$arrayProducers = Producer::searchAll();
$arrayProducers = $producerManager->findProducers();


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

$distribution = Distribution::findOne([
'date' => $date,
'active' => 1,
'id_producer' => $producer->id,
]);
$distribution = $distributionManager
->findOneDistribution($date, true);


if ($distribution) { if ($distribution) {
if ($hour == $producer->order_deadline || strlen($forceDate)) { if ($hour == $producer->order_deadline || strlen($forceDate)) {
*/ */


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


$configCredit = Producer::getConfig('credit', $producer->id);
$configCredit = $producerManager->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) {
$order->saveCreditHistory(
CreditHistory::TYPE_PAYMENT,
$order->getAmount(Order::AMOUNT_REMAINING),
$order->distribution->id_producer,
$order->id_user,
User::ID_USER_SYSTEM
if ($orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING) > 0) {
$creditHistoryManager->createCreditHistory(
CreditHistory::TYPE_PAYMENT,
$orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING),
$order->distribution->producer,
$order->user,
$userManager->findOneUserById(User::ID_USER_SYSTEM),
MeanPayment::CREDIT,
$order
); );
$countOrders++; $countOrders++;
} }
* 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)) {
if (!strlen($forceDate) && $producerManager->getConfig('option_notify_producer_order_summary', $producer->id)) {
$arrayOrders = Order::searchAll([ $arrayOrders = Order::searchAll([
'distribution.date' => $date,
'distribution.id_producer' => $producer->id
], [
'conditions' => 'date_delete IS NULL'
]);
'distribution.date' => $date,
'distribution.id_producer' => $producer->id
], [
'conditions' => 'date_delete IS NULL'
]);


$mail = Yii::$app->mailer->compose( $mail = Yii::$app->mailer->compose(
[
'html' => 'cronOrdersSummary-html',
'text' => 'cronOrdersSummary-text',
], [
'date' => $date,
'orders' => $arrayOrders
]
[
'html' => 'cronOrdersSummary-html',
'text' => 'cronOrdersSummary-text',
], [
'date' => $date,
'orders' => $arrayOrders
]
) )
->setFrom([Yii::$app->params['adminEmail'] => 'distrib']); ->setFrom([Yii::$app->params['adminEmail'] => 'distrib']);


if (is_array($arrayOrders) && count($arrayOrders)) { if (is_array($arrayOrders) && count($arrayOrders)) {
$subject = '[distrib] Commandes du ' . date('d/m', strtotime($date));
$subject = '[Opendistrib] Commandes du ' . date('d/m', strtotime($date));


// génération du pdf de commande // génération du pdf de commande
Yii::$app->runAction('distribution/report-cron', [ Yii::$app->runAction('distribution/report-cron', [
'date' => $date,
'save' => true,
'idProducer' => $producer->id,
'key' => '64ac0bdab7e9f5e48c4d991ec5201d57'
'date' => $date,
'save' => true,
'idProducer' => $producer->id,
'key' => '64ac0bdab7e9f5e48c4d991ec5201d57'
]); ]);
$mail->attach( $mail->attach(
Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $producer->id . '.pdf')
Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $producer->id . '.pdf')
); );
} else { } else {
$subject = '[distrib] Aucune commande';
$subject = '[Opendistrib] Aucune commande';
} }


$mail->setSubject($subject); $mail->setSubject($subject);


// envoi des emails à tous les comptes users (statut producer) associés à ce producteur // envoi des emails à tous les comptes users (statut producer) associés à ce producteur
$userArray = User::searchAll([ $userArray = User::searchAll([
'id_producer' => $producer->id,
'status' => User::STATUS_PRODUCER
]);
'id_producer' => $producer->id,
'status' => User::STATUS_PRODUCER
]);


foreach ($userArray as $user) { foreach ($userArray as $user) {
$mail->setTo($user->email)->send(); $mail->setTo($user->email)->send();

+ 48
- 47
backend/controllers/DeliveryNoteController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\logic\Document\DeliveryNote\Model\DeliveryNoteSearch;
use Yii; use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;



class DeliveryNoteController extends DocumentController
class DeliveryNoteController extends DocumentController
{ {
public function behaviors()
public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


/** /**
* Liste les modèles Invoice. * Liste les modèles Invoice.
*
*
* @return mixed * @return mixed
*/ */
public function actionIndex()
public function actionIndex()
{ {
$searchModel = new DeliveryNoteSearch() ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$searchModel = new DeliveryNoteSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);
} }

} }

+ 64
- 69
backend/controllers/DevelopmentController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Opendistrib;
use common\logic\Development\Development\Development;
use common\logic\Development\DevelopmentPriority\DevelopmentPriority;
use Yii; use Yii;
use common\models\User;
use common\models\Development;
use common\models\DevelopmentPriority;
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\AccessControl; use yii\filters\AccessControl;


/** /**
* DeveloppementController implements the CRUD actions for Developpement model. * DeveloppementController implements the CRUD actions for Developpement model.
*/ */
class DevelopmentController extends Controller
class DevelopmentController extends BackendController
{ {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function behaviors() {
public function behaviors()
{
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend() ;
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


/** /**
* Liste les développements. * Liste les développements.
*
*
* @return mixed * @return mixed
*/ */
public function actionIndex() public function actionIndex()
{ {
$producerManager = $this->getProducerManager();
$versionsArray = Opendistrib::getVersions(); $versionsArray = Opendistrib::getVersions();
$versionsRenderArray = []; $versionsRenderArray = [];
foreach($versionsArray as $version) {
foreach ($versionsArray as $version) {
$versionsRenderArray[$version] = [ $versionsRenderArray[$version] = [
'version' => $version, 'version' => $version,
'content' => $this->renderFile('@common/versions/'.$version.'.php')
'content' => $this->renderFile('@common/versions/' . $version . '.php')
]; ];
} }


// Producer : set latest version d'Opendistrib
$producer = GlobalParam::getCurrentProducer();
$producer->updateOpendistribVersion();
$producer = $this->getProducerCurrent();
$producerManager->updateOpendistribVersion($producer);


return $this->render('index', [ return $this->render('index', [
'versionsArray' => $versionsRenderArray 'versionsArray' => $versionsRenderArray
/** /**
* Creates a new Developpement model. * Creates a new Developpement model.
* If creation is successful, the browser will be redirected to the 'view' page. * If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/ */
public function actionCreate()
public function actionCreate()
{ {
$model = new Development(); $model = new Development();


if ($model->load(Yii::$app->request->post())) {
if ($model->load(\Yii::$app->request->post())) {
$model->date = date('Y-m-d H:i:s'); $model->date = date('Y-m-d H:i:s');
$model->setDateDelivery(); $model->setDateDelivery();
if ($model->save()) { if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Développement ajouté');
$this->setFlash('success', 'Développement ajouté');
return $this->redirect(['index']); return $this->redirect(['index']);
} }
} else { } else {
/** /**
* Updates an existing Developpement model. * Updates an existing Developpement model.
* If update is successful, the browser will be redirected to the 'view' page. * If update is successful, the browser will be redirected to the 'view' page.
*
*
* @param integer $id * @param integer $id
* @return mixed * @return mixed
*/ */
public function actionUpdate($id)
public function actionUpdate($id)
{ {
$model = $this->findModel($id); $model = $this->findModel($id);


if ($model->load(Yii::$app->request->post())) {
if ($model->load(\Yii::$app->request->post())) {
$model->setDateDelivery(); $model->setDateDelivery();
if ($model->save()) { if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Développement modifié');
$this->setFlash('success', 'Développement modifié');
return $this->redirect(['index']); return $this->redirect(['index']);
} }
} else { } else {
* @param integer $id * @param integer $id
* @return mixed * @return mixed
*/ */
public function actionDelete($id)
public function actionDelete($id)
{ {
$this->findModel($id)->delete(); $this->findModel($id)->delete();
Yii::$app->getSession()->setFlash('success', 'Développement supprimé');
$this->setFlash('success', 'Développement supprimé');


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


/** /**
* Définit une priorité pour un développement. * Définit une priorité pour un développement.
*
*
* @param integer $idDevelopment * @param integer $idDevelopment
* @param string $priorite * @param string $priorite
*/ */
public function actionPriority($idDevelopment, $priority = null)
public function actionPriority($idDevelopment, $priority = null)
{ {
$develpmentPriority = DevelopmentPriority::searchOne([ $develpmentPriority = DevelopmentPriority::searchOne([
'id_development' => $idDevelopment, 'id_development' => $idDevelopment,
]) ;
]);


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


if ($develpmentPriority) { if ($develpmentPriority) {
$develpmentPriority->priority = $priority; $develpmentPriority->priority = $priority;
/** /**
* Finds the Developpement model based on its primary key value. * Finds the Developpement model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown. * If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Developpement the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/ */
protected function findModel($id)
protected function findModel($id)
{ {
if (($model = Development::findOne($id)) !== null) { if (($model = Development::findOne($id)) !== null) {
return $model; return $model;

+ 222
- 195
backend/controllers/DistributionController.php
File diff suppressed because it is too large
View File


+ 127
- 114
backend/controllers/DocumentController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\CSV; use common\helpers\CSV;
use common\helpers\Price;
use common\models\DeliveryNote;
use common\models\Invoice;
use common\models\PointSale;
use common\models\Product;
use common\models\Quotation;
use common\models\User;
use common\models\Document;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Order;
use common\models\UserProducer;
use common\helpers\Price;
use common\logic\Document\DeliveryNote\Model\DeliveryNote;
use common\logic\Document\Document\Model\Document;
use common\logic\Document\Invoice\Model\Invoice;
use common\logic\Document\Quotation\Model\Quotation;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\ProductOrder\Model\ProductOrder;
use common\logic\Product\Product\Model\Product;
use kartik\mpdf\Pdf; use kartik\mpdf\Pdf;
use yii\base\UserException; use yii\base\UserException;
use yii; use yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use yii\helpers\Html;


class DocumentController extends BackendController class DocumentController extends BackendController
{ {
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


public function actionCreate() public function actionCreate()
{ {
$documentManager = $this->getDocumentManager();

$class = $this->getClass(); $class = $this->getClass();
$class = 'common\\logic\\Document\\'.$class.'\\Model\\'.$class;
$model = new $class(); $model = new $class();
$model->initTaxCalculationMethod();


if ($model->load(Yii::$app->request->post())) {
$documentManager->initTaxCalculationMethod($model);

if ($model->load(\Yii::$app->request->post())) {
$model->id_producer = GlobalParam::getCurrentProducerId(); $model->id_producer = GlobalParam::getCurrentProducerId();


if ($model->save()) { if ($model->save()) {
$this->processInvoiceViaDeliveryNotes($model); $this->processInvoiceViaDeliveryNotes($model);


Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('create', $model));
$this->setFlash('success', $this->getFlashMessage('create', $model));
return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]); return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]);
} else { } else {
Yii::$app->getSession()->setFlash('error', 'Un problème est survenu lors de la création du document.');
$this->setFlash('error', 'Un problème est survenu lors de la création du document.');
} }
} }




public function processInvoiceViaDeliveryNotes($model) public function processInvoiceViaDeliveryNotes($model)
{ {
if ($model->getClass() == 'Invoice') {
$documentManager = $this->getDocumentManager();
if ($documentManager->getClass($model) == '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([ Order::updateAll([
$model = $this->findModel($id); $model = $this->findModel($id);


if (!$model) { if (!$model) {
throw new NotFoundHttpException('Le document n\'a pas été trouvé.');
throw new yii\web\NotFoundHttpException('Le document n\'a pas été trouvé.');
} }


if ($model && $model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('update', $model));
if ($model && $model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', $this->getFlashMessage('update', $model));
} }


return $this->render('/document/update', [ return $this->render('/document/update', [


public function actionDelete($id) public function actionDelete($id)
{ {
$documentManager = $this->getDocumentManager();

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


if ($model->isStatusValid()) {
if ($documentManager->isStatusValid($model)) {
throw new UserException('Vous ne pouvez pas supprimer un document validé.'); throw new UserException('Vous ne pouvez pas supprimer un document validé.');
} }


$model->delete();
$documentManager->delete($model);


if ($this->getClass() == 'DeliveryNote') { if ($this->getClass() == 'DeliveryNote') {
Order::updateAll([ Order::updateAll([
]); ]);
} }


Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('delete', $model));
$this->setFlash('success', $this->getFlashMessage('delete', $model));

$this->redirect([$this->getControllerUrl() . '/index']); $this->redirect([$this->getControllerUrl() . '/index']);
} }


public function actionExportCsvEvoliz($id)
public function actionExportCsvEvoliz(int $id)
{ {
$documentManager = $this->getDocumentManager();
$productOrderManager = $this->getProductOrderManager();

$datas = []; $datas = [];
$document = $this->findModel($id); $document = $this->findModel($id);


'TVA', 'TVA',
'Total TVA', 'Total TVA',
'Total HT', 'Total HT',
'Classification vente',
'Code Classification vente',
'Créateur',
]; ];


foreach ($document->getProductsOrders() as $productOrderArray) {
foreach ($documentManager->getProductsOrders($document) as $productOrderArray) {
foreach ($productOrderArray as $productOrder) { foreach ($productOrderArray as $productOrder) {


$price = $productOrder->getPrice(); $price = $productOrder->getPrice();
if ($document->isInvoicePrice() && $productOrder->getInvoicePrice()) {
if ($documentManager->isInvoicePrice($document) && $productOrder->getInvoicePrice()) {
$price = $productOrder->getInvoicePrice(); $price = $productOrder->getInvoicePrice();
} }


$typeTotal = $document->isInvoicePrice() ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL;
$priceTotal = $productOrder->getPriceByTypeTotal($typeTotal) * $productOrder->quantity;
$typeTotal = $documentManager->isInvoicePrice($document) ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL;
$priceTotal = $productOrderManager->getPriceByTypeTotal($productOrder, $typeTotal) * $productOrder->quantity;
$tva = Price::getVat( $tva = Price::getVat(
$priceTotal, $priceTotal,
$productOrder->taxRate->value, $productOrder->taxRate->value,
$productOrder->taxRate->value * 100, // TVA $productOrder->taxRate->value * 100, // TVA
$tva, // Total TVA $tva, // Total TVA
$priceTotal, // Total HT $priceTotal, // Total HT
'', // Classification vente
'01', // Code Classification vente
'', // Créateur
]; ];
} }
} }


// status // status
$status = ''; $status = '';
if ($document->isStatusDraft()) {
if ($documentManager->isStatusDraft($document)) {
$status = 'brouillon_'; $status = 'brouillon_';
} }




public function actionDownload($id) public function actionDownload($id)
{ {
$documentManager = $this->getDocumentManager();
$document = $this->findModel($id); $document = $this->findModel($id);
return $document->downloadPdf();
return $documentManager->downloadPdf($document);
} }


public function actionRegenerate($id) public function actionRegenerate($id)
{ {
$documentManager = $this->getDocumentManager();
$document = $this->findModel($id); $document = $this->findModel($id);
$document->downloadPdf(true);
Yii::$app->getSession()->setFlash('success', 'Le document PDF a bien été regénéré.');
$documentManager->downloadPdf($document, true);
$this->setFlash('success', 'Le document PDF a bien été regénéré.');

return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]); return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
} }


public function actionSend($id, $backUpdateForm = false)
public function actionSend(int $id, $backUpdateForm = false)
{ {
$documentManager = $this->getDocumentManager();
$document = $this->findModel($id); $document = $this->findModel($id);
if ($document->send()) {
if ($documentManager->send($document)) {
$document->is_sent = true; $document->is_sent = true;
$document->save(); $document->save();


Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('send', $document));
$this->setFlash('success', $this->getFlashMessage('send', $document));
} else { } else {
Yii::$app->getSession()->setFlash('danger', $this->getFlashMessage('send', $document));
$this->setFlash('danger', $this->getFlashMessage('send', $document));
} }


if ($backUpdateForm) { if ($backUpdateForm) {


public function actionAjaxUserInfos($typeAction, $idUser, $classDocument, $idDocument = false) public function actionAjaxUserInfos($typeAction, $idUser, $classDocument, $idDocument = false)
{ {
$userManager = $this->getUserManager();
$documentManager = $this->getDocumentManager();

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


if ($idUser > 0) { if ($idUser > 0) {
$user = User::searchOne([
'id' => $idUser
]);
$user = $userManager->findOneUserById($idUser);


if ($user) { if ($user) {
$document = null; $document = null;
if (Document::isValidClass($classDocument)) {
$document = $classDocument::searchOne([
'id' => $idDocument,
'id_user' => $idUser
]);
if ($documentManager->isValidClass($classDocument) && $idDocument) {
$document = $this->findModel($idDocument, $classDocument);
} }


if ($document && $document->id_user == $user->id) { if ($document && $document->id_user == $user->id) {
$address = $document->address; $address = $document->address;
} else { } else {
$address = $user->getFullAddress();
$address = $userManager->getFullAddress($user);
} }


$json = [ $json = [


public function addDeliveryNoteToArray($deliveryNote, $isCreate = true) public function addDeliveryNoteToArray($deliveryNote, $isCreate = true)
{ {
$deliveryNoteManager = $this->getDeliveryNoteManager();

$deliveryNoteData = array_merge( $deliveryNoteData = array_merge(
$deliveryNote->getAttributes(), $deliveryNote->getAttributes(),
[ [
'url' => Yii::$app->urlManager->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
'total' => $deliveryNote->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL)
'url' => $this->getUrlManagerBackend()->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
'total' => $deliveryNoteManager->getAmountWithTax($deliveryNote, Order::INVOICE_AMOUNT_TOTAL)
] ]
); );


if (($isCreate && !$deliveryNote->isInvoiced()) || !$isCreate) {
if (($isCreate && !$deliveryNoteManager->isInvoiced($deliveryNote)) || !$isCreate) {
return $deliveryNoteData; return $deliveryNoteData;
} }




public function actionValidate($id, $backUpdateForm = false) public function actionValidate($id, $backUpdateForm = false)
{ {
$documentManager = $this->getDocumentManager();
$classDocument = $this->getClass(); $classDocument = $this->getClass();


if ($id > 0 && Document::isValidClass($classDocument)) {
$document = $classDocument::searchOne([
'id' => $id
]);
if ($id > 0 && $documentManager->isValidClass($classDocument)) {
$document = $this->findModel($id);


if ($document) { if ($document) {
$document->changeStatus(Document::STATUS_VALID);
$document->save();
$documentManager->changeStatus($document,Document::STATUS_VALID);
$documentManager->saveUpdate($document);


// génération PDF // génération PDF
$document->generatePdf(Pdf::DEST_FILE);
$documentManager->generatePdf($document, Pdf::DEST_FILE);


Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('validate', $document));
$this->setFlash('success', $this->getFlashMessage('validate', $document));


if ($backUpdateForm) { if ($backUpdateForm) {
return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]); return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
} }
} }


Yii::$app->getSession()->setFlash('danger', 'Une erreur est survenue lors de la validation du document.');
$this->setFlash('danger', 'Une erreur est survenue lors de la validation du document.');

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


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


if ($idDocument > 0 && Document::isValidClass($classDocument)) {
$documentManager = $this->getDocumentManager();

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


if ($document) { if ($document) {
$document->changeStatus(Document::STATUS_VALID);
$document->save();
$documentManager->changeStatus($document,Document::STATUS_VALID);
$documentManager->saveUpdate($document);

return [ return [
'return' => 'success', 'return' => 'success',
'alert' => [ 'alert' => [
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


if ($idDocument > 0 && Document::isValidClass($classDocument)) {
$document = $classDocument::searchOne([
'id' => $idDocument
]);
$orderManager = $this->getOrderManager();
$productManager = $this->getProductManager();
$documentManager = $this->getDocumentManager();
$deliveryNoteManager = $this->getDeliveryNoteManager();
$userProducerManager = $this->getUserProducerManager();
$pointSaleManager = $this->getPointSaleManager();


if ($document) {
$productsArray = Product::searchAll([], [
'orderby' => 'product.order ASC'
]);
if ($idDocument > 0 && $documentManager->isValidClass($classDocument)) {


$document = $this->findModel($idDocument, $classDocument);

if ($document) {
$ordersArray = []; $ordersArray = [];
$productsArray = $productManager->findProducts();

foreach ($document->orders as $order) { foreach ($document->orders as $order) {
$order->init();
$orderManager->initOrder($order);
$productsOrderArray = []; $productsOrderArray = [];

foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$productsOrderArray[$productOrder->id] = array_merge($productOrder->getAttributes(), [ $productsOrderArray[$productOrder->id] = array_merge($productOrder->getAttributes(), [
'url_order' => Yii::$app->urlManager->createUrl(['distribution/index', 'idOrderUpdate' => $productOrder->id_order])
'url_order' => $this->getUrlManagerBackend()->createUrl(['distribution/index', 'idOrderUpdate' => $productOrder->id_order])
]); ]);
} }
$ordersArray[$order->id] = array_merge( $ordersArray[$order->id] = array_merge(
$order->getAttributes(), $order->getAttributes(),
[ [
'username' => $order->getUsername(),
'username' => $orderManager->getOrderUsername($order),
'distribution_date' => isset($order->distribution) ? date( 'distribution_date' => isset($order->distribution) ? date(
'd/m/Y', 'd/m/Y',
strtotime( strtotime(
); );
} }


$userProducer = UserProducer::searchOne([
'id_user' => $document->user->id,
'id_producer' => GlobalParam::getCurrentProducerId()
]);
$pointSale = PointSale::searchOne([
'id_user' => $document->user->id
]);
$userProducer = $userProducerManager->findOneUserProducer($document->user, $this->getProducerCurrent());
$pointSale = $pointSaleManager->findOnePointSaleByIdUser($document->user->id);


$productsArray = yii\helpers\ArrayHelper::map( $productsArray = yii\helpers\ArrayHelper::map(
$productsArray, $productsArray,
'order', 'order',
function ($product) use ($document, $userProducer, $pointSale) {
function ($product) use ($document, $userProducer, $pointSale, $productManager) {
return array_merge($product->getAttributes(), [ return array_merge($product->getAttributes(), [
'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'], 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
'prices' => $product->getPriceArray($userProducer->user, $pointSale),
'prices' => $productManager->getPriceArray($product, $userProducer->user, $pointSale),
'wording_unit' => $product->wording_unit, 'wording_unit' => $product->wording_unit,
'tax_rate' => $product->taxRate->value 'tax_rate' => $product->taxRate->value
]); ]);
'return' => 'success', 'return' => 'success',
'tax_rate_producer' => GlobalParam::getCurrentProducer()->taxRate->value, 'tax_rate_producer' => GlobalParam::getCurrentProducer()->taxRate->value,
'document' => array_merge($document->getAttributes(), [ 'document' => array_merge($document->getAttributes(), [
'html_label' => $document->getHtmlLabel(),
'class' => $document->getClass()
'html_label' => $documentManager->getHtmlLabel($document),
'class' => $documentManager->getClass($document)
]), ]),
'id_user' => $document->user->id, 'id_user' => $document->user->id,
'products' => $productsArray, 'products' => $productsArray,
'orders' => $ordersArray, 'orders' => $ordersArray,
'total' => ($document->getClass() == 'Invoice' || $document->getClass() == 'DeliveryNote') ? $document->getAmount(
'total' => ($documentManager->getClass($document) == 'Invoice' || $documentManager->getClass($document) == 'DeliveryNote') ? $documentManager->getAmount(
$document,
Order::INVOICE_AMOUNT_TOTAL Order::INVOICE_AMOUNT_TOTAL
) : $document->getAmount(Order::AMOUNT_TOTAL),
'total_with_tax' => ($document->getClass() == 'Invoice' || $document->getClass() == 'DeliveryNote') ? $document->getAmountWithTax(
) : $documentManager->getAmount($document, Order::AMOUNT_TOTAL),
'total_with_tax' => ($documentManager->getClass($document) == 'Invoice' || $documentManager->getClass($document) == 'DeliveryNote') ? $documentManager->getAmountWithTax(
$document,
Order::INVOICE_AMOUNT_TOTAL Order::INVOICE_AMOUNT_TOTAL
) : $document->getAmountWithTax(Order::AMOUNT_TOTAL),
'invoice_url' => ($document->getClass() == 'DeliveryNote' && $document->getInvoice()) ? Yii::$app->urlManager->createUrl(['invoice/update', 'id' => $document->getInvoice()->id]) : null
) : $documentManager->getAmountWithTax($document, Order::AMOUNT_TOTAL),
'invoice_url' => ($documentManager->getClass($document) == 'DeliveryNote' && $deliveryNoteManager->getInvoice($document)) ? $this->getUrlManagerBackend()->createUrl(['invoice/update', 'id' => $deliveryNoteManager->getInvoice($document)->id]) : null
]; ];
} }
} }
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


if (Document::isValidClass($classDocument)) {
$document = $classDocument::searchOne([
'id' => $idDocument
]);
$product = Product::searchOne([
'id' => $idProduct
]);
$documentManager = $this->getDocumentManager();
$productManager = $this->getProductManager();

if ($documentManager->isValidClass($classDocument)) {
$document = $this->findModel($idDocument, $classDocument);
$product = $productManager->findOneProductById($idProduct);


if ($document && $product) { if ($document && $product) {
if (count($document->orders) == 0) { if (count($document->orders) == 0) {
} }


if ($order) { if ($order) {
$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 / Product::$unitsArray[$product->unit]['coefficient'];
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$productOrder = ProductOrder::searchOne([
'id' => $idProductOrder
]);
$productOrderManager = $this->getProductOrderManager();
$productOrder = $productOrderManager->findOneProductOrderById($idProductOrder);


if ($productOrder) { if ($productOrder) {
$productOrder->delete();
$productOrderManager->delete($productOrder);


return [ return [
'return' => 'success', 'return' => 'success',
return ''; return '';
} }


public function getFlashMessage($type = 'create', $model)
public function getFlashMessage(string $type, $model)
{ {
$class = $this->getClass(); $class = $this->getClass();


* @return Document * @return Document
* @throws NotFoundHttpException si le modèle n'est pas trouvé * @throws NotFoundHttpException si le modèle n'est pas trouvé
*/ */
protected function findModel($id)
protected function findModel($idDocument, $classDocument = null)
{ {
$class = $this->getClass();

$model = $class::searchOne([
'id' => $id
], [
'orderby' => 'teshtygjhtyt'
]);
$documentManager = $this->getDocumentManager();
$model = $documentManager->findOneDocumentByIdAndClass($idDocument, $classDocument ?? $this->getClass());


if ($model) { if ($model) {
return $model; return $model;
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
} }
} }

} }

+ 55
- 55
backend/controllers/InvoiceController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\models\Order;
use Yii;
use common\logic\Document\Invoice\Model\InvoiceSearch;
use common\logic\Order\Order\Model\Order;



class InvoiceController extends DocumentController
class InvoiceController extends DocumentController
{ {
/** /**
* Liste les modèles Invoice.
*
* @return mixed
* Liste les factures
*/ */
public function actionIndex()
public function actionIndex()
{ {
$searchModel = new InvoiceSearch() ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$searchModel = new InvoiceSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$invoice = Invoice::searchOne(['id' => $idInvoice]);
$invoiceManager = $this->getInvoiceManager();

$invoice = $invoiceManager->findOneInvoiceById($idInvoice);


if($invoice && $invoice->isStatusDraft()) {
if ($invoice && $invoice->isStatusDraft()) {
Order::updateAll([ Order::updateAll([
'id_invoice' => null 'id_invoice' => null
], [ ], [
'message' => 'Bon de livraison supprimé de la facture.' 'message' => 'Bon de livraison supprimé de la facture.'
] ]
]; ];
}
else {
} else {
return [ return [
'alert' => [ 'alert' => [
'type' => 'error', 'type' => 'error',
{ {
\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]);
$invoiceManager = $this->getInvoiceManager();
$deliveryNoteManager = $this->getDeliveryNoteManager();

$invoice = $invoiceManager->findOneInvoiceById($idInvoice);
$deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById($idDeliveryNote);


if($invoice && $invoice->isStatusDraft() && $deliveryNote) {
if ($invoice && $invoiceManager->isStatusDraft($invoice) && $deliveryNote) {
Order::updateAll([ Order::updateAll([
'id_invoice' => $idInvoice 'id_invoice' => $idInvoice
], [ ], [
'message' => 'Bon de livraison ajouté à la facture.' 'message' => 'Bon de livraison ajouté à la facture.'
] ]
]; ];
}
else {
} else {
return [ return [
'alert' => [ 'alert' => [
'type' => 'error', 'type' => 'error',

+ 195
- 233
backend/controllers/OrderController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\forms\SubscriptionForm;
use common\helpers\CSV;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\CreditHistory;
use common\models\Order;
use common\models\ProductOrder;
use common\models\Product;
use common\models\User;
use common\models\ProductDistribution;
use common\models\Distribution;
use common\models\Producer;
use common\models\UserProducer;
use common\helpers\MeanPayment;
use common\helpers\Price;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Distribution\PointSaleDistribution\Model\PointSaleDistribution;
use common\logic\Distribution\ProductDistribution\Model\ProductDistribution;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\ProductOrder\Model\ProductOrder;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Product\Product\Model\Product;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\logic\User\User\Model\User;
use common\logic\User\UserProducer\Model\UserProducer;
use yii\filters\AccessControl;
use yii\helpers\Html;


class OrderController extends BackendController class OrderController extends BackendController
{ {
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == USER::STATUS_ADMIN
|| User::getCurrentStatus() == USER::STATUS_PRODUCER;
return $this->getUserManager()->isCurrentProducer()
|| $this->getUserManager()->isCurrentAdmin();
} }
] ]
], ],


/** /**
* Traite le formulaire d'ajout/modification de commande. * Traite le formulaire d'ajout/modification de commande.
*
* @param Distribution $distribution
* @param string $date
* @param array $points_vente
* @param array $produits
* @param array $users
*/ */
public function processOrderForm( public function processOrderForm(
$distribution, $date, $pointsSale, $products, $users)
Distribution $distribution,
string $date,
array $pointsSale,
array $products,
array $users
)
{ {
$orderManager = $this->getOrderManager();
$pointSaleManager = $this->getPointSaleManager();

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


foreach ($pointsSale as $point) { foreach ($pointsSale as $point) {
$point->initOrders($orders);
$orderManager->initPointSaleOrders($point, $orders);


if (isset($_POST['submit_pv']) && $_POST['submit_pv']) { if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
// modifs // modifs


// création des commande_produit modifiés // création des commande_produit modifiés
foreach ($products as $product) { foreach ($products as $product) {
$quantity = Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
$quantity = \Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
if ($quantity) { if ($quantity) {
$productOrder = new ProductOrder; $productOrder = new ProductOrder;
$productOrder->id_order = $order->id; $productOrder->id_order = $order->id;
} }
} }


$username = Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
$date = Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
$username = \Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
$date = \Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
$oneProduct = false; $oneProduct = false;
foreach ($products as $product) { foreach ($products as $product) {
$quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
$quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
if ($quantity) { if ($quantity) {
$oneProduct = true; $oneProduct = true;
} }
} }


if (strlen($username) && $date && $oneProduct) { if (strlen($username) && $date && $oneProduct) {
$order = new Order;
$order = new Order();
$order->id_point_sale = $point->id; $order->id_point_sale = $point->id;
$order->id_production = $distribution->id; $order->id_production = $distribution->id;
$order->id_user = 0; $order->id_user = 0;
$order->save(); $order->save();


foreach ($products as $product) { foreach ($products as $product) {
$quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
$quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
if ($quantity) { if ($quantity) {
$productOrder = new ProductOrder;
$productOrder = new ProductOrder();
$productOrder->id_order = $order->id; $productOrder->id_order = $order->id;
$productOrder->id_product = $product->id; $productOrder->id_product = $product->id;
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
} }
} }


$order->initReference();
$orderManager->generateOrderReference($order);
} }
} }
} }


/** /**
* Page principale de la gestion des commandes. * Page principale de la gestion des commandes.
*
* @param string $date
* @param boolean $returnData
* @return string
*/ */
public function actionIndex($date = '', $returnData = false) public function actionIndex($date = '', $returnData = false)
{ {
$distributionManager = $this->getDistributionManager();
$productManager = $this->getProductManager();
$pointSaleManager = $this->getPointSaleManager();
$orderManager = $this->getOrderManager();
$productDistributionManager = $this->getProductDistributionManager();

if (!Product::searchCount() || !PointSale::searchCount()) { if (!Product::searchCount() || !PointSale::searchCount()) {
$this->redirect(['site/index', 'error_products_points_sale' => 1]); $this->redirect(['site/index', 'error_products_points_sale' => 1]);
} }
$arrayUsers[$user->id] = $user->name . ' ' . $user->lastname; $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
} }


// création du jour de distribution
$distribution = Distribution::initDistribution($date);
$distribution = $distributionManager->createDistributionIfNotExist($date);


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


// produits
$arrayProducts = Product::searchAll();
$arrayProducts = $productManager->findProducts();


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


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

$arrayOrders = $orderManager->findOrdersByDistribution($distribution);
$revenues = 0; $revenues = 0;
$weight = 0; $weight = 0;
$revenuesDelivered = 0; $revenuesDelivered = 0;


// init commandes point de vente // init commandes point de vente
foreach ($arrayPointsSale as $pointSale) { foreach ($arrayPointsSale as $pointSale) {
$pointSale->initOrders($arrayOrders);
$orderManager->initPointSaleOrders($pointSale, $arrayOrders);


$dataSelectOrders = []; $dataSelectOrders = [];
$dataOptionsOrders = []; $dataOptionsOrders = [];
if (isset($_POST['Product'])) { if (isset($_POST['Product'])) {


foreach ($arrayProducts as $product) { foreach ($arrayProducts as $product) {
$productDistribution = ProductDistribution::searchOne([
'id_distribution' => $distribution->id,
'id_product' => $product->id
]);

$productDistribution = $productDistributionManager->findOneProductDistribution($distribution, $product);


if (!$productDistribution) { if (!$productDistribution) {
$productDistribution = new ProductDistribution(); $productDistribution = new ProductDistribution();
$productDistribution->quantity_max = null; $productDistribution->quantity_max = null;
} }



$productDistribution->save();
$productDistributionManager->saveCreate($productDistribution);
} }


if (isset($_POST['Product'][$product->id]['active'])) { if (isset($_POST['Product'][$product->id]['active'])) {
$productDistribution->quantity_max = null; $productDistribution->quantity_max = null;
} }


$productDistribution->save();
$productDistributionManager->saveUpdate($productDistribution);
} }
} }
} }


$arrayProductsSelected = []; $arrayProductsSelected = [];
if ($distribution) { if ($distribution) {
// produits selec pour production
$arrayProductsSelected = ProductDistribution::searchByDistribution($distribution->id);
}

// produits
if ($distribution) {
$arrayProducts = Product::searchByDistribution($distribution->id);
$arrayProductsSelected = $productDistributionManager->findProductDistributionsByDistribution($distribution);
$arrayProducts = $productManager->findProductsByDistribution($distribution);
} }


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


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


// commandes auto // commandes auto
$subscriptionForm = new SubscriptionForm;
$subscriptionForm = new SubscriptionForm();


// productions point vente // productions point vente
$pointSaleDistribution = new PointSaleDistribution;

$pointSaleDistribution = new PointSaleDistribution();
$oointsSaleDistribution = []; $oointsSaleDistribution = [];


if ($distribution) { if ($distribution) {
*/ */
public function actionDownload($date = '', $idPointSale = 0, $global = 0) public function actionDownload($date = '', $idPointSale = 0, $global = 0)
{ {
// commandes
$ordersArray = Order::searchAll([
'distribution.date' => $date
]);

// points de vente
$pointsSaleArray = PointSale::searchAll();
$orderManager = $this->getOrderManager();
$distributionManager = $this->getDistributionManager();
$pointSaleManager = $this->getPointSaleManager();
$productManager = $this->getProductManager();
$productDistributionManager = $this->getProductDistributionManager();

$distribution = $distributionManager->findOneDistributionByDate($date);
$selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
$productsArray = $productManager->findProducts();
$ordersArray = $orderManager->findOrdersByDate($date);

$pointsSaleArray = $pointSaleManager->findPointSales();
foreach ($pointsSaleArray as $pointSale) { foreach ($pointsSaleArray as $pointSale) {
$pv->initOrders($ordersArray);
$pointSaleManager->initOrders($pointSale, $ordersArray);
} }


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

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

$selectedProductsArray = ProductDistribution::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 = $orderManager->getProductQuantity($product, $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 = $orderManager->getProductQuantity($product, $ordersArray);
$strQuantity = ''; $strQuantity = '';
if ($quantity) { if ($quantity) {
$strQuantity = $quantity; $strQuantity = $quantity;
* @return array * @return array
* @see OrderController::actionDownload() * @see OrderController::actionDownload()
*/ */
public function contentRecapCSV($date, $products, $pointsSale, $orders)
public function contentRecapCSV(string $date, array $products, array $pointsSale, array $orders)
{ {
$orderManager = $this->getOrderManager();
$distributionManager = $this->getDistributionManager();
$productDistributionManager = $this->getProductDistributionManager();

$data = []; $data = [];
$filename = 'summary_' . $date; $filename = 'summary_' . $date;


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

$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$distribution = $distributionManager->findOneDistributionByDate($date);
$selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);


// 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[] = $orderManager->getProductQuantity($product, $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[] = $orderManager->getProductQuantity($product, $orders);
} }
} }
$data[] = $dataAdd; $data[] = $dataAdd;
*/ */
public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale) public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
{ {
$data = [];
$distributionManager = $this->getDistributionManager();
$productDistributionManager = $this->getProductDistributionManager();


$distribution = Distribution::find()->where('date LIKE \':date\'')->params([':date' => $date])->one();
$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$data = [];
$distribution = $distributionManager->findOneDistributionByDate($date);
$selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);


// datas // datas
foreach ($pointsSale as $pointSale) { foreach ($pointsSale as $pointSale) {
} }


/** /**
* Change l'état d'un jour de production (activé, désactivé).
*
* @param string $date
* @param integer $actif
* @param boolean $redirect
* Change l'état d'un jour de distribution (activé, désactivé).
*/ */
public function actionChangeState($date, $active, $redirect = true)
public function actionChangeState(string $date, bool $active, bool $redirect = true)
{ {
// changement état
$distribution = Distribution::initDistribution($date);
$distribution->active = $active;
$distribution->save();

if ($active) {
// add commandes automatiques
Subscription::addAll($date);
}
$distributionManager = $this->getDistributionManager();
$distribution = $distributionManager->createDistributionIfNotExist($date);
$distributionManager->activeDistribution($distribution, $active);


if ($redirect) { if ($redirect) {
$this->redirect(['index', 'date' => $date]); $this->redirect(['index', 'date' => $date]);


/** /**
* Change l'état d'une semaine de production (activé, désactivé). * Change l'état d'une semaine de production (activé, désactivé).
*
* @param string $date
* @param integer $actif
*/ */
public function actionChangeStateWeek($date, $active)
public function actionChangeStateWeek(string $date, bool $active)
{ {
$pointSaleManager = $this->getPointSaleManager();

$pointsSaleArray = $pointSaleManager->findPointSales();

$week = sprintf('%02d', date('W', strtotime($date))); $week = sprintf('%02d', date('W', strtotime($date)));
$start = strtotime(date('Y', strtotime($date)) . 'W' . $week); $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
$dateMonday = date('Y-m-d', strtotime('Monday', $start)); $dateMonday = date('Y-m-d', strtotime('Monday', $start));
$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();

$activeMonday = false; $activeMonday = false;
$activeTuesday = false; $activeTuesday = false;
$activeWednesday = false; $activeWednesday = false;


/** /**
* Supprime une commande via une requête AJAX. * Supprime une commande via une requête AJAX.
*
* @param string $date
* @param integer $idOrder
*/ */
public function actionAjaxDelete($idOrder)
public function actionAjaxDelete(int $idOrder)
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
'id' => $idOrder
]);
$orderManager = $this->getOrderManager();


// delete
$order = $orderManager->findOneOrderById($idOrder);
if ($order) { if ($order) {
$order->delete();
$orderManager->deleteOrder($order);
} }


return ['success']; return ['success'];


/** /**
* Supprime une commande. * Supprime une commande.
*
* @param string $date
* @param integer $idOrder
*/ */
public function actionDelete($date, $idOrder)
public function actionDelete(string $date, int $idOrder)
{ {
$order = Order::searchOne(['id' => $idOrder]);
$orderManager = $this->getOrderManager();
$order = $orderManager->findOneOrderById($idOrder);
if ($order) { if ($order) {

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

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


$this->redirect(['index', 'date' => $date]); $this->redirect(['index', 'date' => $date]);
* @param string $username * @param string $username
* @param array $produits * @param array $produits
* @param string $commentaire * @param string $commentaire
* @param string $processCredit
*/ */
public function actionAjaxCreate( public function actionAjaxCreate(
$date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment) $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment)
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$distributionManager = $this->getDistributionManager();
$pointSaleManager = $this->getPointSaleManager();
$userPointSaleManager = $this->getUserPointSaleManager();
$userManager = $this->getUserManager();
$userProducerManager = $this->getUserProducerManager();
$producerManager = $this->getProducerManager();
$productManager = $this->getProductManager();
$orderManager = $this->getOrderManager();

$products = json_decode($products); $products = json_decode($products);
$pointSale = PointSale::findOne($idPointSale);
$distribution = Distribution::searchOne([
'date' => $date
]);
$pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
$distribution = $distributionManager->findOneDistributionByDate($date);
$producerCurrent = $this->getProducerCurrent();


if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) &&
($idUser || strlen($username)) &&
$pointSale &&
count(get_object_vars($products)) &&
$distribution) {
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
&& ($idUser || strlen($username))
&& $pointSale
&& count(get_object_vars($products))
&& $distribution) {


$order = new Order; $order = new Order;
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
$order->id_user = $idUser; $order->id_user = $idUser;


// commentaire du point de vente // commentaire du point de vente
$userPointSale = UserPointSale::searchOne([
'id_point_sale' => $idPointSale,
'id_user' => $idUser
]);
$userPointSale = $userPointSaleManager->findOneUserPointSale($userManager->findOneUserById($idUser), $pointSale);


if ($userPointSale && strlen($userPointSale->comment)) { if ($userPointSale && strlen($userPointSale->comment)) {
$order->comment_point_sale = $userPointSale->comment; $order->comment_point_sale = $userPointSale->comment;
$userProducer = false; $userProducer = false;
if (isset($order->user) && $order->user) { if (isset($order->user) && $order->user) {
$user = $order->user; $user = $order->user;
$userProducer = UserProducer::searchOne([
'id_user' => $user->id,
'id_producer' => $order->distribution->id_producer
]);

$userProducer = $userProducerManager->findOneUserProducer(
$user,
$producerManager->findOneProducerById($order->distribution->id_producer)
);
} }


foreach ($products as $key => $dataProductOrder) { foreach ($products as $key => $dataProductOrder) {
$product = Product::findOne($key);
$product = $productManager->findOneProductById($key);
$quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient']; $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
if ($product && $quantity) { if ($product && $quantity) {
$productOrder = new ProductOrder; $productOrder = new ProductOrder;
if ($dataProductOrder->price) { if ($dataProductOrder->price) {
$productOrder->price = $dataProductOrder->price; $productOrder->price = $dataProductOrder->price;
} else { } else {
$productOrder->price = $product->getPrice([
$productOrder->price = $productManager->getPrice($product, [
'user' => $user, 'user' => $user,
'user_producer' => $userProducer, 'user_producer' => $userProducer,
'point_sale' => $order->pointSale, 'point_sale' => $order->pointSale,
} }
} }


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


if ($order) { if ($order) {
$order->initReference();
$order->setTillerSynchronization();
$orderManager->generateOrderReference($order);
$orderManager->updateOrderTillerSynchronization($order);
} }


// lien utilisateur / point de vente // lien utilisateur / point de vente
if ($idUser && $pointSale) { if ($idUser && $pointSale) {
$pointSale->linkUser($idUser);
$pointSaleManager->addUser($user, $pointSale);
} }
} }


*/ */
public function actionAjaxUpdate() public function actionAjaxUpdate()
{ {
$request = Yii::$app->request;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$orderManager = $this->getOrderManager();
$userManager = $this->getUserManager();
$pointSaleManager = $this->getPointSaleManager();
$userPointSaleManager = $this->getUserPointSaleManager();
$creditHistoryManager = $this->getCreditHistoryManager();


$request = \Yii::$app->request;
$date = $request->post('date'); $date = $request->post('date');
$idOrder = $request->post('idOrder'); $idOrder = $request->post('idOrder');
$idPointSale = $request->post('idPointSale'); $idPointSale = $request->post('idPointSale');
$meanPayment = $request->post('meanPayment'); $meanPayment = $request->post('meanPayment');
$products = $request->post('products'); $products = $request->post('products');
$comment = $request->post('comment'); $comment = $request->post('comment');
$processCredit = $request->post('processCredit');

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


$order = Order::searchOne(['id' => $idOrder]);
$order = $orderManager->findOneOrderById($idOrder);
$user = $userManager->findOneUserById($idUser);
$pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);


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


$oldIdUser = $order->id_user; $oldIdUser = $order->id_user;
$oldUser = $userManager->findOneUserById($oldIdUser);
if ($idUser) { if ($idUser) {
$order->username = ''; $order->username = '';
$order->id_user = $idUser; $order->id_user = $idUser;


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

$userPointSale = $userPointSaleManager->findOneUserPointSale($user, $pointSale);
if ($userPointSale && strlen($userPointSale->comment)) { if ($userPointSale && strlen($userPointSale->comment)) {
$order->comment_point_sale = $userPointSale->comment; $order->comment_point_sale = $userPointSale->comment;
} }
if ($productOrder) { if ($productOrder) {
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
$productOrder->price = $dataProductOrder->price; $productOrder->price = $dataProductOrder->price;

if($dataProductOrder->invoice_price && $dataProductOrder->invoice_price != $dataProductOrder->price) {
//die('invoice price : '.$dataProductOrder->invoice_price);
$productOrder->invoice_price = $dataProductOrder->invoice_price;
}
} else { } else {
$product = Product::findOne($key); $product = Product::findOne($key);


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


$order = Order::searchOne(['id' => $order->id]); $order = Order::searchOne(['id' => $order->id]);
if($order && $order->isCreditAutoPayment()) {
$orderManager->initOrder($order);
if ($order && $orderManager->isCreditAutoPayment($order)) {
// Si changement d'user : on rembourse l'ancien user // Si changement d'user : on rembourse l'ancien user
$amountPaid = $order->getAmount(Order::AMOUNT_PAID);
if($oldIdUser != $idUser && $amountPaid > 0) {
$order->saveCreditHistory(
$amountPaid = $orderManager->getOrderAmount($order, Order::AMOUNT_PAID);
if ($oldIdUser != $idUser && $amountPaid > 0) {
$creditHistoryManager->createCreditHistory(
CreditHistory::TYPE_REFUND, CreditHistory::TYPE_REFUND,
$amountPaid, $amountPaid,
GlobalParam::getCurrentProducerId(),
$oldIdUser,
User::getCurrentId()
$this->getProducerCurrent(),
$oldUser,
$this->getUserCurrent()
); );
$order = Order::searchOne(['id' => $order->id]); $order = Order::searchOne(['id' => $order->id]);
$orderManager->initOrder($order);
} }


$order->processCredit();
$orderManager->processCredit($order);
} }
} }
} }



/** /**
* Retourne l'état du paiement (historique, crédit) d'une commande donnée. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
*
* @param integer $idOrder
*/ */
public function actionPaymentStatus($idOrder)
public function actionPaymentStatus(int $idOrder)
{ {
$order = Order::searchOne(['id' => $idOrder]);
$orderManager = $this->getOrderManager();
$creditHistoryManager = $this->getCreditHistoryManager();

$order = $orderManager->findOneOrderById($idOrder);


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


$amountPaid = $order->getAmount(Order::AMOUNT_PAID);
$amountPaid = $orderManager->getOrderAmount($order, Order::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 ' . $orderManager->getOrderAmountWithTax($order, Order::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';
. '<tbody>'; . '<tbody>';


if ($history && is_array($history) && count($history)) { if ($history && is_array($history) && count($history)) {
foreach ($history as $h) {
foreach ($history as $creditHistory) {
$html .= '<tr>' $html .= '<tr>'
. '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
. '<td>' . Html::encode($h->strUserAction()) . '</td>'
. '<td>' . $h->getStrWording() . '</td>'
. '<td>' . ($h->isTypeDebit() ? '- ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($h->isTypeCredit() ? '+ ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryManager->getDate($creditHistory))) . '</td>'
. '<td>' . Html::encode($creditHistoryManager->getStrUserAction($creditHistory)) . '</td>'
. '<td>' . $creditHistoryManager->getStrWording($creditHistory) . '</td>'
. '<td>' . ($creditHistoryManager->isTypeDebit($creditHistory) ? '- ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
. '<td>' . ($creditHistoryManager->isTypeCredit($creditHistory) ? '+ ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
. '</tr>'; . '</tr>';
} }
} else { } else {


/** /**
* Effectue le paiement/remboursement d'une commande. * Effectue le paiement/remboursement d'une commande.
*
* @param integer $idOrder
* @param string $type
* @param float $amount
* @return string
*/ */
public function actionAjaxPayment($idOrder, $type, $amount)
public function actionAjaxPayment(int $idOrder, string $type, float $amount): array
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
'id' => $idOrder
]);
$orderManager = $this->getOrderManager();
$creditHistoryManager = $this->getCreditHistoryManager();

$order = $orderManager->findOneOrderById($idOrder);


if ($order) { if ($order) {
$order->saveCreditHistory(
$creditHistoryManager->createCreditHistory(
$type, $type,
$amount, $amount,
GlobalParam::getCurrentProducerId(),
$order->id_user,
User::getCurrentId()
GlobalParam::getCurrentProducer(),
$order->user,
GlobalParam::getCurrentUser(),
MeanPayment::CREDIT,
$order
); );
} }




/** /**
* Modifie l'état de la synchronisation Tiller d'une commande. * Modifie l'état de la synchronisation Tiller d'une commande.
*
* @param int $idOrder
* @param boolean $boolSynchroTiller
* @return array
*/ */
public function actionAjaxChangeSynchroTiller($idOrder, $boolSynchroTiller)
public function actionAjaxChangeSynchroTiller(int $idOrder, bool $boolSynchroTiller): array
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
'id' => (int)$idOrder
]);
$orderManager = $this->getOrderManager();


$order = $orderManager->findOneOrderById($idOrder);
if ($order) { if ($order) {
$order->tiller_synchronization = (int)$boolSynchroTiller;
$res = $order->save();
$orderManager->updateOrderTillerSynchronization($order, (int) $boolSynchroTiller);
return ['success']; return ['success'];
} }



+ 119
- 127
backend/controllers/PointSaleController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam;
use common\logic\Distribution\PointSaleDistribution\Model\PointSaleDistribution;
use common\logic\Order\Order\Model\Order;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\PointSale\PointSale\Model\PointSaleSearch;
use common\logic\PointSale\UserPointSale\Model\UserPointSale;
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\User;
use common\models\UserPointSale;
use common\models\Order ;
use common\models\Producer ;
use common\models\Distribution ;
use yii\helpers\Html; use yii\helpers\Html;


/**
* PointVenteController implements the CRUD actions for PointVente model.
*/
class PointSaleController extends BackendController
class PointSaleController extends BackendController
{ {

public function behaviors()
public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
], ],


/** /**
* Liste les points de vente. * Liste les points de vente.
*
* @return mixed
*/ */
public function actionIndex()
{
$searchModel = new PointSaleSearch() ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
public function actionIndex()
{
$searchModel = new PointSaleSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);


return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);
} }


/** /**
* Crée un point de vente. * Crée un point de vente.
*
*
* @return mixed * @return mixed
*/ */
public function actionCreate()
public function actionCreate()
{ {
$model = new PointSale();
$pointSaleManager = $this->getPointSaleManager();
$distributionManager = $this->getDistributionManager();

$pointSale = $pointSaleManager->instanciatePointSale();

if ($pointSale->load(\Yii::$app->request->post()) && $pointSale->save()) {
$pointSaleManager->updatePointSalePointProduction($pointSale);
$pointSaleManager->processRestrictedAccess($pointSale);
$distributionManager->addPointSaleIncomingDistributions($pointSale);


if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->processPointProduction();
$model->processRestrictedAccess();
Distribution::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(), [
'model' => $model,
'model' => $pointSale,
])); ]));
} }
} }


/** /**
* Modifie un point de vente. * Modifie un point de vente.
*
* @param integer $id
* @return mixed
*/ */
public function actionUpdate($id)
public function actionUpdate(int $id)
{ {
$distributionManager = $this->getDistributionManager();
$pointSaleManager = $this->getPointSaleManager();

$model = PointSale::find() $model = PointSale::find()
->with('userPointSale')
->where(['id' => $id])
->one();
->with('userPointSale')
->where(['id' => $id])
->one();


foreach ($model->userPointSale as $userPointSale) { foreach ($model->userPointSale as $userPointSale) {
$model->users[] = $userPointSale->id_user; $model->users[] = $userPointSale->id_user;
$model->users_comment[$userPointSale->id_user] = $userPointSale->comment; $model->users_comment[$userPointSale->id_user] = $userPointSale->comment;
} }


if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->processPointProduction();
$model->processRestrictedAccess();
Distribution::linkPointSaleIncomingDistributions($model) ;
Yii::$app->getSession()->setFlash('success', 'Point de vente modifié.');
if ($model->load(\Yii::$app->request->post()) && $model->save()) {

$pointSaleManager->updatePointSalePointProduction($model);
$pointSaleManager->processRestrictedAccess($model);
$distributionManager->addPointSaleIncomingDistributions($model);

$this->setFlash('success', 'Point de vente modifié.');

return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
return $this->render('update', array_merge($this->initForm($id), [ return $this->render('update', array_merge($this->initForm($id), [


/** /**
* Initialise le formulaire de création/modification. * Initialise le formulaire de création/modification.
*
* @param integer $id
* @return mixed
*/ */
public function initForm($id = 0)
public function initForm(int $id = 0)
{ {
$users = User::findBy()
->leftJoin('user_point_sale', 'user_point_sale.id_user = user.id AND user_point_sale.id_point_sale = :id_point_sale',[':id_point_sale' => $id])
$userManager = $this->getUserManager();

$users = $userManager->queryUsersBy()
->leftJoin('user_point_sale', 'user_point_sale.id_user = user.id AND user_point_sale.id_point_sale = :id_point_sale', [':id_point_sale' => $id])
->orderBy('user_point_sale.id_point_sale DESC, lastname ASC, name ASC') ->orderBy('user_point_sale.id_point_sale DESC, lastname ASC, name ASC')
->all(); ->all();
return [ return [
'users' => $users 'users' => $users
]; ];


/** /**
* Supprime un point de vente et redirige vers la liste des points de vente. * Supprime un point de vente et redirige vers la liste des points de vente.
*
* @param integer $id
* @return mixed
*/ */
public function actionDelete($id, $confirm = false)
{
$pointSale = $this->findModel($id) ;
if($confirm) {
public function actionDelete(int $id, $confirm = false)
{
$orderManager = $this->getOrderManager();
$distributionManager = $this->getDistributionManager();

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

if ($confirm) {
$pointSale->status = -1; $pointSale->status = -1;
$pointSale->save(); $pointSale->save();


UserPointSale::deleteAll(['id_point_sale' => $id]); UserPointSale::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 = $distributionManager->findDistributionsIncoming();
foreach ($incomingDistributions as $distribution) { foreach ($incomingDistributions as $distribution) {
PointSaleDistribution::deleteAll(['id_point_sale' => $id, 'id_distribution' => $distribution->id]); PointSaleDistribution::deleteAll(['id_point_sale' => $id, 'id_distribution' => $distribution->id]);
} }
] ]
); );


if($ordersArray) {
foreach($ordersArray as $order) {
$order->delete(true);
if ($ordersArray) {
foreach ($ordersArray as $order) {
$orderManager->deleteOrder($order, true);
} }
} }


Yii::$app->getSession()->setFlash('success', 'Point de vente <strong>'.Html::encode($pointSale->name).'</strong> supprimé.');
}
else {
Yii::$app->getSession()->setFlash('info', 'Souhaitez-vous vraiment supprimer le point de vente <strong>'.Html::encode($pointSale->name).'</strong> ? '
. Html::a('Oui',['point-sale/delete','id' => $id, 'confirm' => 1], ['class' => 'btn btn-default']).' '.Html::a('Non', ['point-sale/index'], ['class' => 'btn btn-default']));
$this->setFlash('success', 'Point de vente <strong>' . Html::encode($pointSale->name) . '</strong> supprimé.');
} else {
$this->setFlash('info', 'Souhaitez-vous vraiment supprimer le point de vente <strong>' . Html::encode($pointSale->name) . '</strong> ? '
. Html::a('Oui', ['point-sale/delete', 'id' => $id, 'confirm' => 1], ['class' => 'btn btn-default']) . ' ' . Html::a('Non', ['point-sale/index'], ['class' => 'btn btn-default']));
} }
return $this->redirect(['index']); return $this->redirect(['index']);
} }
/** /**
* Définit un point de vente par défaut. * Définit un point de vente par défaut.
*
* @param integer $id
*/ */
public function actionDefault($id)
public function actionDefault(int $id)
{ {
$pointSale = $this->findModel($id) ;
if($pointSale) {
PointSale::updateAll(['default' => 0], 'id_producer = :id_producer', [':id_producer' => GlobalParam::getCurrentProducerId()]) ;
if(!$pointSale->default) {
$pointSale->default = 1 ;
$pointSale->save() ;
Yii::$app->getSession()->setFlash('success', 'Point de vente <strong>'.Html::encode($pointSale->name).'</strong> défini par défaut.') ;
}
else {
Yii::$app->getSession()->setFlash('success', 'Aucun point de vente défini par défaut') ;
$pointSaleManager = $this->getPointSaleManager();

$pointSale = $this->findModel($id);
if ($pointSale) {
PointSale::updateAll(['default' => 0], 'id_producer = :id_producer', [':id_producer' => GlobalParam::getCurrentProducerId()]);

if (!$pointSale->default) {
$pointSale->default = 1;
$pointSaleManager->saveUpdate($pointSale);

$this->setFlash('success', 'Point de vente <strong>' . Html::encode($pointSale->name) . '</strong> défini par défaut.');
} else {
$this->setFlash('success', 'Aucun point de vente défini par défaut');
} }
} }
return $this->redirect(['index']); return $this->redirect(['index']);
} }


/** /**
* Recherche un point de vente en fonction de son ID. * Recherche un point de vente en fonction de son ID.
*
* @param integer $id
* @return PointVente
* @throws NotFoundHttpException si le modèle n'est pas trouvé
*/ */
protected function findModel($id)
protected function findModel(int $id)
{ {
if (($model = PointSale::findOne($id)) !== null) { if (($model = PointSale::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.');
} }
} }

} }

+ 102
- 167
backend/controllers/ProducerAdminController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam;
use common\logic\Order\Order\Model\Order;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Product\Product\Model\Product;
use Yii; use Yii;
use common\models\User;
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;
use common\models\Product;
use common\models\Order;
use common\models\Subscription;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
class ProducerAdminController extends BackendController
class ProducerAdminController extends BackendController
{ {

public function behaviors()
public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['post'], 'delete' => ['post'],
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == USER::STATUS_ADMIN;
return $this->getUserManager()->isCurrentAdmin();
} }
] ]
], ],


/** /**
* Liste les producteurs. * Liste les producteurs.
*
*
* @return mixed * @return mixed
*/ */
public function actionIndex()
public function actionIndex()
{ {
$producerManager = $this->getProducerManager();

$dataProviderProducer = new ActiveDataProvider([ $dataProviderProducer = new ActiveDataProvider([
'query' => Producer::find() 'query' => Producer::find()
->with('userProducer', 'user')
->orderBy('active DESC, free_price DESC'),
->with('userProducer', 'user')
->orderBy('active DESC, free_price DESC'),
'pagination' => [ 'pagination' => [
'pageSize' => 1000, 'pageSize' => 1000,
], ],
]); ]);


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

$producersArray = $producerManager->findProducersActive();
$sumPrices = 0; $sumPrices = 0;
foreach($producersArray as $producer) {
$sumPrices += $producer->getAmountBilledLastMonth();
foreach ($producersArray as $producer) {
$sumPrices += $producerManager->getAmountBilledLastMonth($producer);
} }


return $this->render('index', [ return $this->render('index', [
'sumPrices' => $sumPrices 'sumPrices' => $sumPrices
]); ]);
} }
/** /**
* Crée un producteur. * Crée un producteur.
*
* @return mixed
*/ */
public function actionCreate()
public function actionCreate()
{ {
$model = new Producer();
$producerManager = $this->getProducerManager();
$producer = $producerManager->instanciateProducer();


if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Producteur créé.');
if ($producer->load(\Yii::$app->request->post()) && $producerManager->saveCreate($producer)) {
$this->setFlash('success', 'Producteur créé.');
return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
return $this->render('create', [ return $this->render('create', [
'model' => $model,
'model' => $producer,
]); ]);
} }
} }


/** /**
* Modification d'un producteur. * Modification d'un producteur.
*
* @return mixed
*/ */
public function actionUpdate($id)
public function actionUpdate(int $id)
{ {
$model = $this->findModel($id);
$producerManager = $this->getProducerManager();
$producer = $this->findModel($id);


if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Producteur modifié.');
if ($producer->load(\Yii::$app->request->post()) && $producerManager->saveCreate($producer)) {
$this->setFlash('success', 'Producteur modifié.');
return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
return $this->render('update', [ return $this->render('update', [
'model' => $model,
'model' => $producer,
]); ]);
} }
} }


public function actionUserTransfer($fromProducerId, $toProducerId, $withOrders = 1) public function actionUserTransfer($fromProducerId, $toProducerId, $withOrders = 1)
{ {
$fromProducerId = (int) $fromProducerId;
$toProducerId = (int) $toProducerId;
$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();

$fromProducerId = (int)$fromProducerId;
$toProducerId = (int)$toProducerId;
$count = 0; $count = 0;
$usersArray = User::findBy(['id_producer' => $fromProducerId])->all();
$usersArray = $userManager->queryUsersBy(['id_producer' => $fromProducerId])->all();


foreach($usersArray as $user) {
foreach ($usersArray as $user) {
$idUser = $user['user_id']; $idUser = $user['user_id'];


$countOrders = 0; $countOrders = 0;
if($withOrders) {
if ($withOrders) {
$countOrders = Order::searchCount([ $countOrders = Order::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) {
Producer::addUser($idUser, $toProducerId);
$count ++;
if (($withOrders && $countOrders) || !$withOrders) {
$producerManager->addUser(
$userManager->findOneUserById($idUser),
$producerManager->findOneProducerById($toProducerId)
);
$count++;
} }
} }


if($count) {
Yii::$app->getSession()->setFlash('success', $count.' clients importés du producteur #'.$fromProducerId.' vers le producteur #'.$toProducerId.'.');
}
else {
Yii::$app->getSession()->setFlash('error', 'Aucun client à importer.');
if ($count) {
$this->setFlash('success', $count . ' clients importés du producteur #' . $fromProducerId . ' vers le producteur #' . $toProducerId . '.');
} else {
$this->setFlash('error', 'Aucun client à importer.');
} }


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


/**
* Génère la facture mensuelle d'un producteur.
*
* @param integer $idProducer
*/
public function actionBill($idProducer)
{
$producer = Producer::findOne($idProducer);

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

$last_invoice = Invoice::getLastInvoice() ;
if (!$last_invoice) {
$reference = 'BAP000001';
} else {
$reference = str_replace('BAP', '', $last_invoice->reference);
$reference ++;
$reference = 'BAP' . $reference;
}

$invoice = new Invoice;
$invoice->id_producer = $idProducer;
$invoice->date = date('Y-m-d H:i:s');
$invoice->reference = $reference;
$invoice->turnover = $producer->getTurnover($period);
$invoice->amount_ht = $producer->getFreePrice() ;
$invoice->wording = 'Facture ' . date('m/Y', strtotime('-1 month'));
$invoice->text = 'Utilisation de la plateforme <strong>distrib</strong> pour le mois : ' . date('m/Y', strtotime('-1 month')) . '<br />'
. 'Chiffre d\'affaire réalisé sur la plateforme : <strong>' . number_format($facture->ca, 2) . ' €</strong> commissionné à <strong>1%</strong>.';
$invoice->paid = 0;
$invoice->period = $period;
$invoice->save();
}

$this->redirect(['producer-admin/index']);
}

/**
* Liste les factures des producteurs.
*
* @return mxied
*/
public function actionBilling()
public function actionProducerInstallTaxUpdatePrices($idProducer)
{ {
$dataProviderInvoice = new ActiveDataProvider([
'query' => Invoice::find()
->with('producer')
->orderBy('reference DESC'),
'pagination' => [
'pageSize' => 1000,
],
$productsArray = Product::searchAll([
'id_producer' => $idProducer
]); ]);


return $this->render('billing', [
'dataProviderInvoice' => $dataProviderInvoice,
]);
}
public function actionProducerInstallTaxUpdatePrices($idProducer)
{
// product
$productsArray = Product::searchAll([
'id_producer' => $idProducer
]) ;
$connection = Yii::$app->getDb();


$connection = Yii::$app->getDb();
foreach($productsArray as $product) {
$product->price = round($product->price / (1 + $product->taxRate->value), 2) ;
$product->save() ;
foreach ($productsArray as $product) {
$product->price = round($product->price / (1 + $product->taxRate->value), 2);
$product->save();


$command = $connection->createCommand("
$command = $connection->createCommand("
UPDATE `product_order` UPDATE `product_order`
SET price = ROUND(price / (1 + :tax_value), 2), SET price = ROUND(price / (1 + :tax_value), 2),
id_tax_rate = :id_tax_rate id_tax_rate = :id_tax_rate
WHERE id_product = :id_product", WHERE id_product = :id_product",
[
':id_product' => $product->id,
':tax_value' => $product->taxRate->value,
':id_tax_rate' => $product->taxRate->id,
]);
[
':id_product' => $product->id,
':tax_value' => $product->taxRate->value,
':id_tax_rate' => $product->taxRate->id,
]);


$result = $command->query();
}
$result = $command->query();
}


echo 'ok' ;
echo 'ok';
} }


/** /**
* Recherche un établissement.
*
* @param integer $id
* @return Etablissement
* @throws NotFoundHttpException
* Recherche un producteur.
*/ */
protected function findModel($id) {
protected function findModel(int $id)
{
if (($model = Producer::findOne($id)) !== null) { if (($model = Producer::findOne($id)) !== null) {
return $model; return $model;
} else { } else {

+ 18
- 39
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 common\logic\Producer\Producer\Model\Producer;
use common\logic\Producer\ProducerPriceRange\Model\ProducerPriceRange;
use Yii; use Yii;
use common\models\User;
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.
*/ */
class ProducerController extends BackendController class ProducerController extends BackendController
{ {

public $enableCsrfValidation = false; public $enableCsrfValidation = false;


public function behaviors() public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
'delete' => ['post'], 'delete' => ['post'],
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


/** /**
* Modifie un producteur. * Modifie un producteur.
*
* @return mixed
*/ */
public function actionUpdate() public function actionUpdate()
{ {
$producerManager = $this->getProducerManager();
$request = Yii::$app->request; $request = Yii::$app->request;
$model = $this->findModel(GlobalParam::getCurrentProducerId()); $model = $this->findModel(GlobalParam::getCurrentProducerId());
$logoFilenameOld = $model->logo; $logoFilenameOld = $model->logo;
$model->option_dashboard_date_end = date('d/m/Y', strtotime($model->option_dashboard_date_end)); $model->option_dashboard_date_end = date('d/m/Y', strtotime($model->option_dashboard_date_end));
} }


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


if (strlen($model->option_dashboard_date_start)) { if (strlen($model->option_dashboard_date_start)) {
$model->option_dashboard_date_start = date( $model->option_dashboard_date_start = date(
$model->save(); $model->save();
} }


$model->savePrivateKeyApiStripe();
$model->savePrivateKeyEndpointStripe();
$producerManager->savePrivateKeyApiStripe($model);
$producerManager->savePrivateKeyEndpointStripe($model);


$model->option_stripe_private_key = ''; $model->option_stripe_private_key = '';
$model->option_stripe_endpoint_secret = ''; $model->option_stripe_endpoint_secret = '';
$model->save(); $model->save();


Yii::$app->getSession()->setFlash('success', 'Paramètres mis à jour.');
$this->setFlash('success', 'Paramètres mis à jour.');
return $this->redirect(['update', 'id' => $model->id, 'edit_ok' => true]); return $this->redirect(['update', 'id' => $model->id, 'edit_ok' => true]);
} else { } else {
if ($model->load(Yii::$app->request->post())) {
Yii::$app->getSession()->setFlash('error', 'Le formulaire comporte des erreurs.');
if ($model->load(\Yii::$app->request->post())) {
$this->setFlash('error', 'Le formulaire comporte des erreurs.');
} }
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'model' => $model,
/** /**
* Affiche le formulaire permettant au producteur de définir le montant * Affiche le formulaire permettant au producteur de définir le montant
* de son abonnement. * de son abonnement.
*
* @return mixed
*/ */
public function actionBilling() public function actionBilling()
{ {
$datasInvoices = new ActiveDataProvider([
'query' => Invoice::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId()])
->orderBy('reference DESC'),
'pagination' => [
'pageSize' => 1000,
],
]);

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


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


if (!is_null($producer->free_price)) { if (!is_null($producer->free_price)) {


return $this->render('billing', [ return $this->render('billing', [
'dataProviderPrices' => $dataProviderPrices, 'dataProviderPrices' => $dataProviderPrices,
'datasInvoices' => $datasInvoices,
'producer' => $producer, 'producer' => $producer,
'alertFreePrice' => (isset($alertFreeprice)) ? true : false 'alertFreePrice' => (isset($alertFreeprice)) ? true : false
]); ]);


/** /**
* Recherche un établissement via son ID. * Recherche un établissement via son ID.
*
* @param integer $id
* @return Etablissement
* @throws NotFoundHttpException
*/ */
protected function findModel($id)
protected function findModel(int $id)
{ {
if (($model = Producer::findOne($id)) !== null) { if (($model = Producer::findOne($id)) !== null) {
return $model; return $model;


public function actionUpdateOpendistribVersion() public function actionUpdateOpendistribVersion()
{ {
$producer = GlobalParam::getCurrentProducer();
$producer->updateOpendistribVersion();
return $this->redirect(Yii::$app->request->referrer);
$producerManager = $this->getProducerManager();
$producerManager->updateOpendistribVersion(GlobalParam::getCurrentProducer());

return $this->redirect(\Yii::$app->request->referrer);
} }
} }

+ 92
- 103
backend/controllers/ProducerPriceRangeAdminController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\ProducerPriceRange;
use common\logic\Producer\ProducerPriceRange\Model\ProducerPriceRange;
use Yii; use Yii;
use common\models\User;
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 yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;


/** /**
* TaxRateAdminController implements the CRUD actions for TaxRate model.
* ProducerPriceRangeAdminController implements the CRUD actions for ProducerPriceRange model.
*/ */
class ProducerPriceRangeAdminController extends BackendController class ProducerPriceRangeAdminController extends BackendController
{ {
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return $this->getUserManager()->isCurrentAdmin();
}
]
],
],
];
}


public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == USER::STATUS_ADMIN;
}
]
],
],
];
}
/**
* Liste les tranches de prix.
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => ProducerPriceRange::find()->orderBy('range_begin ASC')
]);


/**
* Liste les tranches de prix.
*
* @return mixed
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => ProducerPriceRange::find()->orderBy('range_begin ASC')
]);

return $this->render('index', [
'dataProviderProducerPriceRange' => $dataProvider,
]);
}
return $this->render('index', [
'dataProviderProducerPriceRange' => $dataProvider,
]);
}


/**
* Crée une tranche de prix.
*
* @return mixed
*/
public function actionCreate()
{
$model = new ProducerPriceRange();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Tranche de prix créée.');
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Crée une tranche de prix.
*/
public function actionCreate()
{
$producerPriceRangeManager = $this->getProducerPriceRangeManager();
$producerPriceRange = $producerPriceRangeManager->instanciateProducerPriceRange();

if ($producerPriceRange->load(\Yii::$app->request->post())
&& $producerPriceRangeManager->saveCreate($producerPriceRange)) {

$this->setFlash('success', 'Tranche de prix créée.');


/**
* Édition d'une tranche de prix.
*
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Tranche de prix éditée.');
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $producerPriceRange,
]);
} }
}


/**
* Supprime une tranche de prix.
*
* @param integer $id
*/
public function actionDelete($id)
{
$producerPriceRange = ProducerPriceRange::searchOne([
'id' => $id
]) ;
$producerPriceRange->delete();

Yii::$app->getSession()->setFlash('success', 'Tranche de prix supprimée.');
return $this->redirect(['producer-price-range-admin/index']);
/**
* Édition d'une tranche de prix.
*/
public function actionUpdate(int $id)
{
$producerPriceRangeManager = $this->getProducerPriceRangeManager();
$producerPriceRange = $this->findModel($id);

if ($producerPriceRange->load(\Yii::$app->request->post()) && $producerPriceRangeManager->saveUpdate($producerPriceRange)) {
$this->setFlash('success', 'Tranche de prix éditée.');
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $producerPriceRange,
]);
} }
}

/**
* Supprime une tranche de prix.
*/
public function actionDelete(int $id)
{
$producerPriceRangeManager = $this->getProducerPriceRangeManager();

$producerPriceRange = $this->findModel($id);
$producerPriceRangeManager->delete($producerPriceRange);
$this->setFlash('success', 'Tranche de prix supprimée.');

return $this->redirect(['producer-price-range-admin/index']);
}


/**
* Finds the Developpement model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return ProducerPriceRange the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = ProducerPriceRange::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
protected function findModel($id)
{
$producerPriceRangeManager = $this->getProducerPriceRangeManager();
if (($producerPriceRange = $producerPriceRangeManager->findOneProducerPriceRangeById($id)) !== null) {
return $producerPriceRange;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
} }
}
} }

+ 117
- 140
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 common\logic\Product\Product\Model\Product;
use common\logic\Product\ProductCategory\Model\ProductCategorySearch;
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\User;
use common\models\UserPointSale;
use common\models\Order;
use common\models\Producer;
use common\models\Distribution;
use yii\helpers\Html; use yii\helpers\Html;


/** /**
* PointVenteController implements the CRUD actions for PointVente model.
* ProductCategoryController implements the CRUD actions for ProductCategory model.
*/ */
class ProductCategoryController extends BackendController class ProductCategoryController extends BackendController
{ {
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
}
],
],
],
];
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return $this->getUserManager()->hasAccessBackend();
}
],
],
],
];
}

/**
* Liste les catégories.
*/
public function actionIndex()
{
$searchModel = new ProductCategorySearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

/**
* Crée une catégorie.
*/
public function actionCreate()
{
$productCategoryManager = $this->getProductCategoryManager();
$productCategory = $productCategoryManager->instanciateProductCategory();

$productCategory->id_producer = GlobalParam::getCurrentProducerId();

if ($productCategory->load(\Yii::$app->request->post()) && $productCategoryManager->saveCreate($productCategory)) {
$this->setFlash('success', "Catégorie ajoutée.");
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $productCategory,
]);
} }

/**
* Liste les points de vente.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ProductCategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

/**
* Modifie une catégorie.
*/
public function actionUpdate(int $id)
{
$productCategoryManager = $this->getProductCategoryManager();
$productCategory = $this->findModel($id);

if ($productCategory->load(\Yii::$app->request->post()) && $productCategoryManager->saveUpdate($productCategory)) {
$this->setFlash('success', "Catégorie modifiée.");
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $productCategory,
]);
} }

/**
* Crée une catégorie.
*
* @return mixed
*/
public function actionCreate()
{
$model = new ProductCategory();

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

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', "Catégorie ajoutée.");
return $this->redirect(['index']);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}

/**
* Supprime une catégorie.
*/
public function actionDelete($id)
{
$productCategoryManager = $this->getProductCategoryManager();
$productCategory = $this->findModel($id);

$productCategoryManager->delete($productCategory);
Product::updateAll(['id_product_category' => null], ['id_product_category' => $id]);

$this->setFlash('success', 'Catégorie <strong>' . Html::encode($productCategory->name) . '</strong> supprimée.');

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

/**
* Modifie l'ordre des catégories.
*/
public function actionPosition()
{
$array = Yii::$app->request->post('array');
$positionArray = json_decode(stripslashes($array));

foreach ($positionArray as $id => $position) {
$category = $this->findModel($id);
$category->position = $position;
$category->save();
} }

/**
* Modifie une catégorie.
*
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', "Catégorie modifiée.");
return $this->redirect(['index']);
}
else {
return $this->render('update', [
'model' => $model,
]);
}
}

/**
* Supprime une catégorie
*
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$productCategory = $this->findModel($id);

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

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

/**
* Modifie l'ordre des catégories.
*
* @param array $array
*/
public function actionPosition()
{
$array = Yii::$app->request->post('array');
$positionArray = json_decode(stripslashes($array));

foreach ($positionArray as $id => $position) {
$category = $this->findModel($id);
$category->position = $position;
$category->save();
}
}

/**
* Recherche une catégorie en fonction de son ID.
*
* @param integer $id
* @return ProductCategory
* @throws NotFoundHttpException si le modèle n'est pas trouvé
*/
protected function findModel($id)
{
if (($model = ProductCategory::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}

/**
* Recherche une catégorie en fonction de son ID.
*/
protected function findModel($id)
{
$productCategoryManager = $this->getProductCategoryManager();
if (($productCategory = $productCategoryManager->findOneProductCategoryById($id)) !== null) {
return $productCategory;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
} }
}


} }

+ 226
- 87
backend/controllers/ProductController.php View File



namespace backend\controllers; namespace backend\controllers;


use backend\forms\ProductPriceUploadForm;
use common\helpers\CSV;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\ProductDistribution;
use common\models\ProductPrice;
use common\models\ProductPriceSearch;
use common\models\ProductSearch;
use common\models\UserSearch;
use common\logic\Distribution\ProductDistribution\Model\ProductDistribution;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Product\Product\Model\Product;
use common\logic\Product\Product\Model\ProductSearch;
use common\logic\Product\ProductPointSale\Model\ProductPointSale;
use common\logic\Product\ProductPrice\Model\ProductPrice;
use common\logic\Product\ProductPrice\Model\ProductPriceSearch;
use common\logic\User\UserProducer\Model\UserProducer;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\models\Product;
use common\models\Distribution;
use common\models\User;
use common\models\UserProducer;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\helpers\BaseFileHelper;
use yii\helpers\Html;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use common\helpers\Upload; use common\helpers\Upload;
use yii\web\UploadedFile;


/** /**
* ProduitController implements the CRUD actions for Produit model. * ProduitController implements the CRUD actions for Produit model.
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],
public function actionIndex() public function actionIndex()
{ {
$searchModel = new ProductSearch(); $searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);


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


/** /**
* 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() public function actionCreate()
{ {
$model = new Product();
$productManager = $this->getProductManager();
$distributionManager = $this->getDistributionManager();

$model = $productManager->instanciateProduct();

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

$model->monday = 1; $model->monday = 1;
$model->tuesday = 1; $model->tuesday = 1;
$model->wednesday = 1; $model->wednesday = 1;
$model->sunday = 1; $model->sunday = 1;
$model->available_on_points_sale = 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(); $lastProductOrder = Product::find()->where('id_producer = :id_producer')->params([':id_producer' => GlobalParam::getCurrentProducerId()])->orderBy('order DESC')->one();
if ($lastProductOrder) { if ($lastProductOrder) {
} }


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


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


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

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


return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
} }


/** /**
* 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) public function actionUpdate($id)
{ {
$request = Yii::$app->request;
$productManager = $this->getProductManager();
$distributionManager = $this->getDistributionManager();


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


foreach ($model->productPointSale as $productPointSale) { foreach ($model->productPointSale as $productPointSale) {


$photoFilenameOld = $model->photo; $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); Upload::uploadFile($model, 'photo', $photoFilenameOld);


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


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


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


Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> modifié');
$this->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> modifié');
return $this->redirect(['index']); return $this->redirect(['index']);
} }


/** /**
* Traite les accès restreints d'un point de vente. * 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) { 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); $model = $this->findModel($id);


$searchModel = new ProductPriceSearch(); $searchModel = new ProductPriceSearch();
$searchModel->id_product = $id; $searchModel->id_product = $id;


$dataProvider = $searchModel->search(array_merge(Yii::$app->request->queryParams, [
$dataProvider = $searchModel->search(array_merge(\Yii::$app->request->queryParams, [
'id_product' => $id 'id_product' => $id
])); ]));


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


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


$conditionsProductPriceExist = [ $conditionsProductPriceExist = [
'id_product' => $idProduct, '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); $productPriceExist = ProductPrice::findOne($conditionsProductPriceExist);


if ($productPriceExist) { if ($productPriceExist) {
$productPriceExist->delete(); $productPriceExist->delete();
Yii::$app->getSession()->setFlash('warning', 'Un prix existait déjà pour cet utilisateur / point de vente, il a été supprimé.');
$this->setFlash('warning', 'Un prix existait déjà pour cet utilisateur / point de vente, il a été supprimé.');
} }


if ($model->save()) { if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Le prix a bien été ajouté.');
$this->setFlash('success', 'Le prix a bien été ajouté.');
return $this->redirect(['product/prices-list', 'id' => $idProduct]); return $this->redirect(['product/prices-list', 'id' => $idProduct]);
} }
} }


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

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


if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Prix modifié');
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', 'Prix modifié');
return $this->redirect(['product/prices-list', 'id' => $model->id_product]); return $this->redirect(['product/prices-list', 'id' => $model->id_product]);
} }


{ {
$productPrice = $this->findModelProductPrice($id); $productPrice = $this->findModelProductPrice($id);
$productPrice->delete(); $productPrice->delete();
Yii::$app->getSession()->setFlash('success', 'Prix supprimé');
$this->setFlash('success', 'Prix supprimé');
return $this->redirect(['product/prices-list', 'id' => $productPrice->id_product]); return $this->redirect(['product/prices-list', 'id' => $productPrice->id_product]);
} }


/** /**
* 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); $product = $this->findModel($id);


if ($confirm) { if ($confirm) {
$product->delete(); $product->delete();
ProductDistribution::deleteAll(['id_product' => $id]); ProductDistribution::deleteAll(['id_product' => $id]);
Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($product->name) . '</strong> supprimé');

$this->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> ? '
$this->setFlash('info', 'Souhaitez-vous vraiment supprimer le produit <strong>' . Html::encode($product->name) . '</strong> ? '
. Html::a('Oui', ['product/delete', 'id' => $id, 'confirm' => 1], ['class' => 'btn btn-default']) . ' ' . Html::a('Non', ['product/index'], ['class' => 'btn btn-default'])); . Html::a('Oui', ['product/delete', 'id' => $id, 'confirm' => 1], ['class' => 'btn btn-default']) . ' ' . Html::a('Non', ['product/index'], ['class' => 'btn btn-default']));
} }




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

$distributionManager = $this->getDistributionManager();

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


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


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


/** /**
* Recherche un produit en fonction de son ID.
* Import des prix produits via un fichier CSV.
* *
* @param integer $id
* @return Produit
* @throws NotFoundHttpException si le modèle n'est pas trouvé
* @return mixed
*/ */
protected function findModel($id)
public function actionPriceImport()
{ {
if (($model = Product::findOne($id)) !== null) {
return $model;
$productManager = $this->getProductManager();
$productPriceManager = $this->getProductPriceManager();
$userGroupManager = $this->getUserGroupManager();
$pointSaleManager = $this->getPointSaleManager();
$userManager = $this->getUserManager();

$model = new ProductPriceUploadForm();

if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');

if ($model->file && $model->validate()) {
$productPriceCsvArray = array_map(function($data) { return str_getcsv($data,";");}, file($model->file->tempName));

//die('mime type : '.BaseFileHelper::getMimeType($model->file->tempName));

if(!$productPriceCsvArray || count($productPriceCsvArray[0]) != 6) {
$this->setFlash('error', "Format de fichier invalide. Veuillez vérifier que le séparateur de champs de votre fichier est bien \";\".");
}
else {
unset($productPriceCsvArray[0]);
$countUpdate = 0;
$dataNotFound = false;
foreach ($productPriceCsvArray as $productPriceCsv) {
if (count($productPriceCsv) != 6) {
$dataNotFound = true;
continue;
}

$productName = $productPriceCsv[0];
$userArray = explode('#', $productPriceCsv[1]);
$userGroupName = $productPriceCsv[2];
$pointSaleName = $productPriceCsv[3];
$quantityFrom = (float)$productPriceCsv[4];
$price = (float)$productPriceCsv[5];

$product = $productName ? $productManager->findOneProductByName($productName) : null;
$user = (count($userArray) > 1) ? $userManager->findOneUserById((int)$userArray[1]) : null;
$userGroup = $userGroupName ? $userGroupManager->findOneUserGroupByName($userGroupName) : null;
$pointSale = $pointSaleName ? $pointSaleManager->findOnePointSaleByName($pointSaleName) : null;

if (($productName && !$product)
|| (count($userArray) > 1 && !$user)
|| ($userGroupName && !$userGroup)
|| ($pointSaleName && !$pointSale)) {

$dataNotFound = true;
continue;
}

if ($product) {
// prix de base
if (!$user && !$userGroup && !$pointSale && !$quantityFrom) {
$product->price = $price;
$productManager->saveUpdate($product);
$countUpdate++;
} // prix spécifique
else {
$productPrice = $productPriceManager->findOneProductPriceBy($product, $user, $userGroup, $pointSale, $quantityFrom);
if ($productPrice) {
$productPrice->price = $price;
$productPriceManager->saveUpdate($productPrice);
$countUpdate++;
} else {
$dataNotFound = true;
}
}
}
}

if ($dataNotFound) {
$this->addFlash('error', "Attention, certaines lignes du fichier n'ont pas été prises en compte. Veuillez réessayer en repartant du fichier d'export.<br />Contacter l'administrateur du site si le problème persiste.");
}

if ($countUpdate) {
$this->addFlash('success', $countUpdate . ' prix produits mis à jour.');
}
}
}
}

return $this->render('price_import', [
'model' => $model
]);
}

/**
* Export des prix produits au format CSV.
*
* @return mixed
*/
public function actionPriceExport()
{
$productManager = $this->getProductManager();
$productPriceManager = $this->getProductPriceManager();
$userManager = $this->getUserManager();

$data = [];

$data[] = [
"Produit",
"Utilisateur",
"Groupe d'utilisateur",
"Point de vente",
"À partir de la quantité",
"Prix HT"
];

$productArray = $productManager->findProducts();
foreach($productArray as $product) {

// prix produit
$data[] = [
$product->name,
'',
'',
'',
'',
$product->price
];

// prix spécifiques
foreach($product->productPrice as $productPrice) {
$productPrice = $productPriceManager->findOneProductPriceById($productPrice->id);

if($productPrice->user || $productPrice->userGroup || $productPrice->pointSale || $productPrice->from_quantity) {
$data[] = [
$product->name,
$productPrice->user ? str_replace('#', '', $userManager->getUsername($productPrice->user)).' #'.$productPrice->user->id : '',
$productPrice->userGroup ? $productPrice->userGroup->name : '',
$productPrice->pointSale ? $productPrice->pointSale->name : '',
$productPrice->from_quantity ?? '',
$productPrice->price
];
}
}
}

CSV::downloadSendHeaders('prix_produits.csv');
echo CSV::array2csv($data);
die();
}

/**
* Recherche un produit en fonction de son ID.
*/
protected function findModel(int $id)
{
$productManager = $this->getProductManager();

if (($product = $productManager->findOneProductById($id)) !== null) {
return $product;
} 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) {
return $model;
$productPriceManager = $this->getProductPriceManager();
if (($productPrice = $productPriceManager->findOneProductPriceById($id)) !== null) {
return $productPrice;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
} }
} }

} }

+ 65
- 61
backend/controllers/QuotationController.php View File

namespace backend\controllers; namespace backend\controllers;


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

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


class QuotationController extends DocumentController class QuotationController extends DocumentController
{ {
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
}
]
],
],
];
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return $this->getUserManager()->hasAccessBackend();
}
]
],
],
];
}


/**
* Liste les modèles Invoice.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new QuotationSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
/**
* Liste les modèles Invoice.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new QuotationSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);


return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}


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


$invoice = new Invoice ;
$invoice->initTaxCalculationMethod();
$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() ;
$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);
$invoiceManager->saveCreate($invoice);


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


Yii::$app->getSession()->setFlash('success', 'Le devis <strong>'.Html::encode($quotation->name).'</strong> a bien été transformé en facture.');
return $this->redirect(['/' . $this->getControllerUrl() . '/index']);
}
else {
throw new UserException('Vous ne pouvez pas transformer en facture un devis non validé.');
}
$this->setFlash('success', 'Le devis <strong>' . Html::encode($quotation->name) . '</strong> a bien été transformé en facture.');
return $this->redirect(['/' . $this->getControllerUrl() . '/index']);
} else {
throw new UserException('Vous ne pouvez pas transformer en facture un devis non validé.');
} }
}
} }

+ 107
- 115
backend/controllers/ReportController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


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


class ReportController extends BackendController
class ReportController extends BackendController
{ {
var $enableCsrfValidation = false; var $enableCsrfValidation = false;


public function behaviors()
public function behaviors()
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend() ;
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],
], ],
]; ];
} }
public function actionIndex()
public function actionIndex()
{ {
$this->checkProductsPointsSale() ;
return $this->render('index') ;
$this->checkProductsPointsSale();
return $this->render('index');
} }
public function actionAjaxInit()
public function actionAjaxInit()
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$usersArray = User::findBy()->all() ;
$pointsSaleArray = PointSale::searchAll() ;
// distributions
$firstDistribution = Distribution::searchOne([], [
'orderby' => 'date ASC'
]) ;
$lastDistribution = Distribution::searchOne([], [
'orderby' => 'date DESC'
]) ;
$firstYear = date('Y',strtotime($firstDistribution->date)) ;
$lastYear = date('Y',strtotime($lastDistribution->date)) ;
$distributionYearsArray = [] ;
for($year = $firstYear; $year <= $lastYear; $year ++) {
$distributionYearsArray[] = $year ;

$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 = Distribution::searchAll([
'distribution.active' => 1
], [
'orderby' => 'date ASC',
]) ;
$distributionsByMonthArray = [] ;
foreach($distributionsArray as $distribution) {
$month = date('Y-m', strtotime($distribution->date)) ;
if(!isset($distributionsByMonthArray[$month])) {

$distributionsByMonthArray = [];
$distributionsArray = $distributionManager->findDistributionsActive();
foreach ($distributionsArray as $distribution) {
$month = date('Y-m', strtotime($distribution->date));
if (!isset($distributionsByMonthArray[$month])) {
$distributionsByMonthArray[$month] = [ $distributionsByMonthArray[$month] = [
'display' => 0, 'display' => 0,
'year' => date('Y',strtotime($distribution->date)),
'year' => date('Y', strtotime($distribution->date)),
'month' => strftime('%B', strtotime($distribution->date)), 'month' => strftime('%B', strtotime($distribution->date)),
'distributions' => [] 'distributions' => []
] ;
];
} }
$distribution->date = strftime('%A %d %B %Y', strtotime($distribution->date)) ;
$distributionsByMonthArray[$month]['distributions'][] = $distribution ;
$distribution->date = strftime('%A %d %B %Y', strtotime($distribution->date));
$distributionsByMonthArray[$month]['distributions'][] = $distribution;
} }
return [
return [
'usersArray' => $usersArray, 'usersArray' => $usersArray,
'pointsSaleArray' => $pointsSaleArray, 'pointsSaleArray' => $pointsSaleArray,
'distributionYearsArray' => $distributionYearsArray, 'distributionYearsArray' => $distributionYearsArray,
'distributionsByMonthArray' => $distributionsByMonthArray 'distributionsByMonthArray' => $distributionsByMonthArray
] ;
];
} }
public function actionAjaxReport()
public function actionAjaxReport()
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$posts = Yii::$app->request->post(); $posts = Yii::$app->request->post();
$resArray = [] ;
$resArray = [];
$conditionUsers = $this->_generateConditionSqlReport($posts, 'users', 'id_user');
$conditionPointsSale = $this->_generateConditionSqlReport($posts, 'pointsSale', 'id_point_sale');
$conditionDistributions = $this->_generateConditionSqlReport($posts, 'distributions', 'id_distribution');


$conditionUsers = $this->_generateConditionSqlReport($posts, 'users', 'id_user') ;
$conditionPointsSale = $this->_generateConditionSqlReport($posts, 'pointsSale', 'id_point_sale') ;
$conditionDistributions = $this->_generateConditionSqlReport($posts, 'distributions', 'id_distribution') ;
$res = Yii::$app->db->createCommand("SELECT product.name, SUM(product_order.quantity) AS quantity, SUM(product_order.price * product_order.quantity) AS total $res = Yii::$app->db->createCommand("SELECT product.name, SUM(product_order.quantity) AS quantity, SUM(product_order.price * product_order.quantity) AS total
FROM `order`, product_order, product FROM `order`, product_order, product
WHERE `order`.id = product_order.id_order WHERE `order`.id = product_order.id_order
AND product.id_producer = ".((int) GlobalParam::getCurrentProducerId()) ."
AND product.id_producer = " . ((int)GlobalParam::getCurrentProducerId()) . "
AND product_order.id_product = product.id AND product_order.id_product = product.id
AND `order`.date_delete IS NULL AND `order`.date_delete IS NULL
".$conditionUsers."
".$conditionPointsSale."
".$conditionDistributions."
" . $conditionUsers . "
" . $conditionPointsSale . "
" . $conditionDistributions . "
GROUP BY product.id GROUP BY product.id
ORDER BY product.order ASC ORDER BY product.order ASC
") ")
->queryAll();
->queryAll();


$totalGlobal = 0 ;
foreach($res as $line) {
$total = Price::format(round($line['total'], 2)) ;
if($line['quantity'] > 0) {
$totalGlobal = 0;
foreach ($res as $line) {
$total = Price::format(round($line['total'], 2));
if ($line['quantity'] > 0) {
$resArray[] = [ $resArray[] = [
'name' => $line['name'], 'name' => $line['name'],
'quantity' => $line['quantity'], 'quantity' => $line['quantity'],
'total' => $total, 'total' => $total,
] ;
$totalGlobal += $line['total'] ;
];
$totalGlobal += $line['total'];
} }
} }
$resArray[] = [ $resArray[] = [
'name' => '', 'name' => '',
'quantity' => '', 'quantity' => '',
'total' => '<strong>'.Price::format(round($totalGlobal, 2)).'</strong>',
] ;
return $resArray ;
'total' => '<strong>' . Price::format(round($totalGlobal, 2)) . '</strong>',
];
return $resArray;
} }
public function _generateConditionSqlReport($posts, $name, $fieldOrder)
public function _generateConditionSqlReport($posts, $name, $fieldOrder)
{ {
$condition = '' ;
if(isset($posts[$name]) && strlen($posts[$name])) {
$idsArray = explode(',', $posts[$name]) ;
for($i = 0; $i < count($idsArray); $i++) {
$idsArray[$i] = (int) $idsArray[$i] ;
$condition = '';
if (isset($posts[$name]) && strlen($posts[$name])) {
$idsArray = explode(',', $posts[$name]);
for ($i = 0; $i < count($idsArray); $i++) {
$idsArray[$i] = (int)$idsArray[$i];
} }
$condition = 'AND `order`.'.$fieldOrder.' IN ('.implode(',',$idsArray).') ' ;
$condition = 'AND `order`.' . $fieldOrder . ' IN (' . implode(',', $idsArray) . ') ';
} }
return $condition ;
return $condition;
} }
} }

+ 22
- 92
backend/controllers/SiteController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Subscription;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Order\Order\Model\Order;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Product\Product\Model\Product;
use common\logic\User\User\Model\User;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use common\models\User;
use common\forms\LoginForm;
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
*/ */
class SiteController extends BackendController class SiteController extends BackendController
{ {

/** /**
* @inheritdoc * @inheritdoc
*/ */
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'actions' => ['login', 'error'], 'actions' => ['login', 'error'],
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
], ],
[ [
'actions' => ['change-producer', 'bug-subscription-payment'],
'actions' => ['change-producer'],
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == User::STATUS_ADMIN;
return $this->getUserManager()->getCurrentStatus() == User::STATUS_ADMIN;
} }
], ],
], ],
], ],
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
]; ];
} }


public function actionBugSubscriptionPayment($fix = 0)
{
$producerArray = Producer::find()->where(['active' => 1])->all();

//print_r($producerArray);
//die();

foreach ($producerArray as $producer) {
$orderArray = Order::searchAll([
'distribution.id_producer' => $producer->id,
'origin' => Order::ORIGIN_AUTO,
'auto_payment' => 0,
], [
'conditions' => 'date_delete IS NULL AND point_sale.credit_functioning = \'mandatory\' AND subscription.auto_payment = 1 AND order.date > \'2022-12-01\'',
'join_with' => ['pointSale', 'subscription', 'distribution'],
]);

/*$orderArray = Order::searchAll([
'distribution.id_producer' => $producer->id,
'origin' => Order::ORIGIN_AUTO,
'auto_payment' => 0,
], [
'conditions' => 'date_delete IS NULL AND point_sale.credit_functioning = \'optional\' AND subscription.auto_payment = 1 AND order.date > \'2022-12-01\'',
'join_with' => ['pointSale', 'subscription', 'distribution'],
]);*/

$count = 0;
if($orderArray) {
foreach($orderArray as $order) {
$amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
if($amountRemaining >= 0.01) {
$count ++;
}
}
}

if($count) {
echo '<h1>' . $producer->name . '</h1>';
echo '<p>' . $count . ' commandes.</p>';
echo '<ul>';
foreach($orderArray as $order) {
$amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
if($amountRemaining) {
echo '<li>#'.$order->id.' : '.$order->distribution->date.' / '.$order->pointSale->name.' / '.$order->getAmount(Order::AMOUNT_REMAINING, true);
if($fix) {
$order->processCredit();
echo ' (payée)';
}
echo '</li>';
}
}
echo '</ul>';
}
}

die();
}

/** /**
* Affiche le tableau de bord du backend avec les dernières commandes * Affiche le tableau de bord du backend avec les dernières commandes
* réalisée, les dernières inscriptions, la liste des clients ayant un crédit * réalisée, les dernières inscriptions, la liste des clients ayant un crédit
*/ */
public function actionIndex() public function actionIndex()
{ {
$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();


// commandes
$optionDashboardNumberDistributions = Producer::getConfig('option_dashboard_number_distributions');
$optionDashboardNumberDistributions = $producerManager->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 = $producerManager->getConfig('option_dashboard_date_start');
$optionDashboardDateEnd = $producerManager->getConfig('option_dashboard_date_end');


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


]); ]);


// clients // clients
$usersArray = User::findBy()
$usersArray = $userManager->queryUsersBy()
->orderBy('created_at DESC') ->orderBy('created_at DESC')
->limit(5) ->limit(5)
->all(); ->all();


$usersNegativeCredit = User::findBy(['id_producer' => GlobalParam::getCurrentProducerId()])
$usersNegativeCredit = $userManager->queryUsersBy(['id_producer' => GlobalParam::getCurrentProducerId()])
->andWhere('user_producer.credit < 0') ->andWhere('user_producer.credit < 0')
->all(); ->all();


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

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


'ordersArray' => $ordersArray, 'ordersArray' => $ordersArray,
'usersArray' => $usersArray, 'usersArray' => $usersArray,
'usersNegativeCredit' => $usersNegativeCredit, 'usersNegativeCredit' => $usersNegativeCredit,
'producer' => $producer,
'producer' => $producerCurrent,
'productsCount' => $productsCount, 'productsCount' => $productsCount,
'pointsSaleCount' => $pointsSaleCount 'pointsSaleCount' => $pointsSaleCount
]); ]);


/** /**
* Affiche la page de connexion. * Affiche la page de connexion.
*
* @return mixed
*/ */
public function actionLogin() public function actionLogin()
{ {
} }


$model = new LoginForm(); $model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if ($model->load(\Yii::$app->request->post()) && $model->login()) {
return $this->goBack(); return $this->goBack();
} else { } else {
return $this->render('login', [ return $this->render('login', [


/** /**
* Déconnecte l'utilisateur et le redirige à la page d'accueil. * Déconnecte l'utilisateur et le redirige à la page d'accueil.
*
* @return mixed
*/ */
public function actionLogout() public function actionLogout()
{ {
/** /**
* Change le producteur courant de l'utilisateur connecté. * Change le producteur courant de l'utilisateur connecté.
* Permet de passer d'un producteur à un autre en tant qu'administrateur. * 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->id_producer = $id;
Yii::$app->user->identity->save(); Yii::$app->user->identity->save();
$this->redirect(['site/index']); $this->redirect(['site/index']);
} }

} }

+ 99
- 107
backend/controllers/StatsController.php View File

<?php <?php


/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


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\User;
use common\models\Order;
use DateTime; use DateTime;
use DateInterval; use DateInterval;
use DatePeriod; use DatePeriod;


class StatsController extends BackendController
class StatsController extends BackendController
{ {

public function behaviors()
public function behaviors()
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend() ;
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


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

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


AND distribution.date >= :date_start AND distribution.date >= :date_start
AND distribution.date <= :date_end AND distribution.date <= :date_end
") ")
->bindValue(':id_producer',GlobalParam::getCurrentProducerId())
->bindValue(':date_start', date('Y-m-', $date->getTimestamp()).'01')
->bindValue(':date_end', date('Y-m-', $date->getTimestamp()).'31' )
->bindValue(':id_producer', GlobalParam::getCurrentProducerId())
->bindValue(':date_start', date('Y-m-', $date->getTimestamp()) . '01')
->bindValue(':date_end', date('Y-m-', $date->getTimestamp()) . '31')
->queryOne(); ->queryOne();


if($res['total']) {
if ($res['total']) {
$data[$month] = $res['total']; $data[$month] = $res['total'];
}
else {
} else {
$data[$month] = 0; $data[$month] = 0;
} }


'data' => $dataNoIndex, 'data' => $dataNoIndex,
]); ]);
} }
const TOTALS = 13 ;
const TOTALS = 13;
/** /**
* Affiche un tableau avec les totaux (maximums, commandés) de chaque produit * Affiche un tableau avec les totaux (maximums, commandés) de chaque produit
* par mois d'une année donnée. * 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') ;
$productsArray = Product::searchAll() ;
$dataProducts = [] ;
$dataProducts[self::TOTALS] = ['max' => [], 'orders' => []] ;
foreach($productsArray as $product) {
$dataProducts[self::TOTALS]['max'][$product['name']] = 0 ;
$dataProducts[self::TOTALS]['orders'][$product['name']] = 0 ;
$productManager = $this->getProductManager();

if (!$year) {
$year = date('Y');
} }
if(!in_array($section, [1, 2, 3, 4])) {
$section = 1 ;

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

$dataProducts[self::TOTALS] = ['max' => [], 'orders' => []];
foreach ($productsArray as $product) {
$dataProducts[self::TOTALS]['max'][$product['name']] = 0;
$dataProducts[self::TOTALS]['orders'][$product['name']] = 0;
}

if (!in_array($section, [1, 2, 3, 4])) {
$section = 1;
} }
$iStart = (3 * ($section - 1)) + 1 ;
$iEnd = 3 * $section ;
$empty = true ;
for($i = $iStart; $i <= $iEnd; $i++) {
$iStart = (3 * ($section - 1)) + 1;
$iEnd = 3 * $section;
$empty = true;
for ($i = $iStart; $i <= $iEnd; $i++) {
// Maximums // Maximums
$resMaximums = Yii::$app->db->createCommand("SELECT product.name, SUM(IF(product_distribution.active, product_distribution.quantity_max,0)) AS total $resMaximums = Yii::$app->db->createCommand("SELECT product.name, SUM(IF(product_distribution.active, product_distribution.quantity_max,0)) AS total
FROM distribution, product_distribution, product FROM distribution, product_distribution, product
WHERE distribution.id_producer = ".GlobalParam::getCurrentProducerId()."
WHERE distribution.id_producer = " . GlobalParam::getCurrentProducerId() . "
AND distribution.date >= :date_begin AND distribution.date >= :date_begin
AND distribution.date <= :date_end AND distribution.date <= :date_end
AND distribution.id = product_distribution.id_distribution AND distribution.id = product_distribution.id_distribution
AND product_distribution.id_product = product.id AND product_distribution.id_product = product.id
GROUP BY product.id GROUP BY product.id
ORDER BY product.name") ORDER BY product.name")
->bindValue(':date_begin', date($year.'-'.str_pad($i, 2, 0, STR_PAD_LEFT).'-01'))
->bindValue(':date_end', date($year.'-'.str_pad($i, 2, 0, STR_PAD_LEFT).'-31'))
->queryAll();
$dataProducts[$i]['max'] = $resMaximums ;
if(count($resMaximums)) $empty = false ;
foreach($resMaximums as $productMax) {
if(!isset($dataProducts[self::TOTALS]['max'][$productMax['name']])) {
$dataProducts[self::TOTALS]['max'][$productMax['name']] = 0 ;
->bindValue(':date_begin', date($year . '-' . str_pad($i, 2, 0, STR_PAD_LEFT) . '-01'))
->bindValue(':date_end', date($year . '-' . str_pad($i, 2, 0, STR_PAD_LEFT) . '-31'))
->queryAll();
$dataProducts[$i]['max'] = $resMaximums;
if (count($resMaximums)) $empty = false;
foreach ($resMaximums as $productMax) {
if (!isset($dataProducts[self::TOTALS]['max'][$productMax['name']])) {
$dataProducts[self::TOTALS]['max'][$productMax['name']] = 0;
} }
$dataProducts[self::TOTALS]['max'][$productMax['name']] += $productMax['total'] ;
$dataProducts[self::TOTALS]['max'][$productMax['name']] += $productMax['total'];
} }


// Commandés // Commandés
$resOrders = Yii::$app->db->createCommand(' $resOrders = Yii::$app->db->createCommand('
SELECT product.name, SUM(product_order.quantity) AS total SELECT product.name, SUM(product_order.quantity) AS total
FROM `distribution`, `order`, `product_order`, `product` FROM `distribution`, `order`, `product_order`, `product`
WHERE distribution.id_producer = '.GlobalParam::getCurrentProducerId().'
WHERE distribution.id_producer = ' . GlobalParam::getCurrentProducerId() . '
AND distribution.date >= :date_begin AND distribution.date >= :date_begin
AND distribution.date <= :date_end AND distribution.date <= :date_end
AND distribution.id = `order`.id_distribution AND distribution.id = `order`.id_distribution
AND product_order.id_product = product.id AND product_order.id_product = product.id
GROUP BY product.id GROUP BY product.id
ORDER BY product.name') ORDER BY product.name')
->bindValue(':date_begin', date($year.'-'.str_pad($i, 2, 0, STR_PAD_LEFT).'-01'))
->bindValue(':date_end', date($year.'-'.str_pad($i, 2, 0, STR_PAD_LEFT).'-31'))
->queryAll();
->bindValue(':date_begin', date($year . '-' . str_pad($i, 2, 0, STR_PAD_LEFT) . '-01'))
->bindValue(':date_end', date($year . '-' . str_pad($i, 2, 0, STR_PAD_LEFT) . '-31'))
->queryAll();
$dataProducts[$i]['orders'] = $resOrders; $dataProducts[$i]['orders'] = $resOrders;
if(count($resOrders)) $empty = false ;
foreach($resOrders as $productOrder) {
if(!isset($dataProducts[self::TOTALS]['orders'][$productOrder['name']])) {
$dataProducts[self::TOTALS]['orders'][$productOrder['name']] = 0 ;
if (count($resOrders)) $empty = false;
foreach ($resOrders as $productOrder) {
if (!isset($dataProducts[self::TOTALS]['orders'][$productOrder['name']])) {
$dataProducts[self::TOTALS]['orders'][$productOrder['name']] = 0;
} }
$dataProducts[self::TOTALS]['orders'][$productOrder['name']] += $productOrder['total'] ;
$dataProducts[self::TOTALS]['orders'][$productOrder['name']] += $productOrder['total'];
} }
} }
ksort($dataProducts) ;
$monthArray = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre','Totaux'] ;
ksort($dataProducts);
$monthArray = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre', 'Totaux'];
return $this->render('products', [ return $this->render('products', [
'year' => $year, 'year' => $year,
'monthArray' => $monthArray, 'monthArray' => $monthArray,

+ 158
- 182
backend/controllers/SubscriptionController.php View File

<?php <?php
/**
Copyright distrib (2018)
contact@opendistrib.net
Ce logiciel est un programme informatique servant à aider les producteurs
à distribuer leur production en circuits courts.
Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.
*/
/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/


namespace backend\controllers; namespace backend\controllers;


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


class SubscriptionController extends BackendController
class SubscriptionController extends BackendController
{ {
var $enableCsrfValidation = false; var $enableCsrfValidation = false;


public function behaviors()
public function behaviors()
{ {
return [ return [
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend() ;
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


/** /**
* Liste les commandes récurrente du producteur. * Liste les commandes récurrente du producteur.
*
*
* @return string * @return string
*/ */
public function actionIndex()
public function actionIndex()
{ {
$this->checkProductsPointsSale() ;
$searchModel = new SubscriptionSearch ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$this->checkProductsPointsSale();
$searchModel = new SubscriptionSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider 'dataProvider' => $dataProvider


/** /**
* Crée un abonnement. * Crée un abonnement.
*
* @return string
*/ */
public function actionCreate($idOrder = 0)
{
// form
$model = new SubscriptionForm;
$model->isAdmin = true ;
public function actionCreate($idOrder = 0)
{
$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(); $model->id_producer = GlobalParam::getCurrentProducerId();


if($idOrder) {
$order = Order::searchOne(['id' => $idOrder]);
if ($idOrder) {
$order = $orderManager->findOneOrderById($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;
$model->id_point_sale = $order->id_point_sale; $model->id_point_sale = $order->id_point_sale;
$model->date_begin = date('d/m/Y') ;
$dateDay = strtolower(date('l',strtotime($order->distribution->date))) ;
$model->$dateDay = 1 ;
$model->week_frequency = 1 ;
if($model->id_user && Producer::getConfig('credit')) {
$model->auto_payment = 1 ;
$model->date_begin = date('d/m/Y');
$dateDay = strtolower(date('l', strtotime($order->distribution->date)));
$model->$dateDay = 1;
$model->week_frequency = 1;
if ($model->id_user && $producerManager->getConfig('credit')) {
$model->auto_payment = 1;
} }
// produits

foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$model->products['product_' . $productOrder->id_product] = $productOrder->quantity; $model->products['product_' . $productOrder->id_product] = $productOrder->quantity;
} }
throw new NotFoundHttpException('La commande est introuvable.', 404); throw new NotFoundHttpException('La commande est introuvable.', 404);
} }
} }
// produits // produits
$productsArray = Product::searchAll([], [
'orderby' => 'product.order ASC'
]) ;
if ($model->load(Yii::$app->request->post()) && $model->validate()
&& $model->save())
{
Yii::$app->getSession()->setFlash('success', 'Abonnement ajouté');
$subscription = Subscription::findOne($model->id) ;
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ;
if(count($matchedDistributionsArray)) {
$productsArray = $productManager->findProducts();

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

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

$subscription = $subscriptionManger->findOneSubscriptionById($model->id);
$matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);

if (count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]); return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]);
}
else {
} else {
return $this->redirect(['subscription/index']); return $this->redirect(['subscription/index']);
} }
} }


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

$model = new SubscriptionForm; $model = new SubscriptionForm;
$model->isAdmin = true ;
$subscription = Subscription::findOne($id);
$model->isAdmin = true;
$subscription = $subscriptionManager->findOneSubscriptionById($id);
if ($subscription) { if ($subscription) {
$model->id = $id; $model->id = $id;
$model->id_producer = $subscription->id_producer; $model->id_producer = $subscription->id_producer;
$model->date_end = date('d/m/Y', strtotime($subscription->date_end)); $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
} }


if(strlen($subscription->comment)) {
$model->comment = $subscription->comment ;
if (strlen($subscription->comment)) {
$model->comment = $subscription->comment;
} }


// produits
$arrayProductsSubscription = ProductSubscription::searchAll([
'id_subscription' => $model->id
]) ;
$arrayProductsSubscription = $productSubscriptionManager->findProductSubscriptionsBySubscription($subscription);
foreach ($arrayProductsSubscription as $productSubscription) { foreach ($arrayProductsSubscription as $productSubscription) {
$model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity; $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
} }
} }


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


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


if (!$model->date_end) { if (!$model->date_end) {
$model->date_end = null; $model->date_end = null;


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


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

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


if($countOrdersDeleted) {
$messageOrdersDeleted = '<br />'.$countOrdersDeleted.' commandes supprimées';
if ($model->date_end) {
$countOrdersDeleted = $orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription, true);
if ($countOrdersDeleted) {
$messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées';
} }
} }


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


$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ;
if(count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id,'update' => true]);
}
else {
$matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);
if (count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id, 'update' => true]);
} else {
return $this->redirect(['subscription/index']); return $this->redirect(['subscription/index']);
} }
} }


/** /**
* Supprime une commande récurrente. * 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]);
Yii::$app->getSession()->setFlash('success', 'Abonnement supprimé');
$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']); 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() ;
if($generate) {
if($update) {
$subscription->deleteOrdersIncomingDistributions() ;
$subscriptionManager = $this->getSubscriptionManager();
$distributionManager = $this->getDistributionManager();
$orderManager = $this->getOrderManager();

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

if ($generate) {
if ($update) {
$orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription);
} }
foreach($matchedDistributionsArray as $distribution) {
$subscription->add($distribution->date) ;
foreach ($matchedDistributionsArray as $distribution) {
$orderManager->createOrderFromSubscription($subscription, $distribution->date);
} }
Yii::$app->getSession()->setFlash('success', 'Commandes '.($update ? 're-' : '').'générées dans les distributions futures.');
return $this->redirect(['subscription/index']) ;
$this->setFlash('success', 'Commandes ' . ($update ? 're-' : '') . 'générées dans les distributions futures.');
return $this->redirect(['subscription/index']);
} }
return $this->render('update_distributions',[
return $this->render('update_distributions', [
'matchedDistributionsArray' => $matchedDistributionsArray, 'matchedDistributionsArray' => $matchedDistributionsArray,
'idSubscription' => $idSubscription, 'idSubscription' => $idSubscription,
'update' => $update 'update' => $update
]) ;
]);
} }
public function actionAjaxInfos($idSubscription = 0)
public function actionAjaxInfos(int $idSubscription = 0)
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$productManager = $this->getProductManager();

$productsQuery = Product::find() $productsQuery = Product::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId(),]) ;
if($idSubscription) {
$productsQuery->joinWith(['productSubscription' => function($query) use($idSubscription) {
$query->andOnCondition('product_subscription.id_subscription = '.((int) $idSubscription)) ;
}]) ;
->where(['id_producer' => GlobalParam::getCurrentProducerId(),]);
if ($idSubscription) {
$productsQuery->joinWith(['productSubscription' => function ($query) use ($idSubscription) {
$query->andOnCondition('product_subscription.id_subscription = ' . ((int)$idSubscription));
}]);
} }
$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');

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'] = '' ;

$productsArray = $productsQuery->asArray()->orderBy('order ASC')->all();

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

if (isset($theProduct['productSubscription'][0])) {
$theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * Product::$unitsArray[$theProduct['unit']]['coefficient'];
} else {
$theProduct['quantity'] = '';
} }
} }

return [ return [
'products' => $productsArray 'products' => $productsArray
] ;
];
} }
} }

+ 81
- 115
backend/controllers/TaxRateAdminController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\TaxRate;
use common\logic\Config\TaxRate\Model\TaxRate;
use Yii; use Yii;
use common\models\User;
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.
*/ */
class TaxRateAdminController extends BackendController class TaxRateAdminController extends BackendController
{ {

public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return User::getCurrentStatus() == USER::STATUS_ADMIN;
}
]
],
],
];
}

/**
* Liste les taxes.
*
* @return mixed
*/
public function actionIndex()
{
$dataProviderTaxRate = new ActiveDataProvider([
'query' => TaxRate::find()
]);

return $this->render('index', [
'dataProviderTaxRate' => $dataProviderTaxRate,
]);
}

/**
* Crée une taxe.
*
* @return mixed
*/
public function actionCreate()
{
$model = new TaxRate();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Taxe créé.');
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

/**
* Édition d'une taxe.
*
* @return mixed
*/
public function actionUpdate($id)
{


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

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', 'Taxe édité.');
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return $this->isUserCurrentAdmin();
}
]
],
],
];
}

public function actionIndex()
{
$dataProviderTaxRate = new ActiveDataProvider([
'query' => TaxRate::find()
]);

return $this->render('index', [
'dataProviderTaxRate' => $dataProviderTaxRate,
]);
}

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

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', 'Taxe créée.');
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
} }

/**
* Supprime une commande récurrente.
*
* @param integer $id
*/
public function actionDelete($id)
{
$taxeRate = TaxRate::searchOne([
'id' => $id
]) ;
$taxeRate->delete();

Yii::$app->getSession()->setFlash('success', 'Taxe supprimé');
return $this->redirect(['tax-rate-admin/index']);
}

public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', 'Taxe éditée.');
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
} }


/**
* Finds the Developpement model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Developpement the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TaxRate::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}

public function actionDelete(int $id)
{
$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)
{
$taxRateManager = $this->getTaxRateManager();
if (($taxRate = $taxRateManager->findOneTaxRateById($id)) !== null) {
return $taxRate;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
} }
}


} }

+ 120
- 128
backend/controllers/UserController.php View File



namespace backend\controllers; namespace backend\controllers;


use backend\models\CreditForm;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Mailjet; use common\helpers\Mailjet;
use common\models\User;
use common\models\Producer;
use common\models\Distribution;
use backend\models\MailForm; use backend\models\MailForm;
use common\models\UserGroup;
use common\models\UserProducer;
use common\models\UserPointSale;
use common\models\PointSale;
use common\models\UserUserGroup;
use common\helpers\Password;
use common\logic\Order\Order\Model\OrderSearch;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\PointSale\UserPointSale\Model\UserPointSale;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\logic\User\User\Model\User;
use common\logic\User\User\Model\UserSearch;
use common\logic\User\UserProducer\Model\UserProducer;
use common\logic\User\UserUserGroup\Model\UserUserGroup;
use yii\base\UserException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use \Yii;
use yii\web\NotFoundHttpException;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
class UserController extends BackendController class UserController extends BackendController
{ {

public function behaviors() public function behaviors()
{ {
return [ return [
'verbs' => [ 'verbs' => [
'class' => VerbFilter::className(),
'class' => VerbFilter::class,
'actions' => [ 'actions' => [
], ],
], ],
'access' => [ 'access' => [
'class' => AccessControl::className(),
'class' => AccessControl::class,
'rules' => [ 'rules' => [
[ [
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return $this->getUserManager()->hasAccessBackend();
} }
] ]
], ],


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

$searchModel = new UserSearch();
$dataProvider = $searchModel->search([ $dataProvider = $searchModel->search([
'UserSearch' => array_merge( 'UserSearch' => array_merge(
[ [
'id_point_sale' => $idPointSale, 'id_point_sale' => $idPointSale,
'inactive' => (int)$sectionInactiveUsers,
'subscribers' => (int)$sectionSubscribers
'inactive' => (int) $sectionInactiveUsers,
'subscribers' => (int) $sectionSubscribers
], ],
isset(Yii::$app->request->queryParams['UserSearch']) ?
isset(\Yii::$app->request->queryParams['UserSearch']) ?
Yii::$app->request->queryParams['UserSearch'] : Yii::$app->request->queryParams['UserSearch'] :
[] []
) )
]); ]);


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

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


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


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

$producerCurrent = $this->getProducerCurrent();


if ($model->id) { 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) { 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) { if ($userUserGroupsArray && count($userUserGroupsArray) > 0) {
foreach ($userUserGroupsArray as $userUserGroup) { foreach ($userUserGroupsArray as $userUserGroup) {
$model->user_groups[] = $userUserGroup->id_user_group; $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; $model->product_price_percent = $userProducer->product_price_percent;
} }


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


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


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

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


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


if ($posts && isset($posts['User']['email']) && strlen($posts['User']['email']) > 0) { 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) { if ($userExist) {
Producer::addUser($userExist->id, GlobalParam::getCurrentProducerId());
$producerManager->addUser($userExist, $producerCurrent);
$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.");
$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 { } else {
if ($model->load(Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
// save user
$password = Password::generate();
if ($model->load(\Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
$model->id_producer = 0; $model->id_producer = 0;
$model->setPassword($password);
$model->generateAuthKey();
$password = Password::generate();
$userManager->setPassword($model, $password);
$userManager->generateAuthKey($model);
$model->username = $model->email; $model->username = $model->email;
if (!strlen($model->email)) { if (!strlen($model->email)) {
$model->username = 'inconnu@opendistrib.net'; $model->username = 'inconnu@opendistrib.net';
$model->save(); $model->save();


// liaison etablissement / user // liaison etablissement / user
$useProducer = new UserProducer();
$useProducer = new UserProducer();
$useProducer->id_user = $model->id; $useProducer->id_user = $model->id;
$useProducer->id_producer = GlobalParam::getCurrentProducerId(); $useProducer->id_producer = GlobalParam::getCurrentProducerId();
$useProducer->credit = 0; $useProducer->credit = 0;
$useProducer->active = 1; $useProducer->active = 1;
$useProducer->save(); $useProducer->save();


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


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


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

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


// Moodification du profil // Moodification du profil
$user = User::find()->with('userProducer')->where(['id' => $model['id']])->one(); $user = User::find()->with('userProducer')->where(['id' => $model['id']])->one();
$userBelongToProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]); $userBelongToProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]);
if ($userBelongToProducer) { if ($userBelongToProducer) {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->load(\Yii::$app->request->post()) && $model->save()) {


// on envoie le mail de bienvenue si le mail vient d'être défini // on envoie le mail de bienvenue si le mail vient d'être défini
if (!strlen($previousMail) && strlen($model->email)) { if (!strlen($previousMail) && strlen($model->email)) {
$password = Password::generate(); $password = Password::generate();
$model->setPassword($password);
$userManager->setPassword($model, $password);
$model->username = $model->email; $model->username = $model->email;
$model->sendMailWelcome($password);
$userManager->sendMailWelcome($model, $password);
} }
$this->processLinkPointSale($model); $this->processLinkPointSale($model);
$this->processLinkUserGroup($model); $this->processLinkUserGroup($model);
$this->processProductPricePercent($model); $this->processProductPricePercent($model);
Yii::$app->getSession()->setFlash('success', 'Utilisateur modifié.');

$this->setFlash('success', 'Utilisateur modifié.');
} }
} else { } else {
throw new UserException("Vous ne pouvez pas modifier cet utilisateur."); throw new UserException("Vous ne pouvez pas modifier cet utilisateur.");
$newPassword = Yii::$app->request->post('submit_new_password'); $newPassword = Yii::$app->request->post('submit_new_password');
if ($newPassword) { if ($newPassword) {
$password = Password::generate(); $password = Password::generate();
$model->setPassword($password);
$userManager->setPassword($model, $password);
$model->save(); $model->save();


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


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


Yii::$app->getSession()->setFlash('success', 'Nouveau mot de passe envoyé.');
$this->setFlash('success', 'Nouveau mot de passe envoyé.');
} }


return $this->render('update', array_merge($this->initForm($model), [ return $this->render('update', array_merge($this->initForm($model), [


/** /**
* Lie un utilisateur aux points de vente sélectionnés. * 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(); $posts = Yii::$app->request->post();
UserPointSale::deleteAll([ UserPointSale::deleteAll([


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


/** /**
* Désactive l'utilisateur de l'établissement. * 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()
]);
$userManager = $this->getUserManager();
$userProducerManager = $this->getUserProducerManager();

$user = $userManager->findOneUserById($id);
$producer = $this->getProducerCurrent();
$userProducer = $userProducerManager->findOneUserProducer($user, $producer);

if ($userProducer) { if ($userProducer) {
$userProducer->active = 0; $userProducer->active = 0;
$userProducer->bookmark = 0; $userProducer->bookmark = 0;
$userProducer->save(); $userProducer->save();
Yii::$app->getSession()->setFlash('success', 'L\'utilisateur a bien été supprimé de votre établissement.');

$this->setFlash('success', 'L\'utilisateur a bien été supprimé de votre établissement.');
} else { } else {
throw new \yii\web\NotFoundHttpException('L\'enregistrement UserProducer est introuvable', 404); throw new \yii\web\NotFoundHttpException('L\'enregistrement UserProducer est introuvable', 404);
} }
} }


/** /**
* 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( public function actionMail(
$idPointSale = 0, $idPointSale = 0,
$usersPointSaleLink = 0, $usersPointSaleLink = 0,
$usersPointSaleHasOrder = 0) $usersPointSaleHasOrder = 0)
{ {
$userManager = $this->getUserManager();
$distributionManager = $this->getDistributionManager();

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


$users = User::findBy([
$users = $userManager->queryUsersBy([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
'id_point_sale' => $idPointSale, 'id_point_sale' => $idPointSale,
'users_point_sale_link' => $usersPointSaleLink, 'users_point_sale_link' => $usersPointSaleLink,
])->all(); ])->all();


$usersArray = []; $usersArray = [];
foreach ($users as $user) {
if (isset($user['email']) && strlen($user['email']))
foreach ($users as $key => $user) {
if (isset($user['email']) && strlen($user['email']) > 0) {
$usersArray[] = $user['email']; $usersArray[] = $user['email'];
}
else {
unset($users[$key]);
}
} }


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


$mailForm = new MailForm(); $mailForm = new MailForm();
if ($mailForm->load(Yii::$app->request->post()) && $mailForm->validate()) {
if ($mailForm->load(\Yii::$app->request->post()) && $mailForm->validate()) {
$responseSendMail = $mailForm->sendEmail($users); $responseSendMail = $mailForm->sendEmail($users);
if ($responseSendMail->success()) { if ($responseSendMail->success()) {
Yii::$app->getSession()->setFlash('success', 'Votre email a bien été envoyé.');
$this->setFlash('success', 'Votre email a bien été envoyé.');
} else { } else {
$bodyResponseSendMail = $responseSendMail->getBody(); $bodyResponseSendMail = $responseSendMail->getBody();
$emailsErrorArray = []; $emailsErrorArray = [];


if(isset($bodyResponseSendMail['Messages'])) {
if (isset($bodyResponseSendMail['Messages'])) {
foreach ($bodyResponseSendMail['Messages'] as $message) { foreach ($bodyResponseSendMail['Messages'] as $message) {
if ($message['Status'] != 'success') { if ($message['Status'] != 'success') {
$emailsErrorArray[] = $message['To']['Email'];
$emailsErrorArray[] = $message['Errors'][0]['ErrorMessage'];
} }
} }
} }


$messageError = 'Un problème est survenu lors de l\'envoi de votre email.'; $messageError = 'Un problème est survenu lors de l\'envoi de votre email.';
if (count($emailsErrorArray) > 0) { if (count($emailsErrorArray) > 0) {
$messageError .= '<br />Problème détecté sur les adresses suivantes : ' . implode(',', $emailsErrorArray);
$messageError .= '<br />Problème détecté : ' . implode(',', $emailsErrorArray);
} }
Yii::$app->getSession()->setFlash('error', $messageError);
$this->setFlash('error', $messageError);
} }


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


$incomingDistributions = Distribution::getIncomingDistributions();
$incomingDistributions = $distributionManager->findDistributionsIncoming();
$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));
} }


/** /**
* 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(); $user = User::find()->with('userProducer')->where(['id' => $id])->one();
$userProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]); $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()) {
$creditForm = new CreditForm();
if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
$creditForm->id_user = $id; $creditForm->id_user = $id;
$creditForm->save(); $creditForm->save();

$creditForm = new CreditForm; $creditForm = new CreditForm;
} }


*/ */
public function actionOrders($id) public function actionOrders($id)
{ {
$user = User::findOne($id);
$searchModel = new OrderSearch;
$dataProvider = $searchModel->search(array_merge(Yii::$app->request->queryParams, ['id_user' => $id]));
$userManager = $this->getUserManager();

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


return $this->render('orders', [ return $this->render('orders', [
'user' => $user, 'user' => $user,
/** /**
* Modifie l'option "credit_active" d'un utilisateur pour le producteur courant. * Modifie l'option "credit_active" d'un utilisateur pour le producteur courant.
* Redirige vers la page de crédit de l'utilisateur. * Redirige vers la page de crédit de l'utilisateur.
*
* @param integer $idUser
* @param boolean $state
*/ */
public function actionStateCredit($idUser, $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) { if ($userProducer) {
$userProducer->credit_active = $state; $userProducer->credit_active = $state;
/** /**
* Finds the User model based on its primary key value. * Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown. * If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = User::findOne($id)) !== null) {
return $model;
$userManager = $this->getUserManager();

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

} }

+ 100
- 121
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 common\logic\User\UserGroup\Model\UserGroupSearch;
use common\logic\User\UserUserGroup\Model\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\User;
use common\models\UserPointSale;
use common\models\Order;
use common\models\Producer;
use common\models\Distribution;
use yii\helpers\Html; use yii\helpers\Html;


/** /**
class UserGroupController extends BackendController class UserGroupController extends BackendController
{ {


public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
}
],
],
],
];
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
],
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return $this->getUserManager()->hasAccessBackend();
}
],
],
],
];
}

/**
* Liste les points de vente.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserGroupSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

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

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

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', "Groupe d'utilisateur ajouté.");
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
} }

/**
* Liste les points de vente.
*
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserGroupSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

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

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

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', "Groupe d'utilisateur ajouté.");
return $this->redirect(['index']);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}

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

if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', "Groupe d'utilisateur modifié.");
return $this->redirect(['index']);
}
else {
return $this->render('update', [
'model' => $model,
]);
}
}

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

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

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

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

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', "Groupe d'utilisateur modifié.");
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
} }

/**
* 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)
{
if (($model = UserGroup::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}

/**
* Supprime un groupe d'utilisateur.
*/
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é.');

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

/**
* Recherche un groupe d'utilisateur en fonction de son ID.
*/
protected function findModel(int $id)
{
$userGroupManager = $this->getUserGroupManager();
if (($model = $userGroupManager->findOneUserGroupById($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
} }
}


} }

+ 36
- 0
backend/forms/ProductPriceUploadForm.php View File

<?php

namespace backend\forms;

use yii\base\Model;
use yii\web\UploadedFile;

/**
* UploadForm is the model behind the upload form.
*/
class ProductPriceUploadForm extends Model
{
/**
* @var UploadedFile file attribute
*/
public $file;

/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file', 'skipOnEmpty' => false, 'mimeTypes' => 'text/csv, text/plain'],
];
}

public function attributeLabels()
{
return [
'file' => "Fichier d'import (CSV)"
];
}
}

?>

+ 4
- 8
backend/models/AccessUserProducerForm.php View File

namespace backend\models; namespace backend\models;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use Yii;
use common\logic\User\User\Model\User;
use yii\base\Model; use yii\base\Model;
use common\models\User ;
use common\models\Producer ;
use common\models\UserProducer ;


/** /**
* ContactForm is the model behind the contact form. * ContactForm is the model behind the contact form.
*/ */
class AccessUserProducerForm extends Model class AccessUserProducerForm extends Model
{ {

public $id_user ; public $id_user ;


/** /**
public function save() public function save()
{ {
$user = User::searchOne([
$user = User::searchOne([
'id' => $this->id_user 'id' => $this->id_user
]) ; ]) ;
if($user) { if($user) {
$user->id_producer = GlobalParam::getCurrentProducerId() ; $user->id_producer = GlobalParam::getCurrentProducerId() ;
if($user->status != User::STATUS_PRODUCER && $user->status != User::STATUS_ADMIN) {
$user->status = User::STATUS_PRODUCER ;
if($user->status != User::STATUS_PRODUCER && $user->status != User::STATUS_ADMIN) {
$user->status = User::STATUS_PRODUCER ;
} }
return $user->save(); return $user->save();
} }

+ 23
- 18
backend/models/CreditForm.php View File



use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Mailjet; use common\helpers\Mailjet;
use common\logic\Producer\Producer\Wrapper\ProducerManager;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\logic\User\CreditHistory\Wrapper\CreditHistoryManager;
use common\logic\User\User\Model\User;
use common\logic\User\User\Wrapper\UserManager;
use common\logic\User\UserProducer\Model\UserProducer;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\CreditHistory ;
use common\models\User ;
use common\models\Producer ;
use common\models\UserProducer ;
use common\helpers\Mail ;


/** /**
* ContactForm is the model behind the contact form. * ContactForm is the model behind the contact form.
*/ */
public function save() public function save()
{ {
$userManager = UserManager::getInstance();
$creditHistoryManager = CreditHistoryManager::getInstance();
$producerManager = ProducerManager::getInstance();

if ($this->validate()) { if ($this->validate()) {
$creditHistory = new CreditHistory;
$creditHistory->id_user = $this->id_user;
$creditHistory->id_user_action = Yii::$app->user->identity->id;
$creditHistory->id_producer = GlobalParam::getCurrentProducerId() ;
$creditHistory->type = $this->type ;
$creditHistory->comment = $this->comment ;
$creditHistory->amount = $this->amount ;
$creditHistory->mean_payment = $this->mean_payment ;
$creditHistory->save();
$user = $userManager->findOneUserById($this->id_user);
$creditHistoryManager->createCreditHistory(
$this->type,
$this->amount,
GlobalParam::getCurrentProducer(),
$user,
Yii::$app->user->identity,
$this->mean_payment
);
// on prévient l'utilisateur que son compte vient d'être crédité // on prévient l'utilisateur que son compte vient d'être crédité
if($this->send_mail) { if($this->send_mail) {
$user = User::findOne($this->id_user) ;
$user = User::findOne($this->id_user) ;
$producer = GlobalParam::getCurrentProducer() ; $producer = GlobalParam::getCurrentProducer() ;
$userProducer = UserProducer::searchOne([
$userProducer = UserProducer::searchOne([
'id_user' => $this->id_user 'id_user' => $this->id_user
]); ]);


$paramsEmail = [ $paramsEmail = [
'from_email' => $producer->getEmailOpendistrib(),
'from_email' => $producerManager->getEmailOpendistrib($producer),
'from_name' => $producer->name, 'from_name' => $producer->name,
'to_email' => $user->email, 'to_email' => $user->email,
'to_name' => $user->getUsername(),
'to_name' => $userManager->getUsername($user),
'subject' => '['.$producer->name.'] Mouvement de crédit', 'subject' => '['.$producer->name.'] Mouvement de crédit',
'content_view_text' => '@common/mail/creditUser-text.php', 'content_view_text' => '@common/mail/creditUser-text.php',
'content_view_html' => '@common/mail/creditUser-html.php', 'content_view_html' => '@common/mail/creditUser-html.php',

+ 13
- 6
backend/models/MailForm.php View File

namespace backend\models; namespace backend\models;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Mailjet;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Producer\Producer\Wrapper\ProducerManager;
use common\logic\Product\Product\Model\Product;
use common\logic\Product\Product\Wrapper\ProductManager;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\helpers\Price ; use common\helpers\Price ;
use yii\helpers\Html;


/** /**
* ContactForm is the model behind the contact form. * ContactForm is the model behind the contact form.
*/ */
class MailForm extends Model class MailForm extends Model
{ {

public $id_distribution ; public $id_distribution ;
public $subject; public $subject;
public $message; public $message;
*/ */
public function sendEmail($usersArray, $fromProducer = true) public function sendEmail($usersArray, $fromProducer = true)
{ {
$productManager = ProductManager::getInstance();
$producerManager = ProducerManager::getInstance();

$mj = new \Mailjet\Client( $mj = new \Mailjet\Client(
Mailjet::getApiKey('public'), Mailjet::getApiKey('public'),
Mailjet::getApiKey('private'), Mailjet::getApiKey('private'),
'.$linkOrder ; '.$linkOrder ;


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


$messageAutoText .= '- '.$productDescription.' $messageAutoText .= '- '.$productDescription.'
if($fromProducer) { if($fromProducer) {
$producer = GlobalParam::getCurrentProducer() ; $producer = GlobalParam::getCurrentProducer() ;
$fromEmail = $producer->getEmailOpendistrib() ;
$fromEmail = $producerManager->getEmailOpendistrib($producer) ;
$fromName = $producer->name ; $fromName = $producer->name ;
} }
else { else {
return $response ; return $response ;
} }

} }

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

use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ; use yii\helpers\ArrayHelper ;


$userManager = $this->getUserManager();

$this->setTitle('Accès') ; $this->setTitle('Accès') ;


?> ?>
</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( $userManager->populateUserDropdownList(), ['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>

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

* termes. * termes.
*/ */


use common\logic\Document\DeliveryNote\Model\DeliveryNote;
use yii\grid\GridView;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Order\Order\Model\Order;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use common\logic\Document\DeliveryNote\Wrapper\DeliveryNoteManager;

$deliveryNoteManager = $this->getDeliveryNoteManager();

$this->setTitle('Bons de livraison'); $this->setTitle('Bons de livraison');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());
$this->addButton(['label' => 'Nouveau bon de livraison <span class="glyphicon glyphicon-plus"></span>', 'url' => ['distribution/index', 'message_generate_bl' => 1], 'class' => 'btn btn-primary']); $this->addButton(['label' => 'Nouveau bon de livraison <span class="glyphicon glyphicon-plus"></span>', 'url' => ['distribution/index', 'message_generate_bl' => 1], 'class' => 'btn btn-primary']);
?> ?>


<div class="delivery-note-index"> <div class="delivery-note-index">
<?php if(DeliveryNote::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function($model) {
return $model->getHtmlLabel() ;
}
],
[
'attribute' => 'reference',
'value' => function($model) {
if(strlen($model->reference) > 0) {
return $model->reference ;
}
return '' ;
}
],
'name',
[
'attribute' => 'date_distribution',
'header' => 'Jour de distribution',
'filter' => \yii\jui\DatePicker::widget([
'language' => 'fr',
'dateFormat' => 'dd/MM/yyyy',
'model' => $searchModel,
'attribute' => 'date_distribution',
'options' => ['class' => 'form-control']
]),
'value' => function($model) {
$distribution = $model->getDistribution() ;
if($distribution) {
return date('d/m/Y',strtotime($distribution->date)) ;
}
return '' ;
}
],
[
'attribute' => 'id_point_sale',
'header' => 'Point de vente',
'filter' => ArrayHelper::map(PointSale::searchAll([], ['as_array'=>true]), 'id', 'name'),
'format' => 'html',
'value' => function($model) {
$pointSale = $model->getPointSale() ;
if($pointSale) {
return Html::encode($pointSale->name);
}
return '' ;
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function($deliveryNote) {
return $deliveryNote->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL, true) ;
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{validate} {update} {delete} {send} {download}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'send' => function($url, $model) {
return ((isset($model->user) && strlen($model->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function($url, $model) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'validate' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'update' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucun bon de livraison enregistré</div>
<?php endif; ?>
<?php if (DeliveryNote::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function ($model) use ($deliveryNoteManager) {
return $deliveryNoteManager->getHtmlLabel($model);
}
],
[
'attribute' => 'reference',
'value' => function ($model) {
return (strlen($model->reference) > 0) ? $model->reference : '';
}
],
'name',
[
'attribute' => 'date_distribution',
'header' => 'Jour de distribution',
'filter' => \yii\jui\DatePicker::widget([
'language' => 'fr',
'dateFormat' => 'dd/MM/yyyy',
'model' => $searchModel,
'attribute' => 'date_distribution',
'options' => ['class' => 'form-control']
]),
'value' => function ($model) use ($deliveryNoteManager) {
$distribution = $deliveryNoteManager->getDistribution($model);
return $distribution ? date('d/m/Y', strtotime($distribution->date)) : '';
}
],
[
'attribute' => 'id_point_sale',
'header' => 'Point de vente',
'filter' => ArrayHelper::map(PointSale::searchAll([], ['as_array' => true]), 'id', 'name'),
'format' => 'html',
'value' => function ($model) use ($deliveryNoteManager) {
$pointSale = $deliveryNoteManager->getPointSale($model);
return $pointSale ? Html::encode($pointSale->name) : '';
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function ($deliveryNote) use ($deliveryNoteManager) {
return $deliveryNoteManager->getAmountWithTax($deliveryNote, Order::INVOICE_AMOUNT_TOTAL, true);
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{validate} {update} {delete} {send} {download}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'send' => function ($url, $deliveryNote) use ($deliveryNoteManager) {
return ((isset($deliveryNote->user) && strlen($deliveryNote->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function ($url, $deliveryNote) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'validate' => function ($url, $deliveryNote) use ($deliveryNoteManager) {
return ($deliveryNoteManager->isStatusDraft($deliveryNote) ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'update' => function ($url, $deliveryNote) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $deliveryNote) use ($deliveryNoteManager) {
return ($deliveryNoteManager->isStatusDraft($deliveryNote) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucun bon de livraison enregistré</div>
<?php endif; ?>
</div> </div>

+ 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]) ?>

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

use yii\grid\GridView; use yii\grid\GridView;
use common\models\Development; use common\models\Development;
use common\models\DevelopmentPriority; use common\models\DevelopmentPriority;
use common\models\User;
use common\models\ User;
use common\helpers\Url; use common\helpers\Url;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;


</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>';
]; ];




if (User::hasAccessBackend()) {
if ($this->getUserManager()->hasAccessBackend()) {


$columns[] = [ $columns[] = [
'header' => 'Priorité', 'header' => 'Priorité',
</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 />';


]; ];
} }


if (User::getCurrentStatus() == USER::STATUS_ADMIN) {
if ( User::getCurrentStatus() == User::STATUS_ADMIN) {
$columns[] = [ $columns[] = [
'class' => 'yii\grid\ActionColumn', 'class' => 'yii\grid\ActionColumn',
'template' => '{update}', 'template' => '{update}',

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

use yii\grid\GridView; use yii\grid\GridView;
use common\models\Development; use common\models\Development;
use common\models\DevelopmentPriority; use common\models\DevelopmentPriority;
use common\models\User;
use common\models\ User;
use common\helpers\Url; use common\helpers\Url;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;



+ 17
- 7
backend/views/distribution/index.php View File

<input type="text" v-model="order.productOrder[product.id].price_with_tax" class="form-control input-sm" @change="productPriceChange" :data-with-tax="true" :data-id-product="product.id" /> <input type="text" v-model="order.productOrder[product.id].price_with_tax" class="form-control input-sm" @change="productPriceChange" :data-with-tax="true" :data-id-product="product.id" />
<span class="input-group-addon" id="basic-addon2">€ TTC</span> <span class="input-group-addon" id="basic-addon2">€ TTC</span>
</div> </div>
<div v-if="(order.id_invoice || order.id_delivery_note || order.id_quotation) && order.productOrder[product.id].quantity > 0">
<span class="label label-default">
Facturé
<template v-if="order.productOrder[product.id].invoice_price != null">{{ order.productOrder[product.id].invoice_price }}</template>
<template v-else>{{ order.productOrder[product.id].price }}</template>
€ HT
</span>
<div class="invoice-price" v-show="vatMode == 'all'" v-if="(order.id_invoice || order.id_delivery_note || order.id_quotation) && order.productOrder[product.id].quantity > 0">
<span class="label-invoice-price">Prix facturé</span><br />
<div class="input-group">
<input type="text" v-model="order.productOrder[product.id].invoice_price" class="form-control input-sm" :data-id-product="product.id" />
<span class="input-group-addon" id="basic-addon2">€ HT</span>
</div>
</div> </div>
</td> </td>
<td class="quantity"> <td class="quantity">
</modal> </modal>
</script> </script>


<script type="text/x-template" id="order-state-payment">
<div class="input-group">
<span class="label label-success input-group-addon" v-if="order.amount_paid == order.amount">payé</span>
<span class="label label-default input-group-addon" v-else-if="order.amount_paid == 0">non réglé</span>
<span class="label label-default input-group-addon" v-else-if="order.amount_paid > order.amount">surplus</span>
<span class="label label-warning input-group-addon" v-else-if="order.amount_paid < order.amount">reste à payer</span>

<span class="glyphicon glyphicon-time" title="Paiement automatique" v-if="order.auto_payment && producer && producer.credit && (order.amount_paid == 0 || order.amount_paid < order.amount)"></span>
</div>
</script>

<!-- template for the modal component --> <!-- template for the modal component -->
<script type="text/x-template" id="modal-template"> <script type="text/x-template" id="modal-template">
<transition name="modal"> <transition name="modal">

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

termes. termes.
*/ */


use common\models\Order ;
use common\models\Product ;
use common\helpers\Price;
use common\logic\Order\Order\Wrapper\OrderManager;
use common\logic\Product\Product\Model\Product;
use common\logic\Product\Product\Wrapper\ProductManager;
use common\logic\User\UserProducer\Model\UserProducer;

$productManager = ProductManager::getInstance();
$orderManager = OrderManager::getInstance();


$dayWeek = date('w', strtotime($date)); $dayWeek = date('w', strtotime($date));
$dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday']; $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
$fieldInfosPointSale = 'infos_' . $dayWeekArray[$dayWeek]; $fieldInfosPointSale = 'infos_' . $dayWeekArray[$dayWeek];

$html = '' ; $html = '' ;

$count = count($productsArray) ; $count = count($productsArray) ;
$limit = 100 ; $limit = 100 ;
$isBig = $count > $limit ; $isBig = $count > $limit ;
$strUser = ''; $strUser = '';


// username // username
$strUser = $order->getStrUser() ;
$strUser = $orderManager->getOrderUsername($order) ;
if(strlen($order->comment_point_sale)) if(strlen($order->comment_point_sale))
{ {
$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 = ( $productManager->strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->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 = UserProducer::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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = ( $productManager->strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = ( Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = ( $productManager->strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->strUnit($unit, 'wording_short', true) ;
$html .= $product->name . ' (' .$quantity .$theUnit.')<br />'; $html .= $product->name . ' (' .$quantity .$theUnit.')<br />';
} }
} }

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

<?php <?php


$html = '' ;

foreach($pointsSaleArray as $keyPointSale => $pointSale) {

if(isset($ordersArray[$pointSale->id]) && count($ordersArray[$pointSale->id]) > 0) {
$html .= '<h1>'.$pointSale->name.'</h1>' ;

foreach ($ordersArray[$pointSale->id] as $indexPage => $orders) {

$html .= '<table class="">'
. '<thead>'
. '<tr>'
. '<th></th>';

foreach ($orders as $order) {
$html .= '<th class="th-user" text-rotate="90">'
. '<div class="user">' . $order->getStrUser() . '</div>'
//.'<div class="amount">'.number_format($order->amount_with_tax, 2) .' € </div>'
. '</th>';
}

$html .= '</tr>'
. '<thead>'
. '<tbody>';


foreach ($categoriesArray as $category) {
if ($category) {
$html .= '<tr><td class="category-name">' . $category->name . '</td><td colspan="' . (count($orders)) . '"></td></tr>';
}

foreach ($productsArray as $product) {
if (($category && $product->id_product_category == $category->id) || (!$category && !$product->id_product_category)) {
$html .= line_product($product, $orders);
}
}
}

$html .= '</tbody>'
. '</table>';
$html .= '<pagebreak>';


$html .= '<table class="">'
. '<thead>'
. '<tr>'
. '<th>Client</th>'
. '<th>Contact</th>'
. '<th>Commentaire</th>'
. '<th>Montant</th>'
. '</thead>'
. '<tbody>';

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

$html .= '<td>' . $strUser . '</td>';
$contactUser = '';
if ($order->user) {
$contactUser .= $order->user->phone . '<br />' . $order->user->email;
}
$html .= '<td>' . $contactUser . '</td>';
$html .= '<td>' . nl2br($order->comment) . '</td>';
$html .= '<td>' . number_format($order->amount_with_tax, 2) . ' € </td>';
$html .= '</tr>';
}

$html .= '</tbody></table>';

$html .= ' <pagebreak>';
use common\logic\Order\Order\Wrapper\OrderManager;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Product\Product\Wrapper\ProductManager;

$orderManager = OrderManager::getInstance();

$html = '';

foreach ($pointsSaleArray as $keyPointSale => $pointSale) {

if (isset($ordersArray[$pointSale->id]) && count($ordersArray[$pointSale->id]) > 0) {
$html .= '<h1>' . $pointSale->name . '</h1>';

foreach ($ordersArray[$pointSale->id] as $indexPage => $orders) {

$html .= '<table class="">'
. '<thead>'
. '<tr>'
. '<th></th>';

foreach ($orders as $order) {
$html .= '<th class="th-user" text-rotate="90">'
. '<div class="user">' . $orderManager->getOrderUsername($order) . '</div>'
//.'<div class="amount">'.number_format($order->amount_with_tax, 2) .' € </div>'
. '</th>';
}

$html .= '</tr>'
. '<thead>'
. '<tbody>';


foreach ($categoriesArray as $category) {
if ($category) {
$html .= '<tr><td class="category-name">' . $category->name . '</td><td colspan="' . (count($orders)) . '"></td></tr>';
} }

foreach ($productsArray as $product) {
if (($category && $product->id_product_category == $category->id) || (!$category && !$product->id_product_category)) {
$html .= line_product($product, $orders);
}
}
}

$html .= '</tbody>'
. '</table>';
$html .= '<pagebreak>';


$html .= '<table class="">'
. '<thead>'
. '<tr>'
. '<th>Client</th>'
. '<th>Contact</th>'
. '<th>Commentaire</th>'
. '<th>Montant</th>'
. '</thead>'
. '<tbody>';

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

$html .= '<td>' . $strUser . '</td>';
$contactUser = '';
if ($order->user) {
$contactUser .= $order->user->phone . '<br />' . $order->user->email;
}
$html .= '<td>' . $contactUser . '</td>';
$html .= '<td>' . nl2br($order->comment) . '</td>';
$html .= '<td>' . number_format($order->amount_with_tax, 2) . ' € </td>';
$html .= '</tr>';
}

$html .= '</tbody></table>';

$html .= ' <pagebreak>';
} }
}
} }


$html = substr($html, 0, strlen($html) - 11) ;

echo $html ;
$html = substr($html, 0, strlen($html) - 11);


function line_product($product, $orders) {
$html = '' ;
echo $html;


if(has_quantity($product, $orders)) {
$html .= '<tr>' ;
$html .= '<td>'.$product->name.'</td>' ;
function line_product($product, $orders)
{
$productManager = ProductManager::getInstance();
$html = '';


foreach($orders as $order) {
$quantity = '' ;
foreach($order->productOrder as $productOrder) {
if($product->id == $productOrder->id_product) {
$unit = (Product::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($productOrder->unit, 'wording_short', true) ;
if (has_quantity($product, $orders)) {
$html .= '<tr>';
$html .= '<td>' . $product->name . '</td>';


$quantity .= $productOrder->quantity .$unit ;
if($productOrder->quantity > 1) {
$quantity = '<strong>'.$quantity.'</strong>' ;
}
}
}
foreach ($orders as $order) {
$quantity = '';
foreach ($order->productOrder as $productOrder) {
if ($product->id == $productOrder->id_product) {
$unit = ($productManager->strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;' . $productManager->strUnit($productOrder->unit, 'wording_short', true);


$html .= '<td class="td-nb-products">'.$quantity.'</td>' ;
$quantity .= $productOrder->quantity . $unit;
if ($productOrder->quantity > 1) {
$quantity = '<strong>' . $quantity . '</strong>';
}
} }
}


$html .= '</tr>' ;
$html .= '<td class="td-nb-products">' . $quantity . '</td>';
} }


return $html ;
$html .= '</tr>';
}

return $html;
} }


function has_quantity($product, $orders) {
foreach($orders as $order) {
foreach($order->productOrder as $productOrder) {
if($product->id == $productOrder->id_product) {
return true ;
}
}
function has_quantity($product, $orders)
{
foreach ($orders as $order) {
foreach ($order->productOrder as $productOrder) {
if ($product->id == $productOrder->id_product) {
return true;
}
} }
}


return false ;
return false;
} }

+ 33
- 30
backend/views/distribution/report.php View File

termes. termes.
*/ */


use common\models\Order ;
use common\models\Product ;

use common\helpers\Price;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\Order\Wrapper\OrderManager;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Product\Product\Model\Product;
use common\logic\Product\Product\Wrapper\ProductManager;
use common\logic\User\UserProducer\Model\UserProducer;

$productManager = ProductManager::getInstance();
$orderManager = OrderManager::getInstance();


$dayWeek = date('w', strtotime($date)); $dayWeek = date('w', strtotime($date));
$dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday']; $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
$fieldInfosPointSale = 'infos_' . $dayWeekArray[$dayWeek]; $fieldInfosPointSale = 'infos_' . $dayWeekArray[$dayWeek];

$html = '' ; $html = '' ;

$count = count($productsArray) ; $count = count($productsArray) ;
$limit = 100 ; $limit = 100 ;
$isBig = $count > $limit ; $isBig = $count > $limit ;
$strUser = ''; $strUser = '';


// username // username
$strUser .= $order->getStrUser() ;
$strUser .= $orderManager->getOrderUsername($order) ;
if(strlen($order->comment_point_sale)) if(strlen($order->comment_point_sale))
{ {
$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) ;
$strProducts .= '('.$productOrder->quantity .$unit.') '.$product->getNameExport() . '<br />';
$unit = ( $productManager->strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->strUnit($productOrder->unit, 'wording_short', true) ;
$strProducts .= '('.$productOrder->quantity .$unit.') '.$productManager->getNameExport($product) . '<br />';
$add = true; $add = true;
} }
} }
if($isBig) { if($isBig) {
$html .= '<td></td>' ; $html .= '<td></td>' ;
} }
$html .= '<td>'.$order->getCommentReport().'</td>';
$html .= '<td>'.$orderManager->getCommentReport($order).'</td>';
if($pointSale->credit) { if($pointSale->credit) {
$credit = '' ; $credit = '' ;


if(isset($order->user) && $order->user->id) { if(isset($order->user) && $order->user->id) {
$userProducer = UserProducer::searchOne([
$userProducer = UserProducer::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($orderManager->getPaymentStatus($order) == Order::PAYMENT_PAID)
{ {
$html .= '(payé)' ; $html .= '(payé)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_UNPAID && $order->getAmount(Order::AMOUNT_PAID))
elseif($orderManager->getPaymentStatus($order) == Order::PAYMENT_UNPAID && $orderManager->getOrderAmount($order, Order::AMOUNT_PAID))
{ {
$html .= '(reste '.$order->getAmount(Order::AMOUNT_REMAINING, true).' à payer)' ;
$html .= '(reste '.$orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING, true).' à payer)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_SURPLUS)
elseif($orderManager->getPaymentStatus($order) == Order::PAYMENT_SURPLUS)
{ {
$html .= '(surplus : '.$order->getAmount(Order::PAYMENT_SURPLUS, true).' à rembourser)' ;
$html .= '(surplus : '.$orderManager->getOrderAmount($order, Order::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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$strProducts .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />';
$theUnit = ( $productManager->strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->strUnit($unit, 'wording_short', true) ;
$strProducts .= '(' .$quantity .$theUnit.') '.$productManager->getNameExport($product) . '<br />';
} }
} }




$cpt ++ ; $cpt ++ ;
} }
//$strProducts = substr($strProducts, 0, strlen($strProducts) - 6) ;

$html .= '<td>'.$strProducts.'</td><td></td>' ; $html .= '<td>'.$strProducts.'</td><td></td>' ;
if($pointSale->credit) { if($pointSale->credit) {
$html .= '<td></td>' ; $html .= '<td></td>' ;


$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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$html .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />';
$theUnit = ( $productManager->strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->strUnit($unit, 'wording_short', true) ;
$html .= '(' .$quantity .$theUnit.') '.$productManager->getNameExport($product) . '<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( Product::$unitsArray as $unit => $dataUnit) {
$quantity = $orderManager->getProductQuantity($product, $ordersArray, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = ( $productManager->strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'. $productManager->strUnit($unit, 'wording_short', true) ;
$html .= '(' .$quantity .$theUnit.') '.$product->name . '<br />'; $html .= '(' .$quantity .$theUnit.') '.$product->name . '<br />';
} }
} }
$cpt ++ ; $cpt ++ ;
} }


//$html = substr($html, 0, strlen($html) - 6) ;

$html .= '</td><td><strong>'.number_format($revenues, 2).' €</strong></td></tr>' ; $html .= '</td><td><strong>'.number_format($revenues, 2).' €</strong></td></tr>' ;


$html .= '</tbody></table>' ; $html .= '</tbody></table>' ;

+ 15
- 4
backend/views/document/_download_product_line.php View File

<?php

use common\helpers\Price;
use common\logic\Product\Product\Model\Product;
use yii\helpers\Html;

$documentManager = $this->getDocumentManager();
$productManager = $this->getProductManager();

?>

<tr class="<?php if(isset($displayOrders) && $displayOrders): ?>order<?php endif; ?>"> <tr class="<?php if(isset($displayOrders) && $displayOrders): ?>order<?php endif; ?>">
<td class="align-left"> <td class="align-left">
<?php if($productOrder->product): ?> <?php if($productOrder->product): ?>


<?php <?php
$price = $productOrder->getPrice() ; $price = $productOrder->getPrice() ;
if($document->isInvoicePrice() && $productOrder->getInvoicePrice()) {
if($documentManager->isInvoicePrice($document) && $productOrder->getInvoicePrice()) {
$price = $productOrder->getInvoicePrice() ; $price = $productOrder->getInvoicePrice() ;
} }
?> ?>
</td> </td>
<?php endif; ?> <?php endif; ?>
<td class="align-center"> <td class="align-center">
<?= $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'] ?>
<?= $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'] ?>
</td> </td>
<td class="align-center"><?= Product::strUnit($productOrder->unit, 'wording') ?></td>
<td class="align-center"><?= $productManager->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>
<?php endif; ?> <?php endif; ?>
<td class="align-center"> <td class="align-center">
<?php if($document->getClass() == ''): ?>
<?php if($documentManager->getClass($document) == ''): ?>
<?= Price::format($price * $productOrder->quantity) ?> <?= Price::format($price * $productOrder->quantity) ?>
<?php else: ?> <?php else: ?>
<?= Price::format($price * $productOrder->quantity) ?> <?= Price::format($price * $productOrder->quantity) ?>

+ 18
- 12
backend/views/document/_form.php View File

* termes. * termes.
*/ */


use common\logic\Document\Document\Wrapper\DocumentManager;
use common\logic\Producer\Producer\Wrapper\ProducerManager;
use common\logic\User\User\Model\User;
use common\logic\User\User\Wrapper\UserManager;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\models\Product;
use yii\helpers\ArrayHelper;
use common\models\TaxRate;
use common\models\Producer;


\backend\assets\VuejsDocumentFormAsset::register($this); \backend\assets\VuejsDocumentFormAsset::register($this);


$producerManager = ProducerManager::getInstance();
$documentManager = DocumentManager::getInstance();
$userManager = UserManager::getInstance();

$documentClass = $documentManager->getClass($model);

?> ?>


<div class="document-form" id="app-document-form" data-class-document="<?= $model->getClass() ?>"
<div class="document-form" id="app-document-form" data-class-document="<?= $documentClass ?>"
data-id-document="<?= ($model->id > 0) ? $model->id : $model->id ?>"> data-id-document="<?= ($model->id > 0) ? $model->id : $model->id ?>">


<div class="<?= ($action == 'update') ? 'col-md-6' : '' ?>"> <div class="<?= ($action == 'update') ? 'col-md-6' : '' ?>">
</div> </div>
<div class="panel-body"> <div class="panel-body">
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= Html::hiddenInput('classDocument', $model->getClass(), ['id' => 'class-document']) ?>
<?= Html::hiddenInput('classDocument', $documentClass, ['id' => 'class-document']) ?>
<?= Html::hiddenInput('typeAction', $action, ['id' => 'type-action']) ?> <?= Html::hiddenInput('typeAction', $action, ['id' => 'type-action']) ?>
<?php if ($action == 'update'): ?> <?php if ($action == 'update'): ?>
<?= Html::hiddenInput('idDocument', $model->id, ['id' => 'id-document']) ?> <?= Html::hiddenInput('idDocument', $model->id, ['id' => 'id-document']) ?>


<?php if ($action == 'update'): ?> <?php if ($action == 'update'): ?>
<?= $form->field($model, 'id_user', [ <?= $form->field($model, 'id_user', [
'template' => '{label} <div>{input}</div>' . $model->user->getUsername(),
'template' => '{label} <div>{input}</div>' . $userManager->getUsername($model->user),
])->hiddenInput(); ?> ])->hiddenInput(); ?>
<?php else: ?> <?php else: ?>
<?= $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( ->dropDownList(
User::populateDropdownList(),
$userManager->populateUserDropdownList(),
[ [
'@change' => 'changeUser', '@change' => 'changeUser',
'v-model' => 'idUser', 'v-model' => 'idUser',
<?= $form->field($model, 'comment')->textarea(['rows' => 2])->hint('Affiché en bas du document') ?> <?= $form->field($model, 'comment')->textarea(['rows' => 2])->hint('Affiché en bas du document') ?>
<?php endif; ?> <?php endif; ?>


<?php if ($action == 'create' && $model->getClass() == 'Invoice'): ?>
<?php if ($action == 'create' && $documentClass == 'Invoice'): ?>
<template v-if="idUser > 0"> <template v-if="idUser > 0">
<strong>Bons de livraison</strong> <strong>Bons de livraison</strong>
<table v-if="deliveryNoteCreateArray && deliveryNoteCreateArray.length > 0" class="table table-bordered"> <table v-if="deliveryNoteCreateArray && deliveryNoteCreateArray.length > 0" class="table table-bordered">
</div> </div>
</div> </div>


<?php if ($action == 'update' && $model->getClass() == 'Invoice'): ?>
<?php if ($action == 'update' && $documentClass == 'Invoice'): ?>
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">
Bons de livraison Bons de livraison
<a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/download', 'id' => $model->id]) ?>" <a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/download', 'id' => $model->id]) ?>"
class="btn btn-sm btn-default"><span class="glyphicon glyphicon-download-alt"></span> Télécharger (PDF)</a> class="btn btn-sm btn-default"><span class="glyphicon glyphicon-download-alt"></span> Télécharger (PDF)</a>


<?php if($model->isStatusValid()): ?>
<?php if($documentManager->isStatusValid($model)): ?>
<a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/regenerate', 'id' => $model->id]) ?>" <a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/regenerate', 'id' => $model->id]) ?>"
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 ($documentClass == 'Invoice' && $producerManager->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>

+ 29
- 20
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');
use yii\helpers\Html;
use common\logic\Order\Order\Model\Order;
use common\helpers\Price;

$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();
$documentManager = $this->getDocumentManager();
$orderManager = $this->getOrderManager();

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


?> ?>


<div class="producer"> <div class="producer">
<?php if (strlen($producer->logo)) : ?> <?php if (strlen($producer->logo)) : ?>
<div class="logo"> <div class="logo">
<img style="max-height: 80px;" src="<?= $producer->getUrlLogo() ?>"/>
<img style="max-height: 80px;" src="<?= $producerManager->getUrlLogo($producer) ?>"/>
</div> </div>
<?php endif; ?> <?php endif; ?>
<div class="address"><?= $producer->getFullAddress(true); ?></div>
<div class="address"><?= $producerManager->getFullAddress($producer, true); ?></div>
</div> </div>
<div class="user"> <div class="user">
<?php if ($document->address && strlen($document->address) > 0): ?> <?php if ($document->address && strlen($document->address) > 0): ?>
<?= nl2br($document->address) ?> <?= nl2br($document->address) ?>
<?php else: ?> <?php else: ?>
<?= $document->user->getFullAddress(true); ?>
<?= $userManager->getFullAddress($document->user, true); ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
</div> </div>
</div> </div>
<div class="reference"> <div class="reference">
<?php if (strlen($document->reference)) : ?> <?php if (strlen($document->reference)) : ?>
<?= $document->getType(); ?> N°<?= $document->reference; ?>
<?= $documentManager->getType($document); ?> N°<?= $document->reference; ?>
<?php else: ?> <?php else: ?>
<div class="block-is-draft"><?= $document->getType(); ?> non
validé<?= ($document->getType() == 'Facture') ? 'e' : '' ?></div>
<div class="block-is-draft"><?= $documentManager->getType($document); ?> non
validé<?= ($documentManager->getType($document) == 'Facture') ? 'e' : '' ?></div>
<?php endif; ?> <?php endif; ?>
</div> </div>
<div class="name"> <div class="name">
</thead> </thead>
<tbody> <tbody>


<?php if ($document->isDisplayOrders()): ?>
<?php if ($producerManager->isDocumentDisplayOrders($document)): ?>
<?php foreach ($document->orders as $order): ?> <?php foreach ($document->orders as $order): ?>
<tr> <tr>
<td> <td>
<strong><?= Html::encode($order->getUsername()); ?></strong>
<strong><?= Html::encode($orderManager->getOrderUsername($order)); ?></strong>
<?php if ($order->distribution): ?> <?php if ($order->distribution): ?>
le <?= date('d/m/Y', strtotime($order->distribution->date)) ?> le <?= date('d/m/Y', strtotime($order->distribution->date)) ?>
<?php endif; ?> <?php endif; ?>
<?php endforeach; ?> <?php endforeach; ?>
<?php endforeach; ?> <?php endforeach; ?>
<?php else: ?> <?php else: ?>
<?php foreach ($document->getProductsOrders() as $product): ?>
<?php foreach ($documentManager->getProductsOrders($document) as $product): ?>
<?php foreach ($product as $productOrder): ?> <?php foreach ($product as $productOrder): ?>
<?= $this->render('_download_product_line', [ <?= $this->render('_download_product_line', [
'producer' => $producer, 'producer' => $producer,
<?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 = $documentManager->isInvoicePrice($document) ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL; ?>


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


<tr> <tr>
<td class="align-right" colspan="5"><strong>Total HT</strong></td> <td class="align-right" colspan="5"><strong>Total HT</strong></td>
<td class="align-center"> <td class="align-center">
<?= Price::format($document->getAmount($typeAmount)); ?>
<?= Price::format($documentManager->getAmount($document, $typeAmount)); ?>
</td> </td>
</tr> </tr>


<?php <?php
$taxRateArray = TaxRate::getTaxRateArray();
foreach ($document->getTotalVatArray($typeAmount) as $idTaxRate => $totalVat): ?>
$taxRateArray = $this->getTaxRateManager()->findTaxRatesAsArray();
foreach ($documentManager->getTotalVatArray($document, $typeAmount) as $idTaxRate => $totalVat): ?>
<tr> <tr>
<td class="align-right" colspan="5"> <td class="align-right" colspan="5">
<strong>TVA <?= $taxRateArray[$idTaxRate]->value * 100 ?> %</strong></td> <strong>TVA <?= $taxRateArray[$idTaxRate]->value * 100 ?> %</strong></td>
<!--<tr> <!--<tr>
<td class="align-right" colspan="5"><strong>TVA</strong></td> <td class="align-right" colspan="5"><strong>TVA</strong></td>
<td class="align-center"> <td class="align-center">
<?= Price::format($document->getAmountWithTax($typeAmount) - $document->getAmount($typeAmount)) ?>
<?= Price::format($documentManager->getAmountWithTax($document, $typeAmount) - $documentManager->getAmount($document, $typeAmount)) ?>
</td> </td>
</tr>--> </tr>-->
<tr> <tr>
<td class="align-right" colspan="5"><strong>Total TTC</strong></td> <td class="align-right" colspan="5"><strong>Total TTC</strong></td>
<td class="align-center"><?= Price::format($document->getAmountWithTax($typeAmount)) ?></td>
<td class="align-center"><?= Price::format($documentManager->getAmountWithTax($document, $typeAmount)) ?></td>
</tr> </tr>
<?php else: ?> <?php else: ?>
<tr> <tr>
<strong>Total</strong><br/> <strong>Total</strong><br/>
TVA non applicable TVA non applicable
</td> </td>
<td class="align-center"><?= Price::format($document->getAmount($typeAmount)) ?></td>
<td class="align-center"><?= Price::format($documentManager->getAmount($document, $typeAmount)) ?></td>
</tr> </tr>
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
</div> </div>


<?php <?php
$fieldProducerDocumentInfo = 'document_infos_' . str_replace('deliverynote', 'delivery_note', strtolower($document->getClass())); ?>
$fieldProducerDocumentInfo = 'document_infos_' . str_replace('deliverynote', 'delivery_note', strtolower($documentManager->getClass($document))); ?>
<?php if (strlen($producer->$fieldProducerDocumentInfo)): ?> <?php if (strlen($producer->$fieldProducerDocumentInfo)): ?>
<div class="block-infos"> <div class="block-infos">
<strong>Informations</strong><br/> <strong>Informations</strong><br/>

+ 109
- 110
backend/views/invoice/index.php View File

use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\helpers\Url; use common\helpers\Url;
use common\models\Product;
use common\models\TaxRate;
use common\models\Producer;
use common\logic\Document\Invoice\Model\Invoice;
use common\logic\Order\Order\Model\Order;

$producerManager = $this->getProducerManager();
$invoiceManager = $this->getInvoiceManager();
$userManager = $this->getUserManager();


$this->setTitle('Factures'); $this->setTitle('Factures');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());


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


<?php if(Invoice::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function($model) {
return $model->getHtmlLabel() ;
}
],
[
'attribute' => 'reference',
'value' => function($model) {
if(strlen($model->reference) > 0) {
return $model->reference ;
}
return '' ;
}
],
'name',
[
'attribute' => 'username',
'header' => 'Utilisateur',
'value' => function($model) {
return $model->user->getUsername() ;
}
],
[
'attribute' => 'date',
'header' => 'Date',
'value' => function($model) {
return date('d/m/Y',strtotime($model->date)) ;
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function($invoice) {
return $invoice->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL, true) ;
}
],
[
'attribute' => 'is_sent',
'header' => 'Envoyé',
'format' => 'raw',
'value' => function($model) {
if($model->is_sent) {
return '<span class="label label-success">Oui</span>';
}
else {
return '<span class="label label-danger">Non</span>';
}
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{validate} {update} {delete} {send} {download} {export-csv-evoliz}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'validate' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'send' => function($url, $model) {
return ((isset($model->user) && strlen($model->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function($url, $model) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'export-csv-evoliz' => function($url, $model) {
if(Producer::getConfig('option_export_evoliz')) {
return Html::a('<span class="glyphicon glyphicon-save-file"></span> Evoliz', $url, [
'title' => 'Export CSV Evoliz', 'class' => 'btn btn-default'
]);
}
<?php if (Invoice::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function ($invoice) use ($invoiceManager) {
return $invoiceManager->getHtmlLabel($invoice);
}
],
[
'attribute' => 'reference',
'value' => function ($invoice) {
return (strlen($invoice->reference) > 0) ? $invoice->reference : '';
}
],
'name',
[
'attribute' => 'username',
'header' => 'Utilisateur',
'value' => function ($invoice) use ($userManager) {
return $userManager->getUsername($invoice->user);
}
],
[
'attribute' => 'date',
'header' => 'Date',
'value' => function ($invoice) {
return date('d/m/Y', strtotime($invoice->date));
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function ($invoice) use ($invoiceManager) {
return $invoiceManager->getAmountWithTax($invoice, Order::INVOICE_AMOUNT_TOTAL, true);
}
],
[
'attribute' => 'is_sent',
'header' => 'Envoyé',
'format' => 'raw',
'value' => function ($model) {
if ($model->is_sent) {
return '<span class="label label-success">Oui</span>';
} else {
return '<span class="label label-danger">Non</span>';
}
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{validate} {update} {delete} {send} {download} {export-csv-evoliz}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'validate' => function ($url, $invoice) use ($invoiceManager) {
return ($invoiceManager->isStatusDraft($invoice) ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'send' => function ($url, $invoice) {
return ((isset($invoice->user) && strlen($invoice->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function ($url, $invoice) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'export-csv-evoliz' => function ($url, $invoice) use ($producerManager) {
if ($producerManager->getConfig('option_export_evoliz')) {
return Html::a('<span class="glyphicon glyphicon-save-file"></span> Evoliz', $url, [
'title' => 'Export CSV Evoliz', 'class' => 'btn btn-default'
]);
}


return '';
},
'update' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucune facture enregistrée</div>
<?php endif; ?>
return '';
},
'update' => function ($url, $invoice) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $invoice) use ($invoiceManager) {
return ($invoiceManager->isStatusDraft($invoice) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucune facture enregistrée</div>
<?php endif; ?>
</div> </div>

+ 4
- 1
backend/views/layouts/content.php View File



use yii\widgets\Breadcrumbs; use yii\widgets\Breadcrumbs;
use dmstr\widgets\Alert; use dmstr\widgets\Alert;
use common\helpers\GlobalParam;

$producerManager = $this->getProducerManager();


?> ?>
<div class="content-wrapper"> <div class="content-wrapper">
<section class="content"> <section class="content">


<?php $producer = GlobalParam::getCurrentProducer(); ?> <?php $producer = GlobalParam::getCurrentProducer(); ?>
<?php if(!$producer->isUpToDateWithOpendistribVersion() && $producer->option_display_message_new_opendistrib_version): ?>
<?php if($producer && !$producerManager->isUpToDateWithOpendistribVersion($producer) && $producer->option_display_message_new_opendistrib_version): ?>
<div class="alert alert-warning"> <div class="alert alert-warning">
<p>Opendistrib a été mis à jour vers la version <?= GlobalParam::getOpendistribVersion() ?> ! <a class="alert-link" href="<?= Yii::$app->urlManager->createUrl(['development/index']) ?>">Découvrir les nouveautés</a></p> <p>Opendistrib a été mis à jour vers la version <?= GlobalParam::getOpendistribVersion() ?> ! <a class="alert-link" href="<?= Yii::$app->urlManager->createUrl(['development/index']) ?>">Découvrir les nouveautés</a></p>
<a href="<?= Yii::$app->urlManager->createUrl(['producer/update-opendistrib-version']) ?>" class="close"><span aria-hidden="true">&times;</span></a> <a href="<?= Yii::$app->urlManager->createUrl(['producer/update-opendistrib-version']) ?>" class="close"><span aria-hidden="true">&times;</span></a>

+ 14
- 15
backend/views/layouts/header.php View File

* termes. * termes.
*/ */


use common\helpers\Price;
use common\logic\Producer\Producer\Wrapper\ProducerManager;
use common\logic\User\User\Wrapper\UserManager;
use yii\helpers\Html; use yii\helpers\Html;
use common\models\Producer;
use common\models\User;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;


/* @var $this \yii\web\View */
/* @var $content string */
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Producer\Producer\Model\Producer;


$userManager = UserManager::getInstance();
$producerManager = ProducerManager::getInstance();
$producer = GlobalParam::getCurrentProducer(); $producer = GlobalParam::getCurrentProducer();


?> ?>
<div class="navbar-custom-menu"> <div class="navbar-custom-menu">
<?php <?php


$usersArray = User::findBy(['id_producer' => GlobalParam::getCurrentProducerId()])
$usersArray = $userManager->queryUsersBy(['id_producer' => GlobalParam::getCurrentProducerId()])
->andWhere('CAST(FROM_UNIXTIME(user.created_at) AS date) > \'' . date("Y-m-d", strtotime("-7 days")) . '\'') ->andWhere('CAST(FROM_UNIXTIME(user.created_at) AS date) > \'' . date("Y-m-d", strtotime("-7 days")) . '\'')
->orderBy('created_at DESC') ->orderBy('created_at DESC')
->all(); ->all();


<?php <?php


$usersNegativeCreditArray = User::findBy(['id_producer' => GlobalParam::getCurrentProducerId()])
$usersNegativeCreditArray = $userManager->queryUsersBy(['id_producer' => GlobalParam::getCurrentProducerId()])
->andWhere('user_producer.credit < 0') ->andWhere('user_producer.credit < 0')
->orderBy('lastname, name ASC') ->orderBy('lastname, name ASC')
->all(); ->all();
<?php foreach ($usersNegativeCreditArray as $user): ?> <?php foreach ($usersNegativeCreditArray as $user): ?>
<li> <li>
<a href="<?= Yii::$app->urlManagerBackend->createUrl(['user/credit', 'id' => $user['user_id']]); ?>"> <a href="<?= Yii::$app->urlManagerBackend->createUrl(['user/credit', 'id' => $user['user_id']]); ?>">
<h5><?= User::getUsernameFromArray($user); ?>
<h5><?= $userManager->getUsernameFromArray($user); ?>
<small> <small>
<i class="fa fa-euro"></i> <?= Price::format($user['credit']); ?> <i class="fa fa-euro"></i> <?= Price::format($user['credit']); ?>
</small> </small>


</li> </li>


<?php if (User::isCurrentProducer() || User::isCurrentAdmin()): ?>
<?php if ( $userManager->isCurrentProducer() || $userManager->isCurrentAdmin()): ?>
<li class="dropdown producer-menu"> <li class="dropdown producer-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">


<?php else: ?> <?php else: ?>
<span class="label label-danger">Hors-ligne</span> <span class="label label-danger">Hors-ligne</span>
<?php endif; ?> <?php endif; ?>
<span><?= Html::encode(Yii::$app->user->identity->getNameProducer()); ?></span>
<span><?= Html::encode($producerManager->getNameProducer(Yii::$app->user->identity)); ?></span>
<i class="fa fa-caret-down"></i> <i class="fa fa-caret-down"></i>
</a> </a>


<ul class="dropdown-menu"> <ul class="dropdown-menu">
<?php if (User::isCurrentAdmin()): ?>
<?php if ( $userManager->isCurrentAdmin()): ?>
<li> <li>
<a href="<?= Yii::$app->urlManagerProducer->createAbsoluteUrl(['site/index', 'slug_producer' => GlobalParam::getCurrentProducer()->slug]); ?>"> <a href="<?= Yii::$app->urlManagerProducer->createAbsoluteUrl(['site/index', 'slug_producer' => GlobalParam::getCurrentProducer()->slug]); ?>">
<i class="fa fa-th-large"></i> <i class="fa fa-th-large"></i>
<li class="dropdown user user-menu"> <li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user"></i> <i class="fa fa-user"></i>
<span class="hidden-xs"><?= Html::encode(User::getCurrent()->name . ' ' . User::getCurrent()->lastname); ?></span>
<span class="hidden-xs"><?= Html::encode( GlobalParam::getCurrentUser()->name . ' ' . GlobalParam::getCurrentUser()->lastname); ?></span>
<i class="fa fa-caret-down"></i> <i class="fa fa-caret-down"></i>
</a> </a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
class="fa fa-sign-out"></i> Déconnexion</a></li> class="fa fa-sign-out"></i> Déconnexion</a></li>
</ul> </ul>
</li> </li>

<li class="link-control-sidebar"> <li class="link-control-sidebar">
<a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li> </li>

</ul> </ul>
</div> </div>
</nav> </nav>

+ 36
- 30
backend/views/layouts/left.php View File

* termes. * termes.
*/ */


use common\helpers\GlobalParam;

$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();

?> ?>


<aside class="main-sidebar"> <aside class="main-sidebar">
<?php <?php
$producer = GlobalParam::getCurrentProducer(); $producer = GlobalParam::getCurrentProducer();
$newVersionOpendistribTemplate = ''; $newVersionOpendistribTemplate = '';
if(!$producer->isUpToDateWithOpendistribVersion()) {
if($producer && !$producerManager->isUpToDateWithOpendistribVersion($producer)) {
$newVersionOpendistribTemplate = '<span class="pull-right-container"><small class="label pull-right bg-orange">&nbsp;</small></span>'; $newVersionOpendistribTemplate = '<span class="pull-right-container"><small class="label pull-right bg-orange">&nbsp;</small></span>';
} }
?> ?>
[ [
'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' => $userManager->isCurrentProducer()],
['label' => 'Distributions', 'icon' => 'calendar', 'url' => ['/distribution/index'], 'visible' => $userManager->isCurrentProducer()],
[ [
'label' => 'Produits', 'label' => 'Produits',
'icon' => 'clone', 'icon' => 'clone',
'url' => ['/product/index'], 'url' => ['/product/index'],
'visible' => User::isCurrentProducer(),
'visible' => $userManager->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' => $userManager->isCurrentProducer()],
['label' => 'Catégories', 'icon' => 'book', 'url' => ['/product-category/index'], 'visible' => $userManager->isCurrentProducer()],
['label' => 'Import prix', 'icon' => 'upload', 'url' => ['/product/price-import'], 'visible' => $userManager->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' => $userManager->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' => $userManager->isCurrentProducer()],
['label' => 'Groupes', 'icon' => 'users', 'url' => ['/user-group/index'], 'visible' => $userManager->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' => $userManager->isCurrentProducer(), 'active' => Yii::$app->controller->id == 'subscription'],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate/index'], 'visible' => $userManager->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' => $userManager->isCurrentProducer()],
['label' => 'Factures', 'icon' => 'sticky-note-o', 'url' => ['/invoice/index'], 'visible' => $userManager->isCurrentProducer()],
['label' => 'Devis', 'icon' => 'sticky-note-o', 'url' => ['/quotation/index'], 'visible' => $userManager->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' => $userManager->isCurrentProducer()],
['label' => 'Rapports', 'icon' => 'pencil-square-o', 'url' => ['/report/index'], 'visible' => $userManager->isCurrentProducer()],
['label' => 'Produits', 'icon' => 'table', 'url' => ['/stats/products'], 'visible' => $userManager->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' => $userManager->isCurrentProducer()],
['label' => 'Accès', 'icon' => 'lock', 'url' => ['/access/index'], 'visible' => $userManager->isCurrentProducer()],
[ [
'label' => 'Développement', 'label' => 'Développement',
'icon' => 'code', 'icon' => 'code',
'url' => ['/development/index'], 'url' => ['/development/index'],
'visible' => User::isCurrentProducer(),
'visible' => $userManager->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' => $userManager->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' => $userManager->isCurrentAdmin()],
['label' => 'Producteurs', 'icon' => 'th-list', 'url' => ['/producer-admin/index'], 'visible' => $userManager->isCurrentAdmin()],
['label' => 'Tranches de prix', 'icon' => 'eur', 'url' => ['/producer-price-range-admin/index'], 'visible' => $userManager->isCurrentAdmin()],
['label' => 'Taxes', 'icon' => 'eur', 'url' => ['/tax-rate-admin/index'], 'visible' => $userManager->isCurrentAdmin()],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate-admin/index'], 'visible' => $userManager->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' => $userManager->isCurrentAdmin()],
//['label' => 'Gii', 'icon' => 'file-code-o', 'url' => ['/gii'], 'visible' => $userManager->isCurrentAdmin()],
//['label' => 'Debug', 'icon' => 'dashboard', 'url' => ['/debug'], 'visible' => $userManager->isCurrentAdmin()],
['label' => 'Login', 'url' => ['site/login'], 'visible' => ! $userManager->isCurrentConnected()],
], ],
] ]
) ?> ) ?>

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

<?php

/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use common\models\Producer;
use common\models\User;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\helpers\Url;
use common\helpers\GlobalParam;

/* @var $this \yii\web\View */
/* @var $content string */

\common\assets\CommonAsset::register($this);
\backend\assets\AppAsset::register($this);

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

?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="baseurl" content="<?= Yii::$app->urlManagerBackend->baseUrl; ?>">
<meta name="baseurl-absolute"
content="<?= Yii::$app->urlManagerBackend->getHostInfo() . Yii::$app->urlManagerBackend->baseUrl; ?>">
<link rel="icon" type="image/png" href="<?php echo Yii::$app->urlManager->getBaseUrl(); ?>/img/favicon3.png"/>
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?> - distrib</title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => '<img class="logo" src="' . Yii::$app->urlManager->getBaseUrl() . '/img/laboulange3.png" />',
'brandUrl' => Yii::$app->homeUrl,
'innerContainerOptions' => ['class' => 'container-fluid'],
'options' => [
'class' => 'navbar-inverse navbar-fixed-top nav-header',
],
]);

$menuItems = [
[
'label' => '<span class="glyphicon glyphicon-home"></span> Tableau de bord',
'url' => ['/site/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-calendar"></span> Commandes',
'url' => ['/order/index'],
'visible' => !Yii::$app->user->isGuest,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-calendar"></span> Toutes les commandes',
'url' => ['/order/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-repeat"></span> Abonnements',
'url' => ['/subscription/index'],
'visible' => !Yii::$app->user->isGuest
],
]
],
[
'label' => '<span class="glyphicon glyphicon-grain"></span> Produits',
'url' => ['/product/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-map-marker"></span> Points de vente',
'url' => ['/point-sale/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-user"></span> Clients',
'url' => ['/user/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-plus"></span>',
'url' => ['/producer/update'],
'visible' => !Yii::$app->user->isGuest,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-cog"></span> Paramètres',
'url' => ['/producer/update'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-bullhorn"></span> Communiquer',
'url' => ['/communicate/index'],
'visible' => !Yii::$app->user->isGuest
],
[
'label' => '<span class="glyphicon glyphicon-euro"></span> Mon abonnement',
'url' => ['/producer/billing'],
'visible' => !Yii::$app->user->isGuest,
],
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Statistiques',
'url' => ['/stats/index'],
'visible' => !Yii::$app->user->isGuest,
],
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Statistiques produits',
'url' => ['/stats/products'],
'visible' => !Yii::$app->user->isGuest,
],
[
'label' => '<span class="glyphicon glyphicon-wrench"></span> Développement',
'url' => ['/development/index'],
'visible' => !Yii::$app->user->isGuest
],
],
]
];

if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Connexion', 'url' => ['/site/login']];
} else {

if (Yii::$app->user->identity->status == USER::STATUS_ADMIN) {
$menuItems[] = [
'label' => '<span class="glyphicon glyphicon-asterisk"></span>',
'url' => '#',
'items' => [
[
'label' => '<span class="glyphicon glyphicon-th-list"></span> Producteurs',
'url' => ['producer-admin/index'],
'visible' => !Yii::$app->user->isGuest,
],
[
'label' => '<span class="glyphicon glyphicon-euro"></span> Facturation',
'url' => ['producer-admin/billing'],
'visible' => false,
],
]
];
}

$menuItems[] = [
'label' => '<span class="glyphicon glyphicon-off"></span>',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post', 'title' => 'Déconnexion']
];

$menuItems[] = [
'label' => '<span class="retour-site">Retour sur le site</span>',
'url' => Yii::$app->urlManagerProducer->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]),
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
'encodeLabels' => false
]);
NavBar::end();
?>

<div class="container-fluid container-body">
<?php if (YII_ENV == 'dev' || YII_ENV == 'demo'): ?>
<div id="env-dev"><?php if (YII_ENV == 'dev'): ?>Dév.<?php elseif (YII_ENV == 'demo'): ?>Démo<?php endif; ?></div>
<?php endif; ?>
<?php if (!Yii::$app->user->isGuest): ?>
<div class="name-producer">
<?php if (User::getCurrentStatus() == User::STATUS_PRODUCER): ?>
<span><?= Html::encode(Yii::$app->user->identity->getNameProducer()); ?></span>
<?php elseif (User::getCurrentStatus() == User::STATUS_ADMIN): ?>
<?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) {
return $model->name;
}));
?>
<?php ActiveForm::end(); ?>
<?php endif; ?>

<?php
$producer = Producer::findOne(GlobalParam::getCurrentProducerId());
if (!$producer->active):
?>
<span class="label label-danger" data-toggle="tooltip" data-placement="bottom"
data-original-title="Activez votre établissement quand vous le souhaitez afin de la rendre visible à vos clients.">
<?= Html::a('Hors-ligne', ['producer/update']); ?>
</span>
<?php endif; ?>

<div class="clr"></div>
</div>
<?php endif; ?>

<?php if (YII_ENV == 'demo'): ?>
<div id="block-demo">
<div class="container-fluid">
<span class="glyphicon glyphicon-eye-open"></span> <strong>Espace de démonstration</strong> :
Testez la plateforme sans avoir à vous inscrire. Les données sont réinitialisées quotidiennement
&bull; <?= Html::a('Retour', Url::env('prod', 'frontend')) ?>
</div>
</div>
<?php endif; ?>

<?=
Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
])
?>
<?= $content ?>
</div>
</div>

<div id="alerts-fixed"></div>

<footer class="footer">
<div class="container-fluid">
<p class="pull-left">
<a href="<?php echo Url::frontend('site/contact'); ?>">Contact</a> &bull;
<a href="<?php echo Url::frontend('site/mentions'); ?>">Mentions légales</a> &bull;
<a href="<?php echo Url::frontend('site/cgv'); ?>">CGS</a>
<a id="code-source" href="https://framagit.org/guillaume-bourgeois/laboiteapain">Code source <img
src="<?php echo Yii::$app->urlManager->getBaseUrl(); ?>/img/logo-framagit.png"
alt="Hébergé par Framasoft"/> <img
src="<?php echo Yii::$app->urlManager->getBaseUrl(); ?>/img/logo-gitlab.png"
alt="Propulsé par Gitlab"/></a>
</p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>

<?php $this->endBody() ?>

<!-- analytics -->
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-86917043-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
<?php $this->endPage() ?>

+ 12
- 9
backend/views/order/report.php View File

termes. termes.
*/ */


use common\models\Order ;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\Order\Wrapper\OrderManager;

$orderManager = OrderManager::getInstance();


$dayWeek = date('w', strtotime($date)); $dayWeek = date('w', strtotime($date));
$dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday']; $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
$html .= '<td><strong>'.number_format($order->amount, 2) . ' € '; $html .= '<td><strong>'.number_format($order->amount, 2) . ' € ';


if($order->getPaymentStatus() == Order::PAYMENT_PAID)
if($orderManager->getPaymentStatus($order) == Order::PAYMENT_PAID)
{ {
$html .= '(payé)' ; $html .= '(payé)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_UNPAID && $order->getAmount(Order::AMOUNT_PAID))
elseif($orderManager->getPaymentStatus($order) == Order::PAYMENT_UNPAID && $orderManager->getOrderAmount($order, Order::AMOUNT_PAID))
{ {
$html .= '(reste '.$order->getAmount(Order::AMOUNT_REMAINING, true).' à payer)' ;
$html .= '(reste '.$orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING, true).' à payer)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_SURPLUS)
elseif($orderManager->getPaymentStatus($order) == Order::PAYMENT_SURPLUS)
{ {
$html .= '(surplus : '.$order->getAmount(Order::PAYMENT_SURPLUS, true).' à rembourser)' ;
$html .= '(surplus : '.$orderManager->getOrderAmount($order, Order::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 = $orderManager->getProductQuantity($product, $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 = $orderManager->getProductQuantity($product, $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 = $orderManager->getProductQuantity($product, $ordersArray);
if($quantity) { if($quantity) {
$html .= $quantity . '&nbsp;'.$product->name.', ' ; $html .= $quantity . '&nbsp;'.$product->name.', ' ;
} }

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

use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use common\models\Producer;
use common\models\ProductPrice ;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\User\Wrapper\UserManager;

$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();


/* @var $this yii\web\View */
/* @var $model backend\models\PointVente */
/* @var $form yii\widgets\ActiveForm */
?> ?>


<div class="point-sale-form"> <div class="point-sale-form">
<?= $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($userManager->populateUserDropdownList(), ['class' => 'select2'])
->hint('Utilisé lors de la facturation'); ?> ->hint('Utilisé lors de la facturation'); ?>


<?php <?php
$addHintCredit = ''; $addHintCredit = '';
if (!Producer::getConfig('credit')):
if (!$producerManager->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')] . ')',
'' => 'Paramètres globaux (' . Producer::$creditFunctioningArray[$producerManager->getConfig('credit_functioning')] . ')',
Producer::CREDIT_FUNCTIONING_OPTIONAL => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_OPTIONAL], Producer::CREDIT_FUNCTIONING_OPTIONAL => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_OPTIONAL],
Producer::CREDIT_FUNCTIONING_MANDATORY => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_MANDATORY], Producer::CREDIT_FUNCTIONING_MANDATORY => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_MANDATORY],
Producer::CREDIT_FUNCTIONING_USER => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_USER], Producer::CREDIT_FUNCTIONING_USER => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_USER],
], [])->hint(Producer::HINT_CREDIT_FUNCTIONING); ?> ], [])->hint(Producer::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( ProductPrice::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() ?>


<div id="users"> <div id="users">


<?= 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 />'
$userManager = UserManager::getInstance();
return Html::encode($userManager->getUsernameFromArray($model_user)) . '<br />'
. Html::activeTextInput( . Html::activeTextInput(
$model, $model,
'users_comment[' . $model_user['user_id'] . ']', 'users_comment[' . $model_user['user_id'] . ']',

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



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\PointVenteUser;
use common\logic\PointSale\UserPointSale\Model\UserPointSale;
use common\logic\Producer\Producer\Model\Producer;

$pointSaleManager = $this->getPointSaleManager();


$this->setTitle('Points de vente'); $this->setTitle('Points de vente');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());
'saterday' => 'Samedi', 'saterday' => 'Samedi',
'sunday' => 'Dimanche', 'sunday' => 'Dimanche',
], ],
'value' => function ($model) {
return $model->getStrDeliveryDays();
'value' => function ($model) use ($pointSaleManager) {
return $pointSaleManager->getStrDeliveryDays($model);
} }
], ],
[ [
'<span class="glyphicon glyphicon-star"></span>', '<span class="glyphicon glyphicon-star"></span>',
['point-sale/default', 'id' => $model->id], ['point-sale/default', 'id' => $model->id],
[ [
'title' => Yii::t(
'app',
'Point de vente par défaut'
),
'title' => 'Point de vente par défaut',
'class' => 'btn btn-default' 'class' => 'btn btn-default'
] ]
); );
'<span class="glyphicon glyphicon-star-empty"></span>', '<span class="glyphicon glyphicon-star-empty"></span>',
['point-sale/default', 'id' => $model->id], ['point-sale/default', 'id' => $model->id],
[ [
'title' => Yii::t(
'app',
'Point de vente par défaut'
),
'title' => 'Point de vente par défaut',
'class' => 'btn btn-default' 'class' => 'btn btn-default'
] ]
); );

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



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\logic\Producer\Producer\Model\Producer;


?> ?>



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



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\User ;
use common\models\ User ;
use common\models\Etablissement ; use common\models\Etablissement ;


$this->title = 'Facturation'; $this->title = 'Facturation';

+ 0
- 5
backend/views/producer-admin/create.php View File

termes. termes.
*/ */


use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;

$this->setTitle('Ajouter producteur') ; $this->setTitle('Ajouter producteur') ;
$this->addBreadcrumb(['label' => 'Producteurs', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'Producteurs', 'url' => ['index']]) ;
$this->addBreadcrumb('Ajouter') ; $this->addBreadcrumb('Ajouter') ;

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



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\User ;
use common\models\Producer ;
use common\models\Distribution ;
use common\logic\User\User\Model\User;
use common\logic\Producer\Producer\Model\Producer;
use common\helpers\Price;

$producerManager = $this->getProducerManager();


$this->setTitle('Producteurs') ; $this->setTitle('Producteurs') ;
$this->addBreadcrumb($this->getTitle()) ; $this->addBreadcrumb($this->getTitle()) ;
else { else {
foreach($model->user as $u) foreach($model->user as $u)
{ {
if($u->status == User::STATUS_PRODUCER)
if($u->status == User::STATUS_PRODUCER)
{ {
return Html::encode($u->lastname.' '.$u->name) return Html::encode($u->lastname.' '.$u->name)
.'<br />'.Html::encode($u->email) .'<br />'.Html::encode($u->email)
'attribute' => 'À facturer / chiffre d\'affaire', 'attribute' => 'À facturer / chiffre d\'affaire',
'label' => 'À facturer / chiffre d\'affaire', 'label' => 'À facturer / chiffre d\'affaire',
'format' => 'raw', 'format' => 'raw',
'value' => function($model) {
'value' => function($producer) use ($producerManager) {


$str = ''; $str = '';

if($model->isBillingFrequencyMonthly()) {
$str .= $model->getSummaryAmountsToBeBilled('Mois dernier', 1);
if($producerManager->isBillingFrequencyMonthly($producer)) {
$str .= $producerManager->getSummaryAmountsToBeBilled($producer, 'Mois dernier', 1);
} }
elseif($model->isBillingFrequencyQuarterly()) {
$str .= $model->getSummaryAmountsToBeBilled('3 derniers mois', 3);
elseif($producerManager->isBillingFrequencyQuarterly($producer)) {
$str .= $producerManager->getSummaryAmountsToBeBilled($producer, '3 derniers mois', 3);
} }
elseif($model->isBillingFrequencyBiannual()) {
$str .= $model->getSummaryAmountsToBeBilled('6 derniers mois', 6);
elseif($producerManager->isBillingFrequencyBiannual($producer)) {
$str .= $producerManager->getSummaryAmountsToBeBilled($producer, '6 derniers mois', 6);
} }


if($model->option_billing_reduction && strlen($str)) {
if($producer->option_billing_reduction && strlen($str)) {
$str .= '<br /><u>Avec réduction</u> : '; $str .= '<br /><u>Avec réduction</u> : ';
if($model->option_billing_reduction_percentage) {
$str .= ' '.$model->option_billing_reduction_percentage.'&nbsp;%';
if($producer->option_billing_reduction_percentage) {
$str .= ' '.$producer->option_billing_reduction_percentage.'&nbsp;%';
} }
} }



+ 0
- 5
backend/views/producer-admin/update.php View File

termes. termes.
*/ */


use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;

$this->setTitle('Modifier producteur') ; $this->setTitle('Modifier producteur') ;
$this->addBreadcrumb(['label' => 'Producteurs', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'Producteurs', 'url' => ['index']]) ;
$this->addBreadcrumb('Modifier') ; $this->addBreadcrumb('Modifier') ;

+ 0
- 2
backend/views/producer-price-range-admin/create.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;


$this->setTitle('Ajouter une tranche de prix') ; $this->setTitle('Ajouter une tranche de prix') ;
$this->addBreadcrumb(['label' => 'tranche de prix', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'tranche de prix', 'url' => ['index']]) ;

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

* termes. * termes.
*/ */


use common\helpers\Price;
use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\User;
use common\models\Producer;
use common\models\Distribution;


$this->setTitle('Tranches de prix'); $this->setTitle('Tranches de prix');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());

+ 0
- 2
backend/views/producer-price-range-admin/update.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;


$this->setTitle('Éditer une taxe') ; $this->setTitle('Éditer une taxe') ;
$this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ;

+ 7
- 10
backend/views/producer/billing.php View File

termes. termes.
*/ */


use yii\helpers\Html;
use yii\grid\GridView;
use common\models\User ;
use common\models\Producer ;
use yii\bootstrap\ActiveForm;
$producerManager = $this->getProducerManager();
$producerPriceRangeManager = $this->getProducerPriceRangeManager();


$this->setTitle('Tarifs') ; $this->setTitle('Tarifs') ;
$this->addBreadcrumb($this->getTitle()) ; $this->addBreadcrumb($this->getTitle()) ;


<?php <?php


if($producer->isBillingTypeFreePrice()) {
if($producerManager->isBillingTypeFreePrice($producer)) {
echo '<div class="alert alert-info">'; echo '<div class="alert alert-info">';
echo "Vous bénéficiez actuellement d'un abonnement à prix libre dont voici le montant : <strong>".$producer->getFreePrice()."</strong>"; echo "Vous bénéficiez actuellement d'un abonnement à prix libre dont voici le montant : <strong>".$producer->getFreePrice()."</strong>";
echo '</div>'; echo '</div>';
} }
elseif($producer->isBillingTypeClassic()) {
elseif($producerManager->isBillingTypeClassic($producer)) {
$month = date('Y-m', strtotime('-1 month')); $month = date('Y-m', strtotime('-1 month'));
$turnover = $producer->getTurnover($month);
$amountBilledLastMonth = $producer->getAmountToBeBilledByTurnover($turnover);
$turnover = $producerManager->getTurnover($producer, $month);
$amountBilledLastMonth = $producerPriceRangeManager->getAmountToBeBilledByTurnover($turnover);


if($amountBilledLastMonth) { if($amountBilledLastMonth) {
echo '<div class="alert alert-info">'; echo '<div class="alert alert-info">';
echo "À titre d'information, voici le tarif retenu pour le mois dernier (".strftime('%B', strtotime('-1 month')).") : <strong>".$producer->getAmountToBeBilledByMonth($month, true)."</strong>";
echo "À titre d'information, voici le tarif retenu pour le mois dernier (".strftime('%B', strtotime('-1 month')).") : <strong>".$producerManager->getAmountToBeBilledByMonth($producer, $month, true)."</strong>";
echo "<br />Le chiffre d'affaire pris en compte pour ce calcul est : <strong>".Price::format($turnover)." HT</strong>"; echo "<br />Le chiffre d'affaire pris en compte pour ce calcul est : <strong>".Price::format($turnover)." HT</strong>";
echo '<br /><a href="'.Yii::$app->urlManager->createUrl(['stats/index']).'">Voir l\'évolution de mon chiffre d\'affaire</a>'; echo '<br /><a href="'.Yii::$app->urlManager->createUrl(['stats/index']).'">Voir l\'évolution de mon chiffre d\'affaire</a>';
echo '</div>'; echo '</div>';

+ 7
- 4
backend/views/producer/update.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\helpers\Url;
use common\models\Producer;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Config\TaxRate\Model\TaxRate;
use common\logic\Document\Document\Model\Document;
use yii\helpers\ArrayHelper;


\backend\assets\VuejsProducerUpdateAsset::register($this);
$userManager = $this->getUserManager();


\backend\assets\VuejsProducerUpdateAsset::register($this);
$this->setTitle('Paramètres'); $this->setTitle('Paramètres');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());




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



+ 0
- 7
backend/views/product-category/_form.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\models\Producer;
use common\models\ProductPrice ;

/* @var $this yii\web\View */
/* @var $model backend\models\PointVente */
/* @var $form yii\widgets\ActiveForm */


?> ?>



+ 2
- 2
backend/views/product-category/update.php View File



use yii\helpers\Html; use yii\helpers\Html;


$this->setTitle("Modifier un groupe d'utilisateur") ;
$this->addBreadcrumb(['label' => "Groupes d'utilisateurs", 'url' => ['index']]) ;
$this->setTitle("Modifier une catégorie") ;
$this->addBreadcrumb(['label' => "Catégories", 'url' => ['index']]) ;
$this->addBreadcrumb(['label' => Html::encode($model->name), 'url' => ['update', 'id' => $model->id]]) ; $this->addBreadcrumb(['label' => Html::encode($model->name), 'url' => ['update', 'id' => $model->id]]) ;
$this->addBreadcrumb('Modifier') ; $this->addBreadcrumb('Modifier') ;



+ 8
- 6
backend/views/product/_form.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\bootstrap\ActiveForm; use yii\bootstrap\ActiveForm;
use common\models\Product;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use common\models\TaxRate;
use common\models\Producer;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\Product\Product\Model\Product;
use common\logic\PointSale\PointSale\Model\PointSale;

$productCategoryManager = $this->getProductCategoryManager();
$taxRateManager = $this->getTaxRateManager();


?> ?>


<?= $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($productCategoryManager->populateProductCategoriesDropdownList()); ?>
<?= $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') ?>


$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($taxRateManager->findTaxRates(), '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($taxRateManager->findTaxRates(), 'id', function ($model) {
return $model->value; return $model->value;
})); }));
foreach ($taxRateValuesArray as $key => $taxRateValue) { foreach ($taxRateValuesArray as $key => $taxRateValue) {

+ 6
- 7
backend/views/product/index.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\helpers\Url;
use common\models\Product;
use common\models\TaxRate;
use common\models\Producer;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use \lo\widgets\Toggle; use \lo\widgets\Toggle;
use common\helpers\Price;
use common\logic\Product\Product\Model\Product;

$productManager = $this->getProductManager();


$this->setTitle('Produits'); $this->setTitle('Produits');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());
$this->addButton(['label' => 'Nouveau produit <span class="glyphicon glyphicon-plus"></span>', 'url' => 'product/create', 'class' => 'btn btn-primary']); $this->addButton(['label' => 'Nouveau produit <span class="glyphicon glyphicon-plus"></span>', 'url' => 'product/create', 'class' => 'btn btn-primary']);



?> ?>


<span style="display: none;" id="page-size"><?= $dataProvider->pagination->pageSize; ?></span> <span style="display: none;" id="page-size"><?= $dataProvider->pagination->pageSize; ?></span>
], ],
[ [
'attribute' => 'price', 'attribute' => 'price',
'value' => function ($model) {
'value' => function ($model) use ($productManager) {
$return = ''; $return = '';
if ($model->price) { if ($model->price) {
$return = Price::format($model->getPriceWithTax()) . ' (' . Product::strUnit($model->unit, 'wording_unit', true) . ')';
$return = Price::format($productManager->getPriceWithTax($model)) . ' (' . $productManager->strUnit($model->unit, 'wording_unit', true) . ')';
} }


return $return; return $return;

+ 68
- 0
backend/views/product/price_import.php View File

<?php

/**
* Copyright distrib (2018)
*
* contact@opendistrib.net
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/

use yii\bootstrap\ActiveForm;
use yii\helpers\Html;

$productManager = $this->getProductManager();

$this->setTitle('Import prix produits');
$this->addBreadcrumb($this->getTitle());
$this->addButton(['label' => 'Exporter les prix <span class="glyphicon glyphicon-export"></span>', 'url' => 'product/price-export', 'class' => 'btn btn-primary']);

?>

<div class="product-price-import">
<div class="alert alert-info">
<i class="icon fa fa-info"></i>
Télécharger le fichier CSV via <strong>Exporter les prix</strong> comme base pour éditer vos prix puis envoyez-le via le formulaire.
</div>

<?php $form = ActiveForm::begin([
'enableClientValidation' => false,
'options' => ['enctype' => 'multipart/form-data']
]); ?>

<?= $form->field($model, 'file')->fileInput() ?>

<div class="form-group">
<?= Html::submitButton('Envoyer', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>
</div>

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


<?php

use common\helpers\Price;

$productManager = $this->getProductManager();

?>

<div class="alert alert-warning"> <div class="alert alert-warning">
Prix de base : <strong><?= Price::format($model->getPrice()); ?> HT</strong> / <strong><?= Price::format($model->getPriceWithTax()); ?> TTC</strong><br />
Prix de base : <strong><?= Price::format($productManager->getPrice($model)); ?> HT</strong> / <strong><?= Price::format($productManager->getPriceWithTax($model)); ?> TTC</strong><br />
</div> </div>

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



use yii\helpers\Html; use yii\helpers\Html;
use yii\bootstrap\ActiveForm; use yii\bootstrap\ActiveForm;
use common\models\Product;
use yii\helpers\ArrayHelper;
use common\models\TaxRate;
use common\models\Producer;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\User ;


$userManager = $this->getUserManager();
$userGroupManager = $this->getUserGroupManager();
$pointSaleManager = $this->getPointSaleManager();
$productManager = $this->getProductManager();


?> ?>


<div class="product-form"> <div class="product-form">


<?= <?=

$this->render('_base_price', [ $this->render('_base_price', [
'model' => $modelProduct, 'model' => $modelProduct,
]) ; ]) ;

?> ?>


<?php $form = ActiveForm::begin([ <?php $form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'] 'options' => ['enctype' => 'multipart/form-data']
]); ?> ]); ?>


<?= $form->field($model, 'id_user')->dropDownList(User::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')->dropDownList($userManager->populateUserDropdownList()); ?>
<?= $form->field($model, 'id_user_group')->dropDownList($userGroupManager->populateUserGroupDropdownList()); ?>
<?= $form->field($model, 'id_point_sale')->dropDownList($pointSaleManager->populatePointSaleDropdownList()); ?>
<?= $form->field($model, 'from_quantity')->label('À partir de la quantité ('. $productManager->strUnit($productManager->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 ('. $productManager->strUnit($productManager->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 ('. $productManager->strUnit($productManager->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>
</div> </div>


<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>

</div> </div>

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

<?php <?php


use common\helpers\Price ;

/** /**
* Copyright distrib (2018) * Copyright distrib (2018)
* *
* termes. * termes.
*/ */


$this->setTitle('Liste des prix ('.Html::encode($model->name).')');
use common\logic\User\User\Wrapper\UserManager;
use yii\helpers\Html;
use common\helpers\Price;
use yii\grid\GridView;
use common\logic\Product\Product\Wrapper\ProductManager;

$productManager = ProductManager::getInstance();
$userManager = UserManager::getInstance();

$this->setTitle('Liste des prix (' . Html::encode($model->name) . ')');
$this->addBreadcrumb(['label' => 'Produits', 'url' => ['index']]); $this->addBreadcrumb(['label' => 'Produits', 'url' => ['index']]);
$this->addBreadcrumb(['label' => $model->name, 'url' => ['update', 'id' => $model->id]]); $this->addBreadcrumb(['label' => $model->name, 'url' => ['update', 'id' => $model->id]]);
$this->addBreadcrumb('Modifier'); $this->addBreadcrumb('Modifier');
//$this->addButton(['label' => 'Nouveau prix <span class="glyphicon glyphicon-plus"></span>', 'url' => ['product/prices-create', 'idProduct' => $model->id ], 'class' => 'btn btn-primary']);


?> ?>


<?= <?=
$this->render('../_nav', [
'model' => $model,
'action' => $action,
]) ;
$this->render('../_nav', [
'model' => $model,
'action' => $action,
]);
?> ?>


<div class="col-md-12"> <div class="col-md-12">


<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Prix spécifiques à ce produit
<a href="<?= Yii::$app->urlManager->createUrl(['product/prices-create', 'idProduct' => $model->id ]) ?>" class="btn btn-default btn-xs">
Nouveau prix
<span class="glyphicon glyphicon-plus"></span>
</a>
</h3>
</div>
<div class="panel-body">
<?php

echo GridView::widget([
//'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'id_user',
'format' => 'raw',
'value' => function ($model) {
if($model->user) {
return $model->user->getUsername() ;
}
return '<span class="label label-success">Tous</span>' ;
}
],
[
'attribute' => 'id_user_group',
'format' => 'raw',
'value' => function ($model) {
if($model->userGroup) {
return $model->userGroup->name ;
}
return '<span class="label label-success">Tous</span>' ;
}
],
[
'attribute' => 'id_point_sale',
'format' => 'raw',
'value' => function ($model) {
if($model->pointSale) {
return $model->pointSale->name ;
}
return '<span class="label label-success">Tous</span>' ;
}
],
[
'attribute' => 'from_quantity',
'value' => function ($productPrice) {
if($productPrice->from_quantity) {
return $productPrice->from_quantity.' '.Product::strUnit(Product::getRefUnit($productPrice->product->unit), 'wording');
}

return '' ;
}
],
[
'attribute' => 'price',
'value' => function ($productPrice) {
return Price::numberTwoDecimals($productPrice->price).' €' ;
}
],
[
'attribute' => 'price',
'header' => 'Prix (TTC)',
'value' => function ($productPrice) use ($model) {
return Price::numberTwoDecimals(Price::getPriceWithTax($productPrice->price, $model->taxRate->value)).' €' ;
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'update' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['product/prices-update', 'id' => $model->id], [
'title' => Yii::t('app', 'Modifier'), 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', ['product/prices-delete', 'id' => $model->id], [
'title' => Yii::t('app', 'Supprimer'), 'class' => 'btn btn-default'
]);
}
],
],
],
]);

?>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Prix spécifiques à ce produit
<a href="<?= Yii::$app->urlManager->createUrl(['product/prices-create', 'idProduct' => $model->id]) ?>"
class="btn btn-default btn-xs">
Nouveau prix
<span class="glyphicon glyphicon-plus"></span>
</a>
</h3>
</div> </div>
<div class="panel-body">
<?php


<!--
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Pourcentage global / Utilisateurs</h3>
</div>
<div class="panel-body">
<table class="table table-bordered">
<thead>
<tr>
<th>Utilisateur</th>
<th>Pourcentage</th>
<th>Prix (HT)</th>
<th>Prix (TTC)</th>
</tr>
</thead>
<tbody>
<?php if($userProducerWithProductPercent && count($userProducerWithProductPercent) > 0): ?>
<?php foreach($userProducerWithProductPercent as $userProducer): ?>
<?php if($userProducer->user): ?>
<tr>
<td><?= $userProducer->user->getUsername() ?></td>
<td><?= $userProducer->product_price_percent ?> %</td>
<td><?= Price::format($model->getPrice(['user_producer' => $userProducer])) ?></td>
<td><?= Price::format($model->getPriceWithTax(['user_producer' => $userProducer])) ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<tr><td colspan="4">Aucun résultat</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'id_user',
'format' => 'raw',
'value' => function ($model) use ($userManager) {
if ($model->user) {
return $userManager->getUsername($model->user);
}
return '<span class="label label-success">Tous</span>';
}
],
[
'attribute' => 'id_user_group',
'format' => 'raw',
'value' => function ($model) {
if ($model->userGroup) {
return $model->userGroup->name;
}
return '<span class="label label-success">Tous</span>';
}
],
[
'attribute' => 'id_point_sale',
'format' => 'raw',
'value' => function ($model) {
if ($model->pointSale) {
return $model->pointSale->name;
}
return '<span class="label label-success">Tous</span>';
}
],
[
'attribute' => 'from_quantity',
'value' => function ($productPrice) use ($productManager) {
if ($productPrice->from_quantity) {
return $productPrice->from_quantity . ' ' . $productManager->strUnit($productManager->getRefUnit($productPrice->product->unit), 'wording');
}

return '';
}
],
[
'attribute' => 'price',
'value' => function ($productPrice) {
return Price::numberTwoDecimals($productPrice->price) . ' €';
}
],
[
'attribute' => 'price',
'header' => 'Prix (TTC)',
'value' => function ($productPrice) use ($model) {
return Price::numberTwoDecimals(Price::getPriceWithTax($productPrice->price, $model->taxRate->value)) . ' €';
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'update' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['product/prices-update', 'id' => $model->id], [
'title' => 'Modifier', 'class' => 'btn btn-default'
]);
},
'delete' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', ['product/prices-delete', 'id' => $model->id], [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]);
}
],
],
],
]);


<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Pourcentage global / Points de vente</h3>
</div>
<div class="panel-body">
<table class="table table-bordered">
<thead>
<tr>
<th>Point de vente</th>
<th>Pourcentage</th>
<th>Prix (HT)</th>
<th>Prix (TTC)</th>
</tr>
</thead>
<tbody>
<?php if($pointSaleWithProductPercent && count($pointSaleWithProductPercent) > 0): ?>
<?php foreach($pointSaleWithProductPercent as $pointSale): ?>
<tr>
<td><?= Html::encode($pointSale->name) ?></td>
<td><?= $pointSale->product_price_percent ?> %</td>
<td><?= Price::format($model->getPrice(['point_sale' => $pointSale])) ?></td>
<td><?= Price::format($model->getPriceWithTax(['point_sale' => $pointSale])) ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr><td colspan="4">Aucun résultat</td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
?>
</div> </div>
-->
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Rappel du prix de base</h3>
</div>
<div class="panel-body">
<p>Prix de base : <strong><?= Price::format($model->getPrice()); ?> HT</strong> / <strong><?= Price::format($model->getPriceWithTax()); ?> TTC</strong><br /></p>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Rappel du prix de base</h3>
</div> </div>
</div>

<!--
<div class="col-md-4">

<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Priorités de résolution</h3>
</div>
<div class="panel-body">
<p>Le prix d'un produit se déduit dans un ordre précis de résolution, le voici : </p>
<ul>
<li>Les prix spécifiques définis au niveau du produit</li>
<li>Les pourcentages globaux définis au niveau des utilisateurs et points de vente</li>
<li>Le prix de base défini au niveau du produit</li>
</ul>
<p>À chaque étape de résolution, on vérifie si le contexte courant (utilisateur / point de vente) correspond à un prix.
Si c'est le cas, on l'utilise, sinon on passe à l'étape suivante jusqu'à arriver au prix de base
défini dans "Général".
</p>
</div>
<div class="panel-body">
<p>Prix de base : <strong><?= Price::format($productManager->getPrice($model)); ?> HT</strong> /
<strong><?= Price::format($productManager->getPriceWithTax($model)); ?> TTC</strong><br/></p>
</div> </div>
</div>
-->
</div>
</div>

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

* termes. * termes.
*/ */




/* @var $this yii\web\View */
/* @var $model app\models\Produit */
/* @var $form yii\widgets\ActiveForm */
use yii\helpers\Html;


$this->setTitle('Modifier un produit ('.Html::encode($model->name).')'); $this->setTitle('Modifier un produit ('.Html::encode($model->name).')');
$this->addBreadcrumb(['label' => 'Produits', 'url' => ['index']]); $this->addBreadcrumb(['label' => 'Produits', 'url' => ['index']]);

+ 96
- 91
backend/views/quotation/index.php View File

* termes. * termes.
*/ */


use common\logic\Document\Quotation\Model\Quotation;
use yii\grid\GridView;
use common\logic\Order\Order\Model\Order;
use yii\helpers\Html;

$quotationManager = $this->getQuotationManager();
$userManager = $this->getUserManager();

$this->setTitle('Devis'); $this->setTitle('Devis');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());
$this->addButton(['label' => 'Nouveau devis <span class="glyphicon glyphicon-plus"></span>', 'url' => 'quotation/create', 'class' => 'btn btn-primary']); $this->addButton(['label' => 'Nouveau devis <span class="glyphicon glyphicon-plus"></span>', 'url' => 'quotation/create', 'class' => 'btn btn-primary']);
?> ?>


<div class="quotation-index"> <div class="quotation-index">
<?php if(Quotation::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function($model) {
return $model->getHtmlLabel() ;
}
],
[
'attribute' => 'reference',
'value' => function($model) {
if(strlen($model->reference) > 0) {
return $model->reference ;
}
return '' ;
}
],
'name',
[
'attribute' => 'id_user',
'header' => 'Utilisateur',
'value' => function($model) {
return $model->user->getUsername() ;
}
],
[
'attribute' => 'date',
'header' => 'Date',
'value' => function($model) {
return date('d/m/Y',strtotime($model->date)) ;
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function($invoice) {
return $invoice->getAmountWithTax(Order::AMOUNT_TOTAL, true) ;
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{transform} {validate} {update} {delete} {send} {download}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'transform' => function ($url, $model) {
return ($model->isStatusValid() ? Html::a('<span class="glyphicon glyphicon-check"></span>', $url, [
'title' => 'Transformer en facture', 'class' => 'btn btn-default'
]) : '');
},
'validate' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'send' => function($url, $model) {
return ((isset($model->user) && strlen($model->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function($url, $model) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'update' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]) : '');
},
'delete' => function ($url, $model) {
return ($model->isStatusDraft() ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucun devis enregistré</div>
<?php endif; ?>
<?php if (Quotation::searchCount()): ?>
<?= GridView::widget([
'filterModel' => $searchModel,
'dataProvider' => $dataProvider,
'columns' => [
[
'attribute' => 'status',
'label' => 'Statut',
'filter' => [
'draft' => 'Brouillon',
'valid' => 'Valide',
],
'format' => 'raw',
'value' => function ($quotation) use ($quotationManager) {
return $quotationManager->getHtmlLabel($quotation);
}
],
[
'attribute' => 'reference',
'value' => function ($model) {
return (strlen($model->reference) > 0) ? $model->reference : '';
}
],
'name',
[
'attribute' => 'id_user',
'header' => 'Utilisateur',
'value' => function ($quotation) use ($userManager) {
return $userManager->getUsername($quotation->user);
}
],
[
'attribute' => 'date',
'header' => 'Date',
'value' => function ($quotation) {
return date('d/m/Y', strtotime($quotation->date));
}
],
[
'attribute' => 'amount',
'header' => 'Montant',
'value' => function ($quotation) use ($quotationManager) {
return $quotationManager->getAmountWithTax($quotation, Order::AMOUNT_TOTAL, true);
}
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{transform} {validate} {update} {delete} {send} {download}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
'transform' => function ($url, $quotation) use ($quotationManager) {
return ($quotationManager->isStatusValid($quotation) ? Html::a('<span class="glyphicon glyphicon-check"></span>', $url, [
'title' => 'Transformer en facture', 'class' => 'btn btn-default'
]) : '');
},
'validate' => function ($url, $quotation) use ($quotationManager) {
return ($quotationManager->isStatusValid($quotation) ? Html::a('<span class="glyphicon glyphicon-ok"></span>', $url, [
'title' => 'Valider', 'class' => 'btn btn-default'
]) : '');
},
'send' => function ($url, $quotation) {
return ((isset($quotation->user) && strlen($quotation->user->email) > 0) ? Html::a('<span class="glyphicon glyphicon-send"></span>', $url, [
'title' => 'Envoyer', 'class' => 'btn btn-default'
]) : '');
},
'download' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
'title' => 'Télécharger', 'class' => 'btn btn-default'
]);
},
'update' => function ($url, $quotation) use ($quotationManager) {
return ($quotationManager->isStatusDraft($quotation) ? Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default'
]) : '');
},
'delete' => function ($url, $quotation) use ($quotationManager) {
return ($quotationManager->isStatusDraft($quotation) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Supprimer', 'class' => 'btn btn-default'
]) : '');
}
],
],
],
]); ?>
<?php else: ?>
<div class="alert alert-info">Aucun devis enregistré</div>
<?php endif; ?>
</div> </div>

+ 13
- 7
backend/views/site/index.php View File

termes. termes.
*/ */


use common\logic\Order\Order\Model\Order;
use common\logic\Order\Order\Wrapper\OrderManager;
use yii\helpers\Html ; use yii\helpers\Html ;


$orderManager = OrderManager::getInstance();

$this->setTitle('Tableau de bord'); $this->setTitle('Tableau de bord');


?> ?>
</thead> </thead>
<tbody> <tbody>
<?php foreach($ordersArray as $order): ?> <?php foreach($ordersArray as $order): ?>
<tr class="<?= $order->getClassHistory() ; ?>">
<td class="infos"><?= $order->getStrOrigin(true); ?></td>
<?php $orderManager->initOrder($order); ?>

<tr class="<?= $orderManager->getHistoryClass($order) ; ?>">
<td class="infos"><?= $orderManager->getLabelOrigin($order, true); ?></td>
<td class="date"> <td class="date">
<div class="block-date"> <div class="block-date">
<div class="day"><?= strftime('%A', strtotime($order->distribution->date)) ?></div> <div class="day"><?= strftime('%A', strtotime($order->distribution->date)) ?></div>
</div> </div>
</td> </td>
<td> <td>
<?= $order->getStrUser(); ?><br />
<?= $orderManager->getOrderUsername($order); ?><br />
<?php if(strlen($order->comment)): ?> <?php if(strlen($order->comment)): ?>
<div class="comment"><span class="glyphicon glyphicon-comment"></span> <?= nl2br(Html::encode($order->comment)) ; ?></div> <div class="comment"><span class="glyphicon glyphicon-comment"></span> <?= nl2br(Html::encode($order->comment)) ; ?></div>
<?php endif; ?> <?php endif; ?>
</td> </td>
<td><?= $order->getCartSummary() ; ?></td>
<td><?= $order->getPointSaleSummary() ; ?></td>
<td><?= $order->getAmountWithTax(Order::AMOUNT_TOTAL, true) ; ?></td>
<td class="history"><?= $order->getStrHistory() ; ?></td>
<td><?= $orderManager->getCartSummary($order) ; ?></td>
<td><?= $orderManager->getPointSaleSummary($order) ; ?></td>
<td><?= $orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL, true) ; ?></td>
<td class="history"><?= $orderManager->getHistorySummary($order) ; ?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>

+ 9
- 8
backend/views/subscription/_form.php View File

use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ; use yii\helpers\ArrayHelper ;
use common\models\User ;
use common\models\PointSale ;
use common\helpers\GlobalParam ;
use common\logic\Subscription\Subscription\Model\Subscription;


\backend\assets\VuejsSubscriptionFormAsset::register($this); \backend\assets\VuejsSubscriptionFormAsset::register($this);


$userManager = $this->getUserManager();
$pointSaleManager = $this->getPointSaleManager();

?> ?>


<div class="subscription-form" id="app-subscription-form"> <div class="subscription-form" id="app-subscription-form">
<?= $form->field($model, 'id')->hiddenInput() ?> <?= $form->field($model, 'id')->hiddenInput() ?>
<?php endif; ?> <?php endif; ?>
<div class="col-md-5" id="bloc-select-user"> <div class="col-md-5" id="bloc-select-user">
<?= $form->field($model, 'id_user')->dropDownList(User::populateDropdownList(), ['class' => 'select2']); ?>
<?= $form->field($model, 'id_user')->dropDownList($userManager->populateUserDropdownList(), ['class' => 'select2']); ?>
</div> </div>
<div class="col-md-1" id="or-user"> <div class="col-md-1" id="or-user">
<span>OU</span> <span>OU</span>
<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($pointSaleManager->findPointSales(), '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'
Subscription::AUTO_PAYMENT_DEDUCTED => 'Déduit',
Subscription::AUTO_PAYMENT_YES => 'Oui',
Subscription::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.') ?>

+ 12
- 7
backend/views/subscription/index.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\Product ;
use common\helpers\GlobalParam ; use common\helpers\GlobalParam ;

use common\logic\Subscription\Subscription\Model\Subscription;
use common\logic\PointSale\PointSale\Model\PointSale;
use common\logic\Product\Product\Wrapper\ProductManager;
use yii\helpers\ArrayHelper;
use common\logic\Product\Product\Model\Product;


$this->setTitle('Abonnements') ; $this->setTitle('Abonnements') ;
$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 = Subscription::searchAll() ;


?> ?>
<div class="subscription-index"> <div class="subscription-index">
'label' => 'Produits', 'label' => 'Produits',
'format' => 'raw', 'format' => 'raw',
'value' => function($model) { 'value' => function($model) {
$productManager = ProductManager::getInstance();
$html = '' ; $html = '' ;
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 * Product::$unitsArray[$productSubscription->product->unit]['coefficient']).'&nbsp;'. $productManager->strUnit($productSubscription->product->unit, 'wording_short').')<br />' ;
} }
else { else {
$html .= 'Produit non défini<br />' ; $html .= 'Produit non défini<br />' ;
'format' => 'raw', 'format' => 'raw',
'filter' => ArrayHelper::map(PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->asArray()->all(), 'id', 'name'), 'filter' => ArrayHelper::map(PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->asArray()->all(), 'id', 'name'),
'value' => function($model) { 'value' => function($model) {
return Html::encode($model->pointSale->name) ;
if($model->pointSale) {
return Html::encode($model->pointSale->name) ;
}
return '';
} }
], ],
[ [

+ 0
- 2
backend/views/tax-rate-admin/create.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;


$this->setTitle('Ajouter une taxe') ; $this->setTitle('Ajouter une taxe') ;
$this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ;

+ 0
- 3
backend/views/tax-rate-admin/index.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\User;
use common\models\Producer;
use common\models\Distribution;


$this->setTitle('Taxes'); $this->setTitle('Taxes');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());

+ 0
- 2
backend/views/tax-rate-admin/update.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper ;
use common\models\Producer ;


$this->setTitle('Éditer une taxe') ; $this->setTitle('Éditer une taxe') ;
$this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'taxe', 'url' => ['index']]) ;

+ 0
- 5
backend/views/user-group/_form.php View File

use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use common\models\Producer;
use common\models\ProductPrice ;


/* @var $this yii\web\View */
/* @var $model backend\models\PointVente */
/* @var $form yii\widgets\ActiveForm */
?> ?>


<div class="user-group-form"> <div class="user-group-form">

+ 7
- 4
backend/views/user/_form.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\models\ProductPrice ;
use yii\helpers\ArrayHelper;


\backend\assets\VuejsUserFormAsset::register($this); \backend\assets\VuejsUserFormAsset::register($this);


$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();

?> ?>


<div class="user-form" id="app-user-form"> <div class="user-form" id="app-user-form">
]); ?> ]); ?>


<?= $form->field($model, 'type') <?= $form->field($model, 'type')
->dropDownList(User::getTypeChoicesArray(), [
->dropDownList( $userManager->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($producerManager->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( ProductPrice::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']) ?>

+ 2
- 0
backend/views/user/_menu.php View File

termes. termes.
*/ */


use yii\helpers\Html;

?> ?>


<div id="menu-users"> <div id="menu-users">

+ 21
- 18
backend/views/user/credit.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use common\models\CreditHistory;
use common\models\Producer;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\User\CreditHistory\Model\CreditHistory;
use common\helpers\MeanPayment;

$creditHistoryManager = $this->getCreditHistoryManager();
$producerManager = $this->getProducerManager();
$userManager = $this->getUserManager();


$this->setTitle('Créditer <small>'.Html::encode($user->lastname.' '.$user->name).'</small>', 'Créditer '.Html::encode($user->lastname.' '.$user->name)) ; $this->setTitle('Créditer <small>'.Html::encode($user->lastname.' '.$user->name).'</small>', 'Créditer '.Html::encode($user->lastname.' '.$user->name)) ;
$this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]) ; $this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]) ;
<div class="user-credit"> <div class="user-credit">
<?php <?php
$producer = Producer::searchOne([
'id' => GlobalParam::getCurrentProducerId()
]);
$producer = $producerManager->findOneProducerById(GlobalParam::getCurrentProducerId());
if(!$producer->credit) if(!$producer->credit)
{ {
<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',
CreditHistory::TYPE_CREDIT => 'Crédit',
CreditHistory::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([
</div> </div>
<div class="col-md-8"> <div class="col-md-8">
<h2>Historique <span class="the-credit"><?= number_format($user->getCredit($producer->id), 2); ?> €</span></h2>
<h2>Historique <span class="the-credit"><?= number_format($userManager->getCredit($user, $producer), 2); ?> €</span></h2>
<table class="table table-bordered"> <table class="table table-bordered">
<thead> <thead>
<tr> <tr>
<tbody> <tbody>
<?php if(count($history)): ?> <?php if(count($history)): ?>
<?php foreach($history as $creditHistory): ?> <?php foreach($history as $creditHistory): ?>

<tr> <tr>
<td><?= $creditHistory->getDate(true) ; ?></td>
<td><?= Html::encode($creditHistory->strUserAction()); ?></td>
<td><?= $creditHistory->getStrWording(); ?></td>
<td><?= $creditHistoryManager->getDate($creditHistory, true) ; ?></td>
<td><?= Html::encode($creditHistoryManager->getStrUserAction($creditHistory)); ?></td>
<td><?= $creditHistoryManager->getStrWording($creditHistory); ?></td>
<td> <td>
<?php if($creditHistory->isTypeDebit()): ?>
- <?= $creditHistory->getAmount(true); ?>
<?php if($creditHistoryManager->isTypeDebit($creditHistory)): ?>
- <?= $creditHistoryManager->getAmount($creditHistory, true); ?>
<?php endif; ?> <?php endif; ?>
</td> </td>
<td> <td>
<?php if($creditHistory->isTypeCredit()): ?>
+ <?= $creditHistory->getAmount(true); ?>
<?php if($creditHistoryManager->isTypeCredit($creditHistory)): ?>
+ <?= $creditHistoryManager->getAmount($creditHistory, true); ?>
<?php endif; ?> <?php endif; ?>
</td> </td>
<td> <td>
<?= $creditHistory->getStrMeanPayment() ?>
<?= $creditHistoryManager->getStrMeanPayment($creditHistory) ?>
</td> </td>
<td> <td>
<?php if(strlen($creditHistory->comment)): ?>
<?= nl2br($creditHistory->comment) ; ?>
<?php if(strlen($creditHistory->getComment())): ?>
<?= nl2br($creditHistory->getComment()); ?>
<?php endif; ?> <?php endif; ?>
</td> </td>
</tr> </tr>

+ 10
- 7
backend/views/user/index.php View File



use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\models\User;
use common\models\Order;
use common\logic\User\User\Wrapper\UserManager;
use common\logic\Order\Order\Model\Order;
use common\logic\User\UserProducer\Model\UserProducer;
use common\logic\User\User\Model\User;


$this->setTitle('Utilisateurs'); $this->setTitle('Utilisateurs');
$this->addBreadcrumb($this->getTitle()); $this->addBreadcrumb($this->getTitle());
'attribute' => 'username', 'attribute' => 'username',
'label' => 'Nom', 'label' => 'Nom',
'value' => function ($model) { 'value' => function ($model) {
return User::getUsernameFromArray($model);
$userManager = UserManager::getInstance();
return $userManager->getUsername($model);
} }
], ],
[ [
'attribute' => 'type', 'attribute' => 'type',
'label' => 'Type', 'label' => 'Type',
'value' => function ($model) { 'value' => function ($model) {
$typeArray = User::getTypeChoicesArray();
$userManager = UserManager::getInstance();
$typeArray = $userManager->getTypeChoicesArray();
if(isset($typeArray[$model['type']])) { if(isset($typeArray[$model['type']])) {
return $typeArray[$model['type']]; return $typeArray[$model['type']];
} }
'attribute' => 'credit', 'attribute' => 'credit',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) use ($producer) { 'value' => function ($model) use ($producer) {

$userProducer = UserProducer::searchOne([
$userProducer = UserProducer::searchOne([
'id_user' => $model->id 'id_user' => $model->id
]); ]);
$credit = $userProducer ? $userProducer->credit : 0; $credit = $userProducer ? $userProducer->credit : 0;
'buttons' => [ 'buttons' => [
'update' => function ($url, $model) { 'update' => function ($url, $model) {
$url = Yii::$app->urlManager->createUrl(['user/update', 'id' => $model->id]); $url = Yii::$app->urlManager->createUrl(['user/update', 'id' => $model->id]);
$user = User::find()->with('userProducer')->where(['id' => $model->id])->one();
$user = User::find()->with('userProducer')->where(['id' => $model->id])->one();
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [ return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'title' => 'Modifier', 'class' => 'btn btn-default' 'title' => 'Modifier', 'class' => 'btn btn-default'
]); ]);

+ 16
- 12
backend/views/user/orders.php View File

*/ */


use yii\grid\GridView; use yii\grid\GridView;
use yii\helpers\Html;


$this->setTitle('Commandes <small>' . Html::encode($user->getUsername()) . '</small>', 'Commandes de ' . Html::encode($user->getUsername()));
$userManager = $this->getUserManager();
$orderManager = $this->getOrderManager();

$this->setTitle('Commandes <small>' . Html::encode($userManager->getUsername($user)) . '</small>', 'Commandes de ' . Html::encode($userManager->getUsername($user)));
$this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]); $this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]);
$this->addBreadcrumb(['label' => Html::encode($user->lastname . ' ' . $user->name)]); $this->addBreadcrumb(['label' => Html::encode($user->lastname . ' ' . $user->name)]);
$this->addBreadcrumb('Commandes'); $this->addBreadcrumb('Commandes');
[ [
'attribute' => 'distribution.date', 'attribute' => 'distribution.date',
'label' => 'Date de livraison', 'label' => 'Date de livraison',
'value' => function ($model) {
return date('d/m/Y',strtotime($model->distribution->date));
'value' => function ($user) {
return date('d/m/Y',strtotime($user->distribution->date));
} }
], ],
[ [
'label' => 'Historique', 'label' => 'Historique',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) {
return $model->getStrHistory();
'value' => function ($order) use ($orderManager) {
return $orderManager->getHistorySummary($order);
} }
], ],
[ [
'label' => 'Résumé', 'label' => 'Résumé',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) {
return $model->getCartSummary();
'value' => function ($order) use ($orderManager) {
return $orderManager->getCartSummary($order);
} }
], ],
[ [
'label' => 'Point de vente', 'label' => 'Point de vente',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) {
return $model->getPointSaleSummary();
'value' => function ($order) use ($orderManager) {
return $orderManager->getPointSaleSummary($order);
} }
], ],
[ [
'label' => 'Montant', 'label' => 'Montant',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) {
$model->init();
return $model->getAmountSummary();
'value' => function ($order) use ($orderManager) {
$orderManager->initOrder($order);
return $orderManager->getAmountSummary($order);
} }
], ],
[ [

+ 22
- 12
backend/web/css/screen.css View File

.distribution-index .modal-form-order table.table-products td.price .input-group-addon { .distribution-index .modal-form-order table.table-products td.price .input-group-addon {
background-color: #eee; background-color: #eee;
} }
/* line 396, ../sass/distribution/_index.scss */
/* line 395, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.price .invoice-price {
margin-top: 8px;
}
/* line 397, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.price .invoice-price .label-invoice-price {
font-size: 11px;
font-weight: bold;
color: gray;
}
/* line 405, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity { .distribution-index .modal-form-order table.table-products td.quantity {
width: 165px; width: 165px;
} }
/* line 399, ../sass/distribution/_index.scss */
/* line 408, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity input { .distribution-index .modal-form-order table.table-products td.quantity input {
text-align: center; text-align: center;
color: black; color: black;
} }
/* line 404, ../sass/distribution/_index.scss */
/* line 413, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity .form-control { .distribution-index .modal-form-order table.table-products td.quantity .form-control {
border-right: 0px none; border-right: 0px none;
padding-right: 4px; padding-right: 4px;
} }
/* line 409, ../sass/distribution/_index.scss */
/* line 418, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity .input-group-addon { .distribution-index .modal-form-order table.table-products td.quantity .input-group-addon {
padding: 5px; padding: 5px;
padding-left: 0px; padding-left: 0px;
border-left: 0px none; border-left: 0px none;
border-right: 0px none; border-right: 0px none;
} }
/* line 418, ../sass/distribution/_index.scss */
/* line 427, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity-remaining { .distribution-index .modal-form-order table.table-products td.quantity-remaining {
text-align: right; text-align: right;
} }
/* line 421, ../sass/distribution/_index.scss */
/* line 430, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity-remaining.quantity-remaining, .distribution-index .modal-form-order table.table-products td.quantity-remaining.infinite { .distribution-index .modal-form-order table.table-products td.quantity-remaining.quantity-remaining, .distribution-index .modal-form-order table.table-products td.quantity-remaining.infinite {
color: #00A65A; color: #00A65A;
} }
/* line 425, ../sass/distribution/_index.scss */
/* line 434, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity-remaining.negative { .distribution-index .modal-form-order table.table-products td.quantity-remaining.negative {
color: #DD4B39; color: #DD4B39;
} }
/* line 429, ../sass/distribution/_index.scss */
/* line 438, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order table.table-products td.quantity-remaining.infinite, .distribution-index .modal-form-order table.table-products td.quantity-remaining.empty { .distribution-index .modal-form-order table.table-products td.quantity-remaining.infinite, .distribution-index .modal-form-order table.table-products td.quantity-remaining.empty {
font-size: 18px; font-size: 18px;
} }
/* line 436, ../sass/distribution/_index.scss */
/* line 445, ../sass/distribution/_index.scss */
.distribution-index .modal-form-order .actions-form button { .distribution-index .modal-form-order .actions-form button {
margin-left: 15px; margin-left: 15px;
} }
/* line 444, ../sass/distribution/_index.scss */
/* line 453, ../sass/distribution/_index.scss */
.distribution-index .modal-payment .info-box .info-box-icon { .distribution-index .modal-payment .info-box .info-box-icon {
width: 50px; width: 50px;
} }
/* line 447, ../sass/distribution/_index.scss */
/* line 456, ../sass/distribution/_index.scss */
.distribution-index .modal-payment .info-box .info-box-icon i { .distribution-index .modal-payment .info-box .info-box-icon i {
font-size: 30px; font-size: 30px;
} }
/* line 452, ../sass/distribution/_index.scss */
/* line 461, ../sass/distribution/_index.scss */
.distribution-index .modal-payment .info-box .info-box-content { .distribution-index .modal-payment .info-box .info-box-content {
margin-left: 50px; margin-left: 50px;
} }

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

} }
}, },
initPointsSale: function(idActivePointSale) { initPointsSale: function(idActivePointSale) {
this.countOrdersByPointSale = [] ;
for(var i = 0; i < this.pointsSale.length ; i++) {
this.countOrdersByPointSale[this.pointsSale[i].id] = 0 ;
}
for(var i = 0; i < this.orders.length ; i++) {
this.countOrdersByPointSale[this.orders[i].id_point_sale] ++ ;
}

this.countActivePointsSale = 0 ; this.countActivePointsSale = 0 ;
this.setIdActivePointSale(0) ; this.setIdActivePointSale(0) ;
for(var i= 0; i < this.pointsSale.length; i++) { for(var i= 0; i < this.pointsSale.length; i++) {
if(this.pointsSale[i].pointSaleDistribution[0].delivery == 1 && (this.pointsSale[i].status == 1 || this.countOrdersByPointSale[this.pointsSale[i].id] > 0)) {
this.countActivePointsSale ++ ;
this.setIdActivePointSale(this.pointsSale[i].id) ;
}
if(this.pointsSale[i].pointSaleDistribution[0].delivery == 1) {
this.countActivePointsSale ++ ;
this.setIdActivePointSale(this.pointsSale[i].id) ;
}
} }
if(this.countActivePointsSale > 1) { if(this.countActivePointsSale > 1) {
this.setIdActivePointSale(0) ; this.setIdActivePointSale(0) ;
if(idActivePointSale) { if(idActivePointSale) {
this.setIdActivePointSale(idActivePointSale) ; this.setIdActivePointSale(idActivePointSale) ;
} }
this.countOrdersByPointSale = [] ;
for(var i = 0; i < this.pointsSale.length ; i++) {
this.countOrdersByPointSale[this.pointsSale[i].id] = 0 ;
}
for(var i = 0; i < this.orders.length ; i++) {
this.countOrdersByPointSale[this.orders[i].id_point_sale] ++ ;
}
}, },
dayClicked: function(day) { dayClicked: function(day) {
this.date = day.date ; this.date = day.date ;


Vue.component('order-state-payment', { Vue.component('order-state-payment', {
props: ['order', 'producer'], props: ['order', 'producer'],
template: '#order-state-payment',
template: '#order-state-payment'
}); });


Vue.component('modal', { Vue.component('modal', {
productOrderArrayRequest[key] = { productOrderArrayRequest[key] = {
quantity: this.order.productOrder[key].quantity, quantity: this.order.productOrder[key].quantity,
unit: this.order.productOrder[key].unit, unit: this.order.productOrder[key].unit,
price: this.order.productOrder[key].price
price: this.order.productOrder[key].price,
invoice_price: this.order.productOrder[key].invoice_price
}; };
} }
return JSON.stringify(productOrderArrayRequest); return JSON.stringify(productOrderArrayRequest);

+ 9
- 0
backend/web/sass/distribution/_index.scss View File

.input-group-addon { .input-group-addon {
background-color: #eee; background-color: #eee;
} }

.invoice-price {
margin-top: 8px;
.label-invoice-price {
font-size: 11px;
font-weight: bold;
color: gray;
}
}
} }


td.quantity { td.quantity {

+ 15
- 6
common/components/ActiveRecordCommon.php View File

const SEARCH_ONE = 'one'; const SEARCH_ONE = 'one';
const SEARCH_COUNT = 'count'; const SEARCH_COUNT = 'count';


public function populateFieldObject($fieldIdentifier, $fieldObject, $object)
{
$this->{$fieldIdentifier} = $object->id;
$this->populateRelation($fieldObject, $object);
}

/** /**
* Méthode générique de recherche utilisée pour tous les modèles. Elle a * Méthode générique de recherche utilisée pour tous les modèles. Elle a
* pour but de construire la requête et de retourner le résultat. * pour but de construire la requête et de retourner le résultat.
public static function searchBy($params = [], $options = []) public static function searchBy($params = [], $options = [])
{ {
$class = get_called_class(); $class = get_called_class();
$repositoryClass = str_replace('\\Model\\', '\\Repository\\', $class).'Repository';
$repository = $repositoryClass::getInstance();


if (is_callable([$class, 'defaultOptionsSearch'])) {
$default_options = $class::defaultOptionsSearch();
if(method_exists($repository , 'getDefaultOptionsSearch')) {
$default_options = $repository->getDefaultOptionsSearch();
} else { } else {
throw new \ErrorException('La méthode "defaultOptionsSearch" n\'est '
. 'pas définie dans la classe "' . $class . '"');
throw new \ErrorException('La méthode "getDefaultOptionsSearch" n\'est '
. 'pas définie dans la classe "' . $repositoryClass . '"');
} }


$options = array_merge($default_options, $options); $options = array_merge($default_options, $options);
$pk = $class::tableName() . '.' . $pk[0]; $pk = $class::tableName() . '.' . $pk[0];


if (isset($options['attribute_id_producer']) && strlen($options['attribute_id_producer']) if (isset($options['attribute_id_producer']) && strlen($options['attribute_id_producer'])
&& !isset($params[$options['attribute_id_producer']]) && !Yii::$app->user->isGuest) {
&& !isset($params[$options['attribute_id_producer']]) && !\Yii::$app->user->isGuest
) {
$params[$options['attribute_id_producer']] = GlobalParam::getCurrentProducerId(); $params[$options['attribute_id_producer']] = GlobalParam::getCurrentProducerId();
} }


return $records->count(); return $records->count();
} }


return false;
return null;
} }


public static function groupByPrimaryKey($class, $records) public static function groupByPrimaryKey($class, $records)

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

<?php

namespace common\components;

use common\logic\Producer\Producer\Model\Producer;
use yii\base\ErrorException;

class BusinessLogic
{
use BusinessLogicTrait;

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

public function setProducerContext(Producer $producer)
{
foreach($this->getContainers() as $container) {
foreach($container->getServices() as $serviceClass) {
$instanceService = $serviceClass::getInstance();
$instanceService->setProducerContext($producer);
}
}
}

/*
* Hiérarchie des apps
*/

public function getContainerLevelHierarchyByService($serviceClass): int
{
$containersArray = $this->getContainers();
$entityFqcnService = $this->getEntityFqcnByService($serviceClass);

foreach($containersArray as $key => $container) {
if($container->getEntityFqcn() == $entityFqcnService) {
return $key;
}
}
}

public function getEntityFqcnByService(string $serviceClass): string
{
$containersArray = $this->getContainers();

foreach($containersArray as $container) {
if(in_array($serviceClass, $container->getServices())) {
return $container->getEntityFqcn();
}
}

throw new ErrorException('Service '.$serviceClass.' introuvable dans les containers.');
}
}

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

<?php

namespace common\components;

use common\logic\Config\TaxRate\Wrapper\TaxRateContainer;
use common\logic\Config\TaxRate\Wrapper\TaxRateManager;
use common\logic\Distribution\Distribution\Wrapper\DistributionManager;
use common\logic\Distribution\Distribution\Wrapper\DistributionContainer;
use common\logic\Distribution\PointSaleDistribution\Wrapper\PointSaleDistributionContainer;
use common\logic\Distribution\PointSaleDistribution\Wrapper\PointSaleDistributionManager;
use common\logic\Distribution\ProductDistribution\Wrapper\ProductDistributionContainer;
use common\logic\Distribution\ProductDistribution\Wrapper\ProductDistributionManager;
use common\logic\Document\DeliveryNote\Wrapper\DeliveryNoteContainer;
use common\logic\Document\DeliveryNote\Wrapper\DeliveryNoteManager;
use common\logic\Document\Document\Wrapper\DocumentContainer;
use common\logic\Document\Document\Wrapper\DocumentManager;
use common\logic\Document\Invoice\Wrapper\InvoiceContainer;
use common\logic\Document\Invoice\Wrapper\InvoiceManager;
use common\logic\Document\Quotation\Wrapper\QuotationContainer;
use common\logic\Document\Quotation\Wrapper\QuotationManager;
use common\logic\Order\Order\Wrapper\OrderContainer;
use common\logic\Order\Order\Wrapper\OrderManager;
use common\logic\Order\OrderStatusHistory\Wrapper\OrderStatusHistoryContainer;
use common\logic\Order\OrderStatusHistory\Wrapper\OrderStatusHistoryManager;
use common\logic\Order\ProductOrder\Wrapper\ProductOrderContainer;
use common\logic\Order\ProductOrder\Wrapper\ProductOrderManager;
use common\logic\PointSale\PointSale\Wrapper\PointSaleContainer;
use common\logic\PointSale\PointSale\Wrapper\PointSaleManager;
use common\logic\PointSale\UserPointSale\Wrapper\UserPointSaleContainer;
use common\logic\PointSale\UserPointSale\Wrapper\UserPointSaleManager;
use common\logic\Producer\Producer\Wrapper\ProducerContainer;
use common\logic\Producer\Producer\Wrapper\ProducerManager;
use common\logic\Producer\ProducerPriceRange\Wrapper\ProducerPriceRangeContainer;
use common\logic\Producer\ProducerPriceRange\Wrapper\ProducerPriceRangeManager;
use common\logic\Product\Product\Wrapper\ProductContainer;
use common\logic\Product\Product\Wrapper\ProductManager;
use common\logic\Product\ProductCategory\Wrapper\ProductCategoryContainer;
use common\logic\Product\ProductCategory\Wrapper\ProductCategoryManager;
use common\logic\Product\ProductPointSale\Wrapper\ProductPointSaleContainer;
use common\logic\Product\ProductPointSale\Wrapper\ProductPointSaleManager;
use common\logic\Product\ProductPrice\Wrapper\ProductPriceContainer;
use common\logic\Product\ProductPrice\Wrapper\ProductPriceManager;
use common\logic\Subscription\ProductSubscription\Wrapper\ProductSubscriptionContainer;
use common\logic\Subscription\ProductSubscription\Wrapper\ProductSubscriptionManager;
use common\logic\Subscription\Subscription\Wrapper\SubscriptionContainer;
use common\logic\Subscription\Subscription\Wrapper\SubscriptionManager;
use common\logic\User\CreditHistory\Wrapper\CreditHistoryContainer;
use common\logic\User\CreditHistory\Wrapper\CreditHistoryManager;
use common\logic\User\User\Wrapper\UserContainer;
use common\logic\User\User\Wrapper\UserManager;
use common\logic\User\UserGroup\Wrapper\UserGroupContainer;
use common\logic\User\UserGroup\Wrapper\UserGroupManager;
use common\logic\User\UserProducer\Wrapper\UserProducerContainer;
use common\logic\User\UserProducer\Wrapper\UserProducerManager;
use common\logic\User\UserUserGroup\Wrapper\UserUserGroupContainer;
use common\logic\User\UserUserGroup\Wrapper\UserUserGroupManager;

trait BusinessLogicTrait
{
public function getUserProducerManager(): UserProducerManager
{
return UserProducerManager::getInstance();
}

public function getOrderManager(): OrderManager
{
return OrderManager::getInstance();
}

public function getTaxRateManager(): TaxRateManager
{
return TaxRateManager::getInstance();
}

public function getDistributionManager(): DistributionManager
{
return DistributionManager::getInstance();
}

public function getPointSaleDistributionManager(): PointSaleDistributionManager
{
return PointSaleDistributionManager::getInstance();
}

public function getProductDistributionManager(): ProductDistributionManager
{
return ProductDistributionManager::getInstance();
}

public function getDeliveryNoteManager(): DeliveryNoteManager
{
return DeliveryNoteManager::getInstance();
}

public function getDocumentManager(): DocumentManager
{
return DocumentManager::getInstance();
}

public function getInvoiceManager(): InvoiceManager
{
return InvoiceManager::getInstance();
}

public function getQuotationManager(): QuotationManager
{
return QuotationManager::getInstance();
}

public function getOrderStatusHistoryManager(): OrderStatusHistoryManager
{
return OrderStatusHistoryManager::getInstance();
}

public function getProductOrderManager(): ProductOrderManager
{
return ProductOrderManager::getInstance();
}

public function getPointSaleManager(): PointSaleManager
{
return PointSaleManager::getInstance();
}

public function getUserPointSaleManager(): UserPointSaleManager
{
return UserPointSaleManager::getInstance();
}

public function getProducerManager(): ProducerManager
{
return ProducerManager::getInstance();
}

public function getProducerPriceRangeManager(): ProducerPriceRangeManager
{
return ProducerPriceRangeManager::getInstance();
}

public function getProductManager(): ProductManager
{
return ProductManager::getInstance();
}

public function getProductCategoryManager(): ProductCategoryManager
{
return ProductCategoryManager::getInstance();
}

public function getProductPointSaleManager(): ProductPointSaleManager
{
return ProductPointSaleManager::getInstance();
}

public function getProductPriceManager(): ProductPriceManager
{
return ProductPriceManager::getInstance();
}

public function getProductSubscriptionManager(): ProductSubscriptionManager
{
return ProductSubscriptionManager::getInstance();
}

public function getSubscriptionManager(): SubscriptionManager
{
return SubscriptionManager::getInstance();
}

public function getCreditHistoryManager(): CreditHistoryManager
{
return CreditHistoryManager::getInstance();
}

public function getUserManager(): UserManager
{
return UserManager::getInstance();
}

public function getUserGroupManager(): UserGroupManager
{
return UserGroupManager::getInstance();
}

public function getUserUserGroupManager(): UserUserGroupManager
{
return UserUserGroupManager::getInstance();
}

public function getUserContainer(): UserContainer
{
return UserContainer::getInstance();
}

public function getProducerContainer(): ProducerContainer
{
return ProducerContainer::getInstance();
}

public function getProducerPriceRangeContainer(): ProducerPriceRangeContainer
{
return ProducerPriceRangeContainer::getInstance();
}

public function getUserProducerContainer(): UserProducerContainer
{
return UserProducerContainer::getInstance();
}

public function getCreditHistoryContainer(): CreditHistoryContainer
{
return CreditHistoryContainer::getInstance();
}

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

public function getDeliveryNoteContainer(): DeliveryNoteContainer
{
return DeliveryNoteContainer::getInstance();
}

public function getInvoiceContainer(): InvoiceContainer
{
return InvoiceContainer::getInstance();
}

public function getQuotationContainer(): QuotationContainer
{
return QuotationContainer::getInstance();
}

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

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

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

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

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

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

public function getUserPointSaleContainer(): UserPointSaleContainer
{
return UserPointSaleContainer::getInstance();
}

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

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

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

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

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

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

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

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

public function getPointSaleDistributionContainer(): PointSaleDistributionContainer
{
return PointSaleDistributionContainer::getInstance();
}

public function getProductDistributionContainer(): ProductDistributionContainer
{
return ProductDistributionContainer::getInstance();
}
}

common/components/MyView.php → common/components/View.php View File



namespace common\components ; namespace common\components ;


class MyView extends \yii\web\View
class View extends \yii\web\View
{ {
use BusinessLogicTrait;

var $title ; var $title ;
var $page_title ; var $page_title ;
var $buttons ; var $buttons ;

public function getLogic()
{
return \Yii::$app->logic;
}

public function setTitle($title, $page_title = '') public function setTitle($title, $page_title = '')
{ {
$this->title = $title ; $this->title = $title ;
public function getControllerAction() public function getControllerAction()
{ {
return Yii::$app->controller->id.'/'.Yii::$app->controller->action->id ;
return \Yii::$app->controller->id.'/'.\Yii::$app->controller->action->id ;
} }
public function addBreadcrumb($breadcrumb) public function addBreadcrumb($breadcrumb)
public function setMeta($name, $content) public function setMeta($name, $content)
{ {
Yii::$app->view->registerMetaTag([
\Yii::$app->view->registerMetaTag([
'name' => $name, 'name' => $name,
'content' => $content 'content' => $content
]); ]);
} }

public function getUrlManagerFrontend()
{
return \Yii::$app->urlManagerFrontend;
}

public function getUrlManagerProducer()
{
return \Yii::$app->urlManagerProducer;
}

public function getUrlManagerBackend()
{
return \Yii::$app->urlManagerBackend;
}
} }

+ 11
- 0
common/components/ViewBackend.php View File

<?php

namespace common\components;

class ViewBackend extends View
{
public function getUrlManager()
{
return $this->getUrlManagerBackend();
}
}

+ 11
- 0
common/components/ViewFrontend.php View File

<?php

namespace common\components;

class ViewFrontend extends View
{
public function getUrlManager()
{
return $this->getUrlManagerFrontend();
}
}

+ 84
- 79
common/config/main.php View File

* termes. * termes.
*/ */


$serverName = $_SERVER['SERVER_NAME'];
use common\components\BusinessLogic;

$serverName = isset($_SERVER['SERVER_NAME']) ?? '';


return [ return [
'aliases' => [
'@bower' => '@vendor/bower-asset',
'aliases' => [
'@bower' => '@vendor/bower-asset',
],
'vendorPath' => dirname(__DIR__, 2) . '/vendor',
'on beforeRequest' => function () {
if (method_exists(Yii::$app->request, 'getAbsoluteUrl')) {
$url = Yii::$app->request->getAbsoluteUrl();
if ($_SERVER['SERVER_NAME'] != 'localhost' && !empty($url) && substr($url, -1) == '/' && substr($url, -5) != '.net/') {
$url = substr($url, 0, strlen($url) - 1);
Yii::$app->getResponse()->redirect($url, 301);
Yii::$app->end();
}
}
},
'components' => [
'assetManager' => [
'linkAssets' => YII_ENV == "dev" ? 'true' : false,
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'common\logic\User\User\Model\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => 'distrib',
'domain' => (($serverName != 'localhost') ? '.' : '') . Yii::getAlias('@domainName'),
'path' => '/',
]
],
'session' => [
'class' => 'yii\web\Session',
'name' => 'PHPDISTRIBSESSID',
'cookieParams' => [
'domain' => (($serverName != 'localhost') ? '.' : '') . Yii::getAlias('@domainName'),
'httpOnly' => true,
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'image' => [
'class' => 'yii\image\ImageDriver',
'driver' => 'GD', //GD or Imagick
],
'urlManagerProducer' => [
'class' => 'producer\components\UrlManagerProducer',
'subDomain' => Yii::getAlias('@producerSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlProducer'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'<slug_producer:\w+>' => 'site/index',
'<slug_producer:\w+>/<controller>/<action>' => '<controller>/<action>',
],
],
'urlManagerFrontend' => [
'class' => 'common\components\UrlManagerCommon',
'subDomain' => Yii::getAlias('@frontendSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlFrontend'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
],
], ],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'on beforeRequest' => function () {
if (method_exists(Yii::$app->request, 'getAbsoluteUrl')) {
$url = Yii::$app->request->getAbsoluteUrl();
if ($_SERVER['SERVER_NAME'] != 'localhost' && !empty($url) && substr($url, -1) == '/' && substr($url, -5) != '.net/') {
$url = substr($url, 0, strlen($url) - 1);
Yii::$app->getResponse()->redirect($url, 301);
Yii::$app->end();
}
}
},
'components' => [
'assetManager' => [
'linkAssets' => YII_ENV == "dev" ? 'true' : false,
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => 'distrib',
'domain' => (($serverName != 'localhost') ? '.' : '') . Yii::getAlias('@domainName'),
'path' => '/',
]
],
'session' => [
'class' => 'yii\web\Session',
'name' => 'PHPDISTRIBSESSID',
'cookieParams' => [
'domain' => (($serverName != 'localhost') ? '.' : '') . Yii::getAlias('@domainName'),
'httpOnly' => true,
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'image' => [
'class' => 'yii\image\ImageDriver',
'driver' => 'GD', //GD or Imagick
],
'urlManagerProducer' => [
'class' => 'producer\components\UrlManagerProducer',
'subDomain' => Yii::getAlias('@producerSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlProducer'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'<slug_producer:\w+>' => 'site/index',
'<slug_producer:\w+>/<controller>/<action>' => '<controller>/<action>',
],
],
'urlManagerFrontend' => [
'class' => 'common\components\UrlManagerCommon',
'subDomain' => Yii::getAlias('@frontendSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlFrontend'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
],
],
'urlManagerBackend' => [
'class' => 'common\components\UrlManagerCommon',
'subDomain' => Yii::getAlias('@backendSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlBackend'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
],
]
'urlManagerBackend' => [
'class' => 'common\components\UrlManagerCommon',
'subDomain' => Yii::getAlias('@backendSubdomain'),
'domainName' => Yii::getAlias('@domainName'),
'baseUrl' => Yii::getAlias('@baseUrl') . Yii::getAlias('@baseUrlBackend'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
],
], ],
'language' => 'fr-FR',
'logic' => function () {
return new BusinessLogic();
}
],
'language' => 'fr-FR',
]; ];

+ 50
- 2
common/controllers/CommonController.php View File



namespace common\controllers; namespace common\controllers;


use common\components\BusinessLogic;
use common\components\BusinessLogicTrait;
use common\logic\User\User\Model\User;
use yii; use yii;


class CommonController extends \yii\web\Controller class CommonController extends \yii\web\Controller
{ {
use BusinessLogicTrait;


public function beforeAction($event) public function beforeAction($event)
{ {
if (!Yii::$app->user->isGuest) { if (!Yii::$app->user->isGuest) {
Yii::$app->user->identity->updateLastConnection();
$this->getUserManager()->updateUserLastConnection(Yii::$app->user->identity);
} }


return parent::beforeAction($event); return parent::beforeAction($event);
} }

public function getLogic(): BusinessLogic
{
return Yii::$app->logic;
}

public function getUrlManagerProducer()
{
return Yii::$app->urlManagerProducer;
}

public function getUrlManagerFrontend()
{
return Yii::$app->urlManagerFrontend;
}

public function getUrlManagerBackend()
{
return Yii::$app->urlManagerBackend;
}

public function getUserCurrent(): ?User
{
return Yii::$app->user->identity;
}

public function isUserCurrentAdmin()
{
return $this->getUserManager()->isAdmin($this->getUserCurrent());
}

public function getRequest()
{
return Yii::$app->request;
}

public function setFlash($key, $value = true, $removeAfterAccess = true): void
{
Yii::$app->session->setFlash($key, $value, $removeAfterAccess);
}

public function addFlash($key, $value = true, $removeAfterAccess = true): void
{
Yii::$app->session->addFlash($key, $value, $removeAfterAccess);
}
} }


?> ?>

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

termes. termes.
*/ */


namespace common\models;
namespace common\forms;


use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
public $subject; public $subject;
public $body; public $body;
public $verifyCode; public $verifyCode;
public $isTest;


/** /**
* @inheritdoc * @inheritdoc
public function rules() public function rules()
{ {
return [ return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required', 'message' => 'Champs obligatoire'], [['name', 'email', 'subject', 'body'], 'required', 'message' => 'Champs obligatoire'],
// email has to be a valid email address
['email', 'email', 'message' => 'Email incorrect'], ['email', 'email', 'message' => 'Email incorrect'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha', 'message' => 'Veuillez recopier le code de vérification'],
['isTest', 'string'],
['verifyCode', 'captcha', 'message' => 'Veuillez recopier le code de vérification', 'when' => function($model) {
return $model->isTest != 'isTest';
}],
]; ];
} }


*/ */
public function sendEmail($email) public function sendEmail($email)
{ {

return Yii::$app->mailer->compose([ return Yii::$app->mailer->compose([
'html' => 'contact-html', 'html' => 'contact-html',
'text' => 'contact-text'], [ 'content' => $this->body, 'text' => 'contact-text'], [ 'content' => $this->body,
]) ])
->setTo($email) ->setTo($email)
->setFrom([$this->email => $this->name]) ->setFrom([$this->email => $this->name])
->setSubject('[distrib] Contact : ' . $this->subject)
->setSubject('[Opendistrib] Contact : ' . $this->subject)
->send(); ->send();
} }



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

termes. termes.
*/ */


namespace common\models;
namespace common\forms;


use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\User\Model\User;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;


/** /**
* Finds user by [[username]] * Finds user by [[username]]
* *
* @return User|null
*/ */
public function getUser()
public function getUser(): ?User
{ {
if ($this->_user === false) { if ($this->_user === false) {
$this->_user = User::searchOne( $this->_user = User::searchOne(

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

termes. termes.
*/ */


namespace common\models;
namespace common\forms;


use common\logic\Product\Product\Model\Product;
use common\logic\Subscription\ProductSubscription\Model\ProductSubscription;
use common\logic\Subscription\Subscription\Model\Subscription;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\Subscription;
use common\models\SubscriptionProduct;


/** /**
* Login form * Login form
public function save() public function save()
{ {
if ($this->id) { if ($this->id) {
$subscription = Subscription::searchOne(['id' => $this->id]) ;
$subscription = Subscription::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 = ProductSubscription::findAll(['id_subscription' => $this->id]) ;
ProductSubscription::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 = Product::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 / Product::$unitsArray[$product->unit]['coefficient'];


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

+ 4
- 3
common/helpers/CSV.php View File

* termes. * termes.
*/ */



namespace common\helpers; namespace common\helpers;


use common\logic\Producer\Producer\Wrapper\ProducerManager;

class CSV class CSV
{ {

public static function array2csv(array &$array) public static function array2csv(array &$array)
{ {
$separator = Producer::getConfig('option_csv_separator') ?: ';';
$producerManager = ProducerManager::getInstance();
$separator = $producerManager->getConfig('option_csv_separator') ?: ';';


if (count($array) == 0) { if (count($array) == 0) {
return null; return null;

+ 17
- 4
common/helpers/GlobalParam.php View File



namespace common\helpers; namespace common\helpers;


use common\models\Producer;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\User\Service\UserSolver;


class GlobalParam class GlobalParam
{ {
public static function get($key) public static function get($key)
{ {
if ($key == 'producer') { if ($key == 'producer') {
return $this->getCurrentProducer();
return self::getCurrentProducer();
} else { } else {


return \Yii::$app->params[$key]; return \Yii::$app->params[$key];
{ {
if (\Yii::$app->controller->module->id == 'app-backend') { if (\Yii::$app->controller->module->id == 'app-backend') {
if (!\Yii::$app->user->isGuest) { if (!\Yii::$app->user->isGuest) {
return Yii::$app->user->identity->id_producer;
return \Yii::$app->user->identity->id_producer;
} }
} else { } else {
return \Yii::$app->controller->getProducer()->id;
return \Yii::$app->controller->getProducerCurrent()->id;
} }


return false; return false;
} }

public static function getCurrentUser()
{
$userSolver = UserSolver::getInstance();
return $userSolver->getCurrent();
}

public static function getCurrentUserId()
{
$userSolver = UserSolver::getInstance();
return $userSolver->getCurrentId();
}
} }

+ 1
- 1
common/helpers/Mail.php View File

$data) $data)
->setTo($email) ->setTo($email)
->setFrom(['contact@opendistrib.net' => 'distrib']) ->setFrom(['contact@opendistrib.net' => 'distrib'])
->setSubject('[distrib] '.$subject)
->setSubject('[Opendistrib] '.$subject)
->send(); ->send();
} }
} }

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

] ]
], ],
'Subject' => $params['subject'], 'Subject' => $params['subject'],
'TextPart' => Yii::$app->view->renderFile($params['content_view_text'], $params['content_params']),
'HTMLPart' => Yii::$app->view->renderFile($params['content_view_html'], $params['content_params'])
'TextPart' => \Yii::$app->view->renderFile($params['content_view_text'], $params['content_params']),
'HTMLPart' => \Yii::$app->view->renderFile($params['content_view_html'], $params['content_params'])
] ; ] ;


$response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]); $response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]);
$success = $response->success() ; $success = $response->success() ;


if(!$success) { if(!$success) {
Yii::error($response->getBody(), 'Mailjet');
\Yii::error($response->getBody(), 'Mailjet');
} }


return $success ; return $success ;

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

Loading…
Cancel
Save