Browse Source

Merge branch 'refactoring/models' into dev

refactoring
Guillaume Bourgeois 6 years ago
parent
commit
ec5a31a8a6
31 changed files with 1132 additions and 502 deletions
  1. +1
    -1
      backend/controllers/CommandeController.php
  2. +11
    -5
      backend/models/CreditForm.php
  3. +8
    -4
      backend/models/MailForm.php
  4. +0
    -15
      backend/views/layouts/main.php
  5. +0
    -39
      backend/views/paiement/index.php
  6. +1
    -1
      backend/views/site/index.php
  7. +253
    -114
      common/models/Commande.php
  8. +51
    -17
      common/models/CommandeAuto.php
  9. +23
    -8
      common/models/CommandeAutoForm.php
  10. +14
    -5
      common/models/CommandeAutoProduit.php
  11. +11
    -6
      common/models/CommandeProduit.php
  12. +8
    -4
      common/models/ContactForm.php
  13. +94
    -18
      common/models/CreditHistorique.php
  14. +22
    -7
      common/models/Developpement.php
  15. +28
    -7
      common/models/DeveloppementPriorite.php
  16. +113
    -51
      common/models/Etablissement.php
  17. +21
    -6
      common/models/Facture.php
  18. +17
    -7
      common/models/LoginForm.php
  19. +88
    -35
      common/models/PointVente.php
  20. +8
    -4
      common/models/PointVenteUser.php
  21. +44
    -16
      common/models/Production.php
  22. +25
    -7
      common/models/ProductionPointVente.php
  23. +20
    -5
      common/models/ProductionProduit.php
  24. +52
    -10
      common/models/Produit.php
  25. +154
    -68
      common/models/User.php
  26. +8
    -4
      common/models/UserEtablissement.php
  27. +8
    -4
      frontend/models/AddEtablissementForm.php
  28. +6
    -3
      frontend/models/PasswordResetRequestForm.php
  29. +6
    -3
      frontend/models/ProducerCodeForm.php
  30. +10
    -5
      frontend/models/ResetPasswordForm.php
  31. +27
    -23
      frontend/models/SignupForm.php

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



if (abs($commande->montant - $montant_paye) < 0.0001) { if (abs($commande->montant - $montant_paye) < 0.0001) {
$html .= '<span class="label label-success">Payé</span>'; $html .= '<span class="label label-success">Payé</span>';
$buttons_credit = Html::a('Rembourser ' . $commande->getMontantFormat(), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $commande->montant, 'data-type' => 'remboursement']);
$buttons_credit = Html::a('Rembourser ' . $commande->getMontant(true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $commande->montant, 'data-type' => 'remboursement']);
} elseif ($commande->montant > $montant_paye) { } elseif ($commande->montant > $montant_paye) {
$montant_payer = $commande->montant - $montant_paye; $montant_payer = $commande->montant - $montant_paye;
$html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($montant_payer, 2) . ' €</strong> à payer'; $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($montant_payer, 2) . ' €</strong> à payer';

+ 11
- 5
backend/models/CreditForm.php View File

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


public $id_user ; public $id_user ;
public $id_user_action ; public $id_user_action ;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['montant'], 'required'], [['montant'], 'required'],
[['id_user', 'id_user_action', 'id_etablissement'], 'integer'], [['id_user', 'id_user_action', 'id_etablissement'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_user' => 'Utilisateur', 'id_user' => 'Utilisateur',
'id_user_action' => 'Utilisateur', 'id_user_action' => 'Utilisateur',
]; ];
} }
public function save() {
/**
* Enregistre un modèle CreditHistorique.
*/
public function save()
{
if ($this->validate()) { if ($this->validate()) {
$credit_historique = new CreditHistorique ; $credit_historique = new CreditHistorique ;
$credit_historique->id_user = $this->id_user; $credit_historique->id_user = $this->id_user;
'credit_form' => $this 'credit_form' => $this
]) ; ]) ;
} }
} }
} }



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

/** /**
* 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 $subject; public $subject;
public $body; public $body;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
// name, email, subject and body are required // name, email, subject and body are required
[['subject', 'body'], 'required', 'message' => 'Champs obligatoire'], [['subject', 'body'], 'required', 'message' => 'Champs obligatoire'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'subject' => 'Sujet', 'subject' => 'Sujet',
'body' => 'Message', 'body' => 'Message',
* @param string $email the target email address * @param string $email the target email address
* @return boolean whether the email was sent * @return boolean whether the email was sent
*/ */
public function sendEmail($email) {
public function sendEmail($email)
{


return Yii::$app->mailer->compose() return Yii::$app->mailer->compose()
->setTo($email) ->setTo($email)

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

<?php endif; ?> <?php endif; ?>


<div class="clr"></div> <div class="clr"></div>

<?php $etat_paiement_etablissement = Yii::$app->user->identity->etatPaiementEtablissement(); ?>
<?php if ($etat_paiement_etablissement == 'essai'): ?>
<span id="etat-paiement-etablissement">Période d'essai gratuite
<span class="strong"><?php echo Yii::$app->user->identity->periodeEssai(); ?> jours</span> <a class="btn btn-success" href="<?php echo Yii::$app->urlManager->createUrl(['paiement/index']) ?>">S'abonner</a>
</span>
<?php elseif ($etat_paiement_etablissement == Etablissement::PAIEMENT_ESSAI_TERMINE || $etat_paiement_etablissement == Etablissement::PAIEMENT_RETARD): ?>
<span id="etat-paiement-etablissement">
<span class="strong">
<?php if ($etat_paiement_etablissement == Etablissement::PAIEMENT_ESSAI_TERMINE): ?>Période d'essai gratuite terminée
<?php elseif ($etat_paiement_etablissement == Etablissement::PAIEMENT_RETARD): ?>Retard de paiement
<?php endif; ?>
</span>
</span>
<?php endif; ?>
</div> </div>
<?php endif; ?> <?php endif; ?>



+ 0
- 39
backend/views/paiement/index.php View File



$this->title = 'Paiement'; $this->title = 'Paiement';


$etat_paiement = Yii::$app->user->identity->etatPaiementEtablissement() ;

?> ?>


<h1>Paiement</h1> <h1>Paiement</h1>

<div class="alert alert-warning">
<?php if($etat_paiement == Etablissement::PAIEMENT_ESSAI_TERMINE): ?>
Votre période d'essai gratuite est terminée.<br />
Vous pouvez continuer à bénéficier de ce service en vous abonnant à <strong>La boîte à pain</strong>
pour <strong>30 € / mois</strong>
<?php elseif($etat_paiement == Etablissement::PAIEMENT_RETARD): ?>
Nous constatons un retard de paiement sur votre compte.<br />
Nous vous invitons à vérifier que tout est en ordre au niveau de votre compte Paypal ou à vous
abonner à nouveau en utilisant le bouton ci-dessous (<strong>30 € / mois</strong>).
<?php elseif($etat_paiement == Etablissement::PAIEMENT_ESSAI): ?>
Si vous souhaitez profiter de ce service au-delà de la période d'essai gratuite,
abonnez-vous à <strong>La boîte à pain</strong> pour <strong>30 € / mois</strong>.
<?php endif; ?>
</div>
<div class="alert alert-info">Si vous rencontrez des difficultés, n'hésitez pas à nous contacter.</div>


<!--<h2>Prod</h2>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="K96K2WLBSBDSA">
<input name="custom" value="<?php echo Yii::$app->user->identity->id; ?>" type="hidden" />
<input type="image" src="https://www.paypalobjects.com/fr_FR/FR/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal, le réflexe sécurité pour payer en ligne">
<img alt="" border="0" src="https://www.paypalobjects.com/fr_FR/i/scr/pixel.gif" width="1" height="1">
</form>-->

<!--<h2>Test</h2>-->
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="USASPWAC39S4N">
<input name="custom" value="<?php echo Yii::$app->user->identity->id; ?>" type="hidden" />
<input type="image" src="https://www.sandbox.paypal.com/fr_FR/FR/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal, le réflexe sécurité pour payer en ligne">
<img alt="" border="0" src="https://www.sandbox.paypal.com/fr_FR/i/scr/pixel.gif" width="1" height="1">
</form>


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

<td class="historique"><?= $c->getStrHistorique() ; ?></td> <td class="historique"><?= $c->getStrHistorique() ; ?></td>
<td><?= $c->getResumePanier() ; ?></td> <td><?= $c->getResumePanier() ; ?></td>
<td><?= $c->getResumePointVente() ; ?></td> <td><?= $c->getResumePointVente() ; ?></td>
<td><?= $c->getStrMontant() ; ?></td>
<td><?= $c->getMontant(true) ; ?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>

+ 253
- 114
common/models/Commande.php View File

* @property integer $id_production * @property integer $id_production
* @property boolean $paiement_automatique * @property boolean $paiement_automatique
*/ */
class Commande extends \yii\db\ActiveRecord {

var $montant = 0;
var $montant_pain = 0;
var $montant_vrac = 0;
var $montant_paye = 0;
var $poids_pain = 0;
var $poids_vrac = 0;
class Commande extends \yii\db\ActiveRecord
{


var $montant = 0 ;
var $montant_paye = 0 ;
var $poids = 0 ;
const TYPE_AUTO = 'auto'; const TYPE_AUTO = 'auto';
const TYPE_USER = 'user'; const TYPE_USER = 'user';
const TYPE_ADMIN = 'admin'; const TYPE_ADMIN = 'admin';
const STATUT_PAYEE = 'payee'; const STATUT_PAYEE = 'payee';
const STATUT_IMPAYEE = 'impayee'; const STATUT_IMPAYEE = 'impayee';
const STATUT_SURPLUS = 'surplus'; const STATUT_SURPLUS = 'surplus';
const ETAT_MODIFIABLE = 'ouverte'; const ETAT_MODIFIABLE = 'ouverte';
const ETAT_PREPARATION = 'preparation'; const ETAT_PREPARATION = 'preparation';
const ETAT_LIVREE = 'livree'; const ETAT_LIVREE = 'livree';
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'commande'; return 'commande';
} }


public function init() {
if (isset($this->commandeProduits)) {
foreach ($this->commandeProduits as $p) {
if ($p->mode_vente == 'unite') {
$this->montant_pain += $p->prix * $p->quantite;
if(isset($p->produit))
$this->poids_pain += ($p->quantite * $p->produit->poids) / 1000 ;
} elseif ($p->mode_vente == 'poids') {
$this->montant_pain += $p->prix * $p->quantite / 1000;
}
}

$this->montant = $this->montant_vrac + $this->montant_pain;
}
if (isset($this->creditHistorique) && !$this->montant_paye) {
foreach ($this->creditHistorique as $ch) {
if ($ch->type == CreditHistorique::TYPE_PAIEMENT)
$this->montant_paye += $ch->montant;
elseif ($ch->type == CreditHistorique::TYPE_REMBOURSEMENT)
$this->montant_paye -= $ch->montant;
}
}
}

public static function getQuantiteProduit($id_produit, $commandes) {

$quantite = 0;

if (isset($commandes) && is_array($commandes) && count($commandes)) {
foreach ($commandes as $c) {
if(is_null($c->date_delete)) {
foreach ($c->commandeProduits as $cp) {
if ($cp->id_produit == $id_produit)
$quantite += $cp->quantite;
}
}
}
}

return $quantite;
}

/* /*
* relations * relations
*/ */


public function getUser() {
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'id_user']); return $this->hasOne(User::className(), ['id' => 'id_user']);
} }


public function getCommandeProduits() {
return $this->hasMany(CommandeProduit::className(), ['id_commande' => 'id'])->with('produit');
public function getCommandeProduits()
{
return $this->hasMany(CommandeProduit::className(),['id_commande' => 'id'])
->with('produit');
} }


public function getProduction() {
return $this->hasOne(Production::className(), ['id' => 'id_production'])->with('etablissement');
public function getProduction()
{
return $this->hasOne(Production::className(), ['id' => 'id_production'])
->with('etablissement');
} }


public function getPointVente() {
return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente'])->with('pointVenteUser');
public function getPointVente()
{
return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente'])
->with('pointVenteUser');
} }


public function getCreditHistorique() {
public function getCreditHistorique()
{
return $this->hasMany(CreditHistorique::className(), ['id_commande' => 'id']); return $this->hasMany(CreditHistorique::className(), ['id_commande' => 'id']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_user', 'date', 'id_point_vente', 'id_production'], 'required', 'message' => ''], [['id_user', 'date', 'id_point_vente', 'id_production'], 'required', 'message' => ''],
[['id_user', 'id_point_vente', 'id_production'], 'integer'], [['id_user', 'id_point_vente', 'id_production'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_user' => 'Id User', 'id_user' => 'Id User',
'id_production' => 'Date de production', 'id_production' => 'Date de production',
]; ];
} }

public function strListeVrac() {
$str = '';

foreach ($this->commandeProduits as $cp) {
if ($cp->produit->vrac) {
$str .= $cp->quantite . '&nbsp;' . Html::encode($cp->produit->diminutif) . ', ';
/**
* Initialise le montant total, le montant déjà payé et le poids de la
* commande
*/
public function init()
{
// Montant
if (isset($this->commandeProduits)) {
foreach ($this->commandeProduits as $p) {
if ($p->mode_vente == 'unite') {
$this->montant += $p->prix * $p->quantite;
if(isset($p->produit)) {
$this->poids += ($p->quantite * $p->produit->poids) / 1000 ;
}
}
elseif ($p->mode_vente == 'poids') {
$this->montant += $p->prix * $p->quantite / 1000;
}
}
}
// Montant payé
if (isset($this->creditHistorique) && !$this->montant_paye) {
foreach ($this->creditHistorique as $ch) {
if ($ch->type == CreditHistorique::TYPE_PAIEMENT) {
$this->montant_paye += $ch->montant;
}
elseif ($ch->type == CreditHistorique::TYPE_REMBOURSEMENT) {
$this->montant_paye -= $ch->montant;
}
} }
} }

return substr($str, 0, strlen($str) - 2);
} }
/**
* Retourne la quantité d'un produit donné de plusieurs commandes.
*
* @param integer $id_produit
* @param array $commandes
*
* @return integer
*/
public static function getQuantiteProduit($id_produit, $commandes)
{
$quantite = 0;
if (isset($commandes) && is_array($commandes) && count($commandes)) {
foreach ($commandes as $c) {
if(is_null($c->date_delete)) {
foreach ($c->commandeProduits as $cp) {
if ($cp->id_produit == $id_produit) {
$quantite += $cp->quantite;
}
}
}
}
}


public function getMontantPaye() {
return $quantite;
}
/**
* Retourne le montant payé de la commande.
*
* @return float
*/
public function getMontantPaye()
{
if ($this->montant_paye) { if ($this->montant_paye) {
return $this->montant_paye; return $this->montant_paye;
} else {
}
else {
$historique = CreditHistorique::find() $historique = CreditHistorique::find()
->where(['id_commande' => $this->id]) ->where(['id_commande' => $this->id])
->all(); ->all();
$montant = 0; $montant = 0;


foreach ($historique as $ch) { foreach ($historique as $ch) {
if ($ch->type == CreditHistorique::TYPE_PAIEMENT)
if ($ch->type == CreditHistorique::TYPE_PAIEMENT) {
$montant += $ch->montant; $montant += $ch->montant;
elseif ($ch->type == CreditHistorique::TYPE_REMBOURSEMENT)
}
elseif ($ch->type == CreditHistorique::TYPE_REMBOURSEMENT) {
$montant -= $ch->montant; $montant -= $ch->montant;
}
} }


return $montant; return $montant;
} }
} }


public function getMontant($format = false) {
if ($format)
/**
* Retourne le montant de la commande.
*
* @param boolean $format
* @return float
*/
public function getMontant($format = false)
{
if ($format) {
return number_format($this->getMontant(), 2) . ' €'; return number_format($this->getMontant(), 2) . ' €';
else
}
else {
return $this->montant; return $this->montant;
}
} }


public function getMontantFormat() {
return number_format($this->getMontant(), 2) . ' €';
}

public function getMontantRestant($format = false) {
/**
* Retourne le montant restant à payer.
*
* @param boolean $format
* @return float
*/
public function getMontantRestant($format = false)
{
$montant_restant = $this->getMontant() - $this->getMontantPaye(); $montant_restant = $this->getMontant() - $this->getMontantPaye();
if ($format)
if ($format) {
return number_format($montant_restant, 2) . ' €'; return number_format($montant_restant, 2) . ' €';
else
}
else {
return $montant_restant; return $montant_restant;
}
} }


public function getMontantSurplus($format = false) {
/**
* Retourne le montant payé en surplus.
*
* @param boolean $format
* @return float
*/
public function getMontantSurplus($format = false)
{
$montant_surplus = $this->getMontantPaye() - $this->getMontant(); $montant_surplus = $this->getMontantPaye() - $this->getMontant();
if ($format)
if ($format) {
return number_format($montant_surplus, 2) . ' €'; return number_format($montant_surplus, 2) . ' €';
else
}
else {
return $montant_surplus; return $montant_surplus;
}
} }


public function getDataJson() {
/**
* Retourne les informations relatives à la commande au format JSON.
*
* @return string
*/
public function getDataJson()
{
$commande = Commande::find()->with('commandeProduits')->where(['id' => $this->id])->one(); $commande = Commande::find()->with('commandeProduits')->where(['id' => $this->id])->one();

$commande->init(); $commande->init();


$json_commande = [ $json_commande = [
'str_montant' => $commande->getMontantFormat(), 'str_montant' => $commande->getMontantFormat(),
'montant_paye' => $commande->getMontantPaye(), 'montant_paye' => $commande->getMontantPaye(),
'commentaire' => $commande->commentaire, 'commentaire' => $commande->commentaire,
];
];


foreach ($commande->commandeProduits as $commande_produit) { foreach ($commande->commandeProduits as $commande_produit) {
$json_commande['produits'][$commande_produit->id_produit] = $commande_produit->quantite; $json_commande['produits'][$commande_produit->id_produit] = $commande_produit->quantite;
return json_encode($json_commande); return json_encode($json_commande);
} }


public function creditHistorique($type, $montant, $id_etablissement, $id_user, $id_user_action) {
/**
* Enregistre un modèle de type CreditHistorique.
*
* @param string $type
* @param float $montant
* @param integer $id_etablissement
* @param integer $id_user
* @param integer $id_user_action
*/
public function creditHistorique($type, $montant, $id_etablissement, $id_user, $id_user_action)
{
$credit_historique = new CreditHistorique; $credit_historique = new CreditHistorique;
$credit_historique->id_user = $this->id_user; $credit_historique->id_user = $this->id_user;
$credit_historique->id_commande = $this->id; $credit_historique->id_commande = $this->id;
$credit_historique->save(); $credit_historique->save();
} }


public function getStatutPaiement() {
/**
* Retourne le statut de paiement de la commande (payée, surplus, ou impayée).
*
* @return string
*/
public function getStatutPaiement()
{
// payé // payé
if ($this->getMontant() - $this->getMontantPaye() < 0.01 && if ($this->getMontant() - $this->getMontantPaye() < 0.01 &&
$this->getMontant() - $this->getMontantPaye() >= 0) {
$this->getMontant() - $this->getMontantPaye() >= 0)
{
return self::STATUT_PAYEE; return self::STATUT_PAYEE;
} }
// à rembourser // à rembourser
return self::STATUT_IMPAYEE; return self::STATUT_IMPAYEE;
} }
} }

public function getResumePanier() {
if (!isset($this->commandeProduits))
/**
* Retourne le résumé du panier au format HTML.
*
* @return string
*/
public function getResumePanier()
{
if (!isset($this->commandeProduits)) {
$this->commandeProduits = CommandeProduit::find()->where(['id_commande' => $this->id])->all(); $this->commandeProduits = CommandeProduit::find()->where(['id_commande' => $this->id])->all();

}
$html = ''; $html = '';
$count = count($this->commandeProduits); $count = count($this->commandeProduits);
$i = 0; $i = 0;
foreach ($this->commandeProduits as $p) { foreach ($this->commandeProduits as $p) {
if (isset($p->produit)) { if (isset($p->produit)) {
$html .= $p->quantite . ' x ' . Html::encode($p->produit->nom); $html .= $p->quantite . ' x ' . Html::encode($p->produit->nom);
if (++$i != $count)
if (++$i != $count) {
$html .= '<br />'; $html .= '<br />';
}
} }
} }
return $html; return $html;
} }


public function getResumePointVente() {
/**
* Retourne le résumé du point de vente lié à la commande au format HTML.
*
* @return string
*/
public function getResumePointVente()
{
$html = ''; $html = '';


if (isset($this->pointVente)) { if (isset($this->pointVente)) {
return $html; return $html;
} }


public function getStrMontant() {
return number_format($this->montant, 2) . ' €';
}

public function getResumeMontant() {
/**
* Retourne le résumé du paiement (montant, statut).
*
* @return string
*/
public function getResumeMontant()
{
$html = ''; $html = '';


$html .= $this->getStrMontant() . '<br />';
$html .= $this->getMontant(true) . '<br />';


if ($this->montant_paye) { if ($this->montant_paye) {
if ($this->getStatutPaiement() == Commande::STATUT_PAYEE) { if ($this->getStatutPaiement() == Commande::STATUT_PAYEE) {
} elseif ($this->getStatutPaiement() == Commande::STATUT_SURPLUS) { } elseif ($this->getStatutPaiement() == Commande::STATUT_SURPLUS) {
$html .= '<span class="label label-success">Payée</span>'; $html .= '<span class="label label-success">Payée</span>';
} }
} else {
}
else {
$html .= '<span class="label label-default">À régler sur place</span>'; $html .= '<span class="label label-default">À régler sur place</span>';
} }


return $html; return $html;
} }


public function getStrUser() {
/**
* Retourne une chaine de caractère décrivant l'utilisateur lié à la commande.
*
* @return string
*/
public function getStrUser()
{
if (isset($this->user)) { if (isset($this->user)) {
return Html::encode($this->user->prenom . ' ' . $this->user->nom); return Html::encode($this->user->prenom . ' ' . $this->user->nom);
} elseif (strlen($this->username)) { } elseif (strlen($this->username)) {
} }
} }


public static function findBy($params = []) {
/**
* Recherche dans les commandes suivant les paramètres suivants :
* - id_etablissement
* - condition
* - date
* - type
* - orderby
* - limit
*
* @param array $params
* @return array
*/
public static function findBy($params = [])
{
if (!isset($params['id_etablissement'])) if (!isset($params['id_etablissement']))
$params['id_etablissement'] = Yii::$app->user->identity->id_etablissement; $params['id_etablissement'] = Yii::$app->user->identity->id_etablissement;


return $commandes; return $commandes;
} }


public function getEtat() {
/**
* Retourne l'état de la commande (livrée, modifiable ou en préparation)
*
* @return string
*/
public function getEtat()
{
$delai_commande = Etablissement::getConfig('delai_commande', $this->production->id_etablissement); $delai_commande = Etablissement::getConfig('delai_commande', $this->production->id_etablissement);
$heure_limite = Etablissement::getConfig('heure_limite_commande', $this->production->id_etablissement); $heure_limite = Etablissement::getConfig('heure_limite_commande', $this->production->id_etablissement);




if ($nb_jours <= 0) { if ($nb_jours <= 0) {
return self::ETAT_LIVREE; return self::ETAT_LIVREE;
} elseif ($nb_jours >= $delai_commande &&
}
elseif ($nb_jours >= $delai_commande &&
($nb_jours != $delai_commande || ($nb_jours != $delai_commande ||
($nb_jours == $delai_commande && $heure_today < $heure_limite))) {
($nb_jours == $delai_commande && $heure_today < $heure_limite)))
{
return self::ETAT_MODIFIABLE; return self::ETAT_MODIFIABLE;
} }


return self::ETAT_PREPARATION; return self::ETAT_PREPARATION;
} }


/**
* Retourne le type de la commande (client, automatique ou admin) sous forme
* texte ou HTML.
*
* @param boolean $with_label
* @return string
*/
public function getStrType($with_label = false) { public function getStrType($with_label = false) {
$class_label = ''; $class_label = '';
$str = ''; $str = '';
return $str; return $str;
} }


public function getStrHistorique() {
/**
* Retourne l'historique de la commande (ajoutée, modifiée, supprimée) au format
* HTML.
*
* @return string
*/
public function getStrHistorique()
{
$arr = [ $arr = [
'class' => 'create', 'class' => 'create',
'glyphicon' => 'plus', 'glyphicon' => 'plus',
return $html ; return $html ;
} }
public function getClassHistorique() {
/**
* Retourne une classe identifiant l'historique de la commande (ajoutée,
* modifiée, supprimée).
*
* @return string
*/
public function getClassHistorique()
{
if(!is_null($this->date_delete)) { if(!is_null($this->date_delete)) {
return 'commande-delete' ; return 'commande-delete' ;
} }
return 'commande-create' ; return 'commande-create' ;
} }
}
}

+ 51
- 17
common/models/CommandeAuto.php View File

* @property string $username * @property string $username
* @property string $paiement_automatique * @property string $paiement_automatique
*/ */
class CommandeAuto extends \yii\db\ActiveRecord {
class CommandeAuto extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'commande_auto'; return 'commande_auto';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_etablissement', 'id_point_vente'], 'required'], [['id_etablissement', 'id_point_vente'], 'required'],
[['id_user', 'id_etablissement', 'id_point_vente', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'periodicite_semaine'], 'integer'], [['id_user', 'id_etablissement', 'id_point_vente', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'periodicite_semaine'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_user' => 'Utilisateur', 'id_user' => 'Utilisateur',
]; ];
} }


public function getUser() {
/*
* Relations
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'id_user']); return $this->hasOne(User::className(), ['id' => 'id_user']);
} }


public function getEtablissement() {
public function getEtablissement()
{
return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']); return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']);
} }


public function getPointVente() {
public function getPointVente()
{
return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente']); return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente']);
} }


public function getCommandeAutoProduit() {
public function getCommandeAutoProduit()
{
return $this->hasMany(CommandeAutoProduit::className(), ['id_commande_auto' => 'id'])->with('produit'); return $this->hasMany(CommandeAutoProduit::className(), ['id_commande_auto' => 'id'])->with('produit');
} }


public static function getAll($date) {
/**
* Retourne les commandes récurrentes pour une date donnée.
*
* @param string $date
* @return array
*/
public static function getAll($date)
{
$date = date('Y-m-d', strtotime($date)); $date = date('Y-m-d', strtotime($date));


// commandes auto // commandes auto
foreach ($commandes_auto as $c) { foreach ($commandes_auto as $c) {
// vérif dates // vérif dates
if ($date >= $c->date_debut && if ($date >= $c->date_debut &&
(!$c->date_fin || $date <= $c->date_fin)) {
(!$c->date_fin || $date <= $c->date_fin))
{
// périodicite // périodicite
$nb_jours = (strtotime($date) - strtotime($c->date_debut)) / (24 * 60 * 60); $nb_jours = (strtotime($date) - strtotime($c->date_debut)) / (24 * 60 * 60);
if ($nb_jours % ($c->periodicite_semaine * 7) < 7) { if ($nb_jours % ($c->periodicite_semaine * 7) < 7) {
return $arr_commandes_auto; return $arr_commandes_auto;
} }


public static function addAll($date, $force = false) {
/**
* Ajoute les commandes pour une date donnée à partir des commnandes
* récurrentes.
*
* @param string $date
* @param boolean $force
*/
public static function addAll($date, $force = false)
{
// production // production
$production = Production::findOne([ $production = Production::findOne([
'date' => date('Y-m-d', strtotime($date)),
'id_etablissement' => Yii::$app->user->identity->id_etablissement
]);
'date' => date('Y-m-d', strtotime($date)),
'id_etablissement' => Yii::$app->user->identity->id_etablissement
]);


if ($production) { if ($production) {
$count_commandes_prod = Commande::find() $count_commandes_prod = Commande::find()
->where(['id_production' => $production->id])
->count();
->where(['id_production' => $production->id])
->count();


if (!$count_commandes_prod || $force) { if (!$count_commandes_prod || $force) {
$commandes_auto = self::getAll($date); $commandes_auto = self::getAll($date);
} }
} }


public function add($date) {
/**
* Ajoute la commande récurrente pour une date donnée.
*
* @param string $date
*/
public function add($date)
{
// production // production
$production = Production::find() $production = Production::find()
->where([ ->where([

+ 23
- 8
common/models/CommandeAutoForm.php View File

/** /**
* Login form * Login form
*/ */
class CommandeAutoForm extends Model {
class CommandeAutoForm extends Model
{


public $id; public $id;
public $id_user; public $id_user;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_etablissement', 'periodicite_semaine', 'id_point_vente'], 'integer'], [['id_etablissement', 'periodicite_semaine', 'id_point_vente'], 'integer'],
[['date_debut', 'date_fin'], 'date', 'format' => 'php:d/m/Y'], [['date_debut', 'date_fin'], 'date', 'format' => 'php:d/m/Y'],
]; ];
} }


public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_user' => 'Utilisateur', 'id_user' => 'Utilisateur',
]; ];
} }


public function save() {
/**
* Enregistre la CommandeAuto.
*
* @return boolean
*/
public function save()
{
if ($this->id) { if ($this->id) {
$commandeauto = CommandeAuto::findOne($this->id); $commandeauto = CommandeAuto::findOne($this->id);
} else {
}
else {
$commandeauto = new CommandeAuto; $commandeauto = new CommandeAuto;
} }


$commandeauto->username = $this->username; $commandeauto->username = $this->username;
$commandeauto->id_etablissement = $this->id_etablissement; $commandeauto->id_etablissement = $this->id_etablissement;
$commandeauto->id_point_vente = $this->id_point_vente; $commandeauto->id_point_vente = $this->id_point_vente;
$commandeauto->date_debut = date('Y-m-d', strtotime(str_replace('/', '-', $this->date_debut)));
$commandeauto->date_debut = date(
'Y-m-d',
strtotime(str_replace('/', '-', $this->date_debut)
));
if (strlen($this->date_fin)) { if (strlen($this->date_fin)) {
$commandeauto->date_fin = date('Y-m-d', strtotime(str_replace('/', '-', $this->date_fin)));
$commandeauto->date_fin = date(
'Y-m-d',
strtotime(str_replace('/', '-', $this->date_fin)
));
} }
$commandeauto->lundi = $this->lundi; $commandeauto->lundi = $this->lundi;
$commandeauto->mardi = $this->mardi; $commandeauto->mardi = $this->mardi;
} }
} }
} }

return true; return true;
} }



+ 14
- 5
common/models/CommandeAutoProduit.php View File

* @property integer $id_produit * @property integer $id_produit
* @property double $quantite * @property double $quantite
*/ */
class CommandeAutoProduit extends \yii\db\ActiveRecord {
class CommandeAutoProduit extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'commande_auto_produit'; return 'commande_auto_produit';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_commande_auto', 'id_produit'], 'required'], [['id_commande_auto', 'id_produit'], 'required'],
[['id_commande_auto', 'id_produit'], 'integer'], [['id_commande_auto', 'id_produit'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_commande_auto' => 'Id Commande Auto', 'id_commande_auto' => 'Id Commande Auto',
]; ];
} }


public function getProduit() {
/*
* Relations
*/
public function getProduit()
{
return $this->hasOne(Produit::className(), ['id' => 'id_produit']); return $this->hasOne(Produit::className(), ['id' => 'id_produit']);
} }



+ 11
- 6
common/models/CommandeProduit.php View File

* @property integer $id_produit * @property integer $id_produit
* @property double $quantite * @property double $quantite
*/ */
class CommandeProduit extends \yii\db\ActiveRecord {
class CommandeProduit extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'commande_produit'; return 'commande_produit';
} }


* Relations * Relations
*/ */


public function getProduit() {
public function getProduit()
{
return $this->hasOne(Produit::className(), ['id' => 'id_produit']); return $this->hasOne(Produit::className(), ['id' => 'id_produit']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_commande', 'id_produit', 'quantite'], 'required'], [['id_commande', 'id_produit', 'quantite'], 'required'],
[['id_commande', 'id_produit'], 'integer'], [['id_commande', 'id_produit'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_commande' => 'Id Commande', 'id_commande' => 'Id Commande',
]; ];
} }


}
}

+ 8
- 4
common/models/ContactForm.php View File

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


public $name; public $name;
public $email; public $email;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
// name, email, subject and body are required // name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required', 'message' => 'Champs obligatoire'], [['name', 'email', 'subject', 'body'], 'required', 'message' => 'Champs obligatoire'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'name' => 'Nom', 'name' => 'Nom',
'email' => 'Email', 'email' => 'Email',
* @param string $email the target email address * @param string $email the target email address
* @return boolean whether the email was sent * @return boolean whether the email was sent
*/ */
public function sendEmail($email) {
public function sendEmail($email)
{


return Yii::$app->mailer->compose([ return Yii::$app->mailer->compose([
'html' => 'contact-html', 'html' => 'contact-html',

+ 94
- 18
common/models/CreditHistorique.php View File

* @property integer $id_etablissement * @property integer $id_etablissement
* @property string $moyen_paiement * @property string $moyen_paiement
*/ */
class CreditHistorique extends ActiveRecord {
class CreditHistorique extends ActiveRecord
{


const TYPE_CREDIT_INITIAL = 'credit-initial'; const TYPE_CREDIT_INITIAL = 'credit-initial';
const TYPE_CREDIT = 'credit'; const TYPE_CREDIT = 'credit';
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'credit_historique'; return 'credit_historique';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['montant'], 'required'], [['montant'], 'required'],
[['id_user', 'id_user_action', 'id_commande', 'id_etablissement'], 'integer'], [['id_user', 'id_user_action', 'id_commande', 'id_etablissement'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_user' => 'Utilisateur', 'id_user' => 'Utilisateur',
]; ];
} }


public function getUser() {
/*
* Relations
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'id_user']); return $this->hasOne(User::className(), ['id' => 'id_user']);
} }


public function getUserAction() {
public function getUserAction()
{
return $this->hasOne(User::className(), ['id' => 'id_user_action']); return $this->hasOne(User::className(), ['id' => 'id_user_action']);
} }


public function getCommande() {
public function getCommande()
{
return $this->hasOne(Commande::className(), ['id' => 'id_commande']); return $this->hasOne(Commande::className(), ['id' => 'id_commande']);
} }


public function getLibelleType() {
/**
* Retourne le type de CreditHistorique (paiement, remboursement ou débit).
*
* @return string
*/
public function getLibelleType()
{
switch ($this->type) { switch ($this->type) {
case 'paiement': case 'paiement':
return 'Paiement'; return 'Paiement';
} }
} }


public function save($runValidation = true, $attributeNames = NULL) {
/**
* Enregistre le modèle.
*
* @param boolean $runValidation
* @param array $attributeNames
*/
public function save($runValidation = true, $attributeNames = NULL)
{
// initialisation du commentaire avant sauvegarde // initialisation du commentaire avant sauvegarde
$this->commentaire .= $this->getStrCommentaire() ; $this->commentaire .= $this->getStrCommentaire() ;
} }
} }
public function isTypeDebit() {
/**
* Retourne si le CreditHistorique est un débit ou non.
*
* @return boolean
*/
public function isTypeDebit()
{
return in_array($this->type, [ return in_array($this->type, [
self::TYPE_DEBIT, self::TYPE_DEBIT,
self::TYPE_PAIEMENT, self::TYPE_PAIEMENT,
]) ; ]) ;
} }
public function isTypeCredit() {
/**
* Retourne si le CreditHistorique est un crédit ou non.
*
* @return boolean
*/
public function isTypeCredit()
{
return in_array($this->type, [ return in_array($this->type, [
self::TYPE_CREDIT, self::TYPE_CREDIT,
self::TYPE_CREDIT_INITIAL, self::TYPE_CREDIT_INITIAL,
]) ; ]) ;
} }
public function getMontant($format = false) {
/**
* Retourne le montant.
*
* @param boolean $format
* @return float
*/
public function getMontant($format = false)
{
if($format) if($format)
return number_format($this->montant,2) .' €' ; return number_format($this->montant,2) .' €' ;
else else
return $this->montant ; return $this->montant ;
} }
public function getStrLibelle() {
/**
* Retourne le libellé du CreditHistorique informant de son type et
* éventuellement de la date de sa commande associée.
*
* @return string
*/
public function getStrLibelle()
{
$str = '' ; $str = '' ;
if($this->type == self::TYPE_CREDIT_INITIAL) { if($this->type == self::TYPE_CREDIT_INITIAL) {
} }
} }
return $str ; return $str ;
} }
public function getStrCommentaire() {
/**
* Retourne les informations à ajouter au commentaire du CreditHistorique
* (libellé, montant, client, action) au format HTML.
*
* @return string
*/
public function getStrCommentaire()
{
$str = '' ; $str = '' ;
if(strlen($this->commentaire)) { if(strlen($this->commentaire)) {
$str .= '<br />' ; $str .= '<br />' ;
return $str ; return $str ;
} }
public function getDate($format = false) {
/**
* Retourne la date.
*
* @param boolean $format
* @return string
*/
public function getDate($format = false)
{
if($format) if($format)
return date('d/m/Y à H:i:s',strtotime($this->date)) ; return date('d/m/Y à H:i:s',strtotime($this->date)) ;
else else
return $this->date ; return $this->date ;
} }
public function getStrMoyenPaiement() {
/**
* Retourne le moyen de paiement.
*
* @return string
*/
public function getStrMoyenPaiement()
{
switch($this->moyen_paiement) { switch($this->moyen_paiement) {
case CreditHistorique::MOYEN_ESPECES : return 'Espèces' ; case CreditHistorique::MOYEN_ESPECES : return 'Espèces' ;
case CreditHistorique::MOYEN_CHEQUE : return 'Chèque' ; case CreditHistorique::MOYEN_CHEQUE : return 'Chèque' ;
} }
} }
public function strUserAction() {
/**
* Retourne le libellé de l'utilisateur ayant initié l'action.
*
* @return string
*/
public function strUserAction()
{
if($this->userAction) { if($this->userAction) {
return $this->userAction->nom . ' ' . $this->userAction->prenom ; return $this->userAction->nom . ' ' . $this->userAction->prenom ;
} }

+ 22
- 7
common/models/Developpement.php View File

* @property string $statut * @property string $statut
* @property double $estimation_temps * @property double $estimation_temps
*/ */
class Developpement extends \yii\db\ActiveRecord {
class Developpement extends \yii\db\ActiveRecord
{


const STATUT_OPEN = 'open'; const STATUT_OPEN = 'open';
const STATUT_CLOSED = 'closed'; const STATUT_CLOSED = 'closed';
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'developpement'; return 'developpement';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['objet', 'date'], 'required'], [['objet', 'date'], 'required'],
[['id', 'avancement'], 'integer'], [['id', 'avancement'], 'integer'],
]; ];
} }


public function getDeveloppementPriorite() {
/*
* Relations
*/
public function getDeveloppementPriorite()
{
return $this->hasMany(DeveloppementPriorite::className(), ['id_developpement' => 'id'])->with('etablissement'); return $this->hasMany(DeveloppementPriorite::className(), ['id_developpement' => 'id'])->with('etablissement');
} }


public function getDeveloppementPrioriteCurrentEtablissement() {
public function getDeveloppementPrioriteCurrentEtablissement()
{
return $this->hasOne(DeveloppementPriorite::className(), ['id_developpement' => 'id'])->where(['id_etablissement' => Yii::$app->user->identity->id_etablissement])->with('etablissement'); return $this->hasOne(DeveloppementPriorite::className(), ['id_developpement' => 'id'])->where(['id_etablissement' => Yii::$app->user->identity->id_etablissement])->with('etablissement');
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'objet' => 'Sujet', 'objet' => 'Sujet',
'date_livraison' => 'Date de livraison' 'date_livraison' => 'Date de livraison'
]; ];
} }

/**
* Définit une date de livraison.
*
* @param string $date
*/
public function setDateLivraison($date = '') { public function setDateLivraison($date = '') {


if (strlen($date)) if (strlen($date))

+ 28
- 7
common/models/DeveloppementPriorite.php View File

* @property integer $id_user * @property integer $id_user
* @property integer $id_developpement * @property integer $id_developpement
*/ */
class DeveloppementPriorite extends \yii\db\ActiveRecord {
class DeveloppementPriorite extends \yii\db\ActiveRecord
{


const PRIORITE_HAUTE = 'haute'; const PRIORITE_HAUTE = 'haute';
const PRIORITE_NORMALE = 'normale'; const PRIORITE_NORMALE = 'normale';
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'developpement_priorite'; return 'developpement_priorite';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_etablissement', 'id_developpement'], 'required'], [['id_etablissement', 'id_developpement'], 'required'],
[['id_etablissement', 'id_developpement'], 'integer'], [['id_etablissement', 'id_developpement'], 'integer'],
[['priorite'], 'string'], [['priorite'], 'string'],
]; ];
} }
/*
* Relations
*/


public function getEtablissement() {
public function getEtablissement()
{
return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']); return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_etablissement' => 'Établissement', 'id_etablissement' => 'Établissement',
'id_developpement' => 'Développement', 'id_developpement' => 'Développement',
]; ];
} }


public function getStrPriorite() {
/**
* Retourne la priorité.
*
* @return string
*/
public function getStrPriorite()
{
switch ($this->priorite) { switch ($this->priorite) {
case self::PRIORITE_BASSE : return 'Basse'; case self::PRIORITE_BASSE : return 'Basse';
break; break;
} }
} }


public function getClassCssStyleBouton() {
/**
* Retourne la classe CSS du bouton servant à définir la priorité.
*
* @return string
*/
public function getClassCssStyleBouton()
{
$style_bouton = 'default'; $style_bouton = 'default';
if ($this->priorite == DeveloppementPriorite::PRIORITE_BASSE) if ($this->priorite == DeveloppementPriorite::PRIORITE_BASSE)
$style_bouton = 'info'; $style_bouton = 'info';

+ 113
- 51
common/models/Etablissement.php View File

* @property string $code_postal * @property string $code_postal
* @property string $ville * @property string $ville
*/ */
class Etablissement extends \yii\db\ActiveRecord {
class Etablissement extends \yii\db\ActiveRecord
{


const PAIEMENT_OK = 'ok'; const PAIEMENT_OK = 'ok';
const PAIEMENT_ESSAI = 'essai'; const PAIEMENT_ESSAI = 'essai';
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'etablissement'; return 'etablissement';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['nom', 'siret', 'heure_limite_commande', 'delai_commande','type'], 'required'], [['nom', 'siret', 'heure_limite_commande', 'delai_commande','type'], 'required'],
[['heure_limite_commande', 'delai_commande'], 'integer'], [['heure_limite_commande', 'delai_commande'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'nom' => 'Nom', 'nom' => 'Nom',
]; ];
} }


public function getUserEtablissement() {
return $this->hasMany(UserEtablissement::className(), ['id_etablissement' => 'id']);
/*
* Relations
*/
public function getUserEtablissement()
{
return $this->hasMany(
UserEtablissement::className(),
['id_etablissement' => 'id']
);
} }


public function getUser() {
public function getUser()
{
return $this->hasMany(User::className(), ['id_etablissement' => 'id']); return $this->hasMany(User::className(), ['id_etablissement' => 'id']);
} }
public function getContact() {
return $this->hasMany(User::className(), ['id_etablissement' => 'id'])->where(['status' => User::STATUS_BOULANGER]);
public function getContact()
{
return $this->hasMany(User::className(),['id_etablissement' => 'id'])
->where(['status' => User::STATUS_BOULANGER]);
} }


public static function getEtablissementsPopulateDropdown() {

/**
* Retourne la liste des établissements pour l'initialisation d'une liste
* sélective.
*
* @return array
*/
public static function getEtablissementsPopulateDropdown()
{
$etablissements_dispos = Etablissement::find() $etablissements_dispos = Etablissement::find()
->where(['actif' => 1]) ->where(['actif' => 1])
->orderby('code_postal, ville ASC') ->orderby('code_postal, ville ASC')
return ['data' => $data_etablissements_dispos, 'options' => $options_etablissements_dispos]; return ['data' => $data_etablissements_dispos, 'options' => $options_etablissements_dispos];
} }


public function etatPaiement() {
$date_limite = strtotime($this->date_creation) + 30 * 24 * 60 * 60;
$date = time();
$date_paiement = strtotime($this->date_paiement);

if ($date < $date_paiement + 30 * 24 * 60 * 60 || $this->gratuit) {
return 'ok';
} else {
if ($date < $date_limite) {
return 'essai';
} else {
if (!$this->date_paiement)
return 'essai-terminee';
else
return 'retard-paiement';
}
}
}

public function getCA($periode = '', $format = false) {
/**
* Retourne le CA de l'établissement pour un mois donné.
*
* @param string $periode
* @param boolean $format
* @return string
*/
public function getCA($periode = '', $format = false)
{
if (!$periode) if (!$periode)
$periode = date('Y-m'); $periode = date('Y-m');


$connection = Yii::$app->getDb(); $connection = Yii::$app->getDb();
$command = $connection->createCommand(' $command = $connection->createCommand('
SELECT SUM(IF(produit.vrac,0,commande_produit.prix * commande_produit.quantite)) AS CA
FROM commande, commande_produit, production, produit
WHERE commande.id = commande_produit.id_commande
AND production.id_etablissement = :id_etablissement
AND commande.id_production = production.id
AND commande_produit.id_produit = produit.id
AND production.date > :date_debut
AND production.date < :date_fin', [
':date_debut' => date('Y-m-31', strtotime("-1 month", strtotime($periode))),
':date_fin' => date('Y-m-01', strtotime("+1 month", strtotime($periode))),
':id_etablissement' => $this->id
SELECT SUM(IF(produit.vrac,0,commande_produit.prix * commande_produit.quantite)) AS CA
FROM commande, commande_produit, production, produit
WHERE commande.id = commande_produit.id_commande
AND production.id_etablissement = :id_etablissement
AND commande.id_production = production.id
AND commande_produit.id_produit = produit.id
AND production.date > :date_debut
AND production.date < :date_fin', [
':date_debut' => date('Y-m-31', strtotime("-1 month", strtotime($periode))),
':date_fin' => date('Y-m-01', strtotime("+1 month", strtotime($periode))),
':id_etablissement' => $this->id
]); ]);


$result = $command->queryOne(); $result = $command->queryOne();
return $ca; return $ca;
} }


public function getMontantFacturer($periode = '', $ca = 0, $format = false) {
/**
* Retourne le montant à facturer pour une période donnée.
*
* @param string $periode
* @param float $ca
* @param boolean $format
* @return string
*/
public function getMontantFacturer($periode = '', $ca = 0, $format = false)
{
if (!$periode) if (!$periode)
$periode = date('Y-m'); $periode = date('Y-m');


} }
} }


public function getFacture($periode = '') {
/**
* Retourne la facture d'une période donnée.
*
* @param string $periode
* @return Facture
*/
public function getFacture($periode = '')
{
if (!$periode) if (!$periode)
$periode = date('Y-m', strtotime('-1 month')); $periode = date('Y-m', strtotime('-1 month'));


return $facture; return $facture;
} }


public function factureMoisDernier() {
/**
* Retourne la facture du mois dernier.
*
* @return Facture
*/
public function factureMoisDernier()
{
return $this->getFacture(date('Y-m', strtotime('-1 month'))); return $this->getFacture(date('Y-m', strtotime('-1 month')));
} }


public static function getConfig($config = '', $id_etablissement = 0) {
/**
* Retourne une configuration d'un établissement donné.
*
* @param string $config
* @param integer $id_etablissement
* @return mixed
*/
public static function getConfig($config = '', $id_etablissement = 0)
{
if (strlen($config)) { if (strlen($config)) {
if (!$id_etablissement)
if (!$id_etablissement) {
$id_etablissement = Yii::$app->user->identity->id_etablissement; $id_etablissement = Yii::$app->user->identity->id_etablissement;

}
$etablissement = self::findOne($id_etablissement); $etablissement = self::findOne($id_etablissement);
if ($etablissement) { if ($etablissement) {
return $etablissement->$config; return $etablissement->$config;
return false; return false;
} }


public function getPrixLibre() {
/**
* Retourne le montant de l'abonnement à prix libre définit par
* l'établissement
*
* @param boolean $format
* @return mixed
*/
public function getPrixLibre($format = true)
{
if (!is_null($this->prix_libre)) { if (!is_null($this->prix_libre)) {
return number_format($this->prix_libre, 2, ',', false) . ' € HT';
if($format) {
return number_format($this->prix_libre, 2, ',', false) . ' € HT';
}
else {
return $this->prix_libre;
}
} }
} }
public static function addUser($id_user, $id_producer) {
/**
* Lie un utilisateur à un producteur.
*
* @param integer $id_user
* @param integer $id_producer
* @return UserProducer
*/
public static function addUser($id_user, $id_producer)
{
$user_producer = UserEtablissement::find() $user_producer = UserEtablissement::find()
->where([ ->where([
'id_user' => $id_user, 'id_user' => $id_user,

+ 21
- 6
common/models/Facture.php View File

* @property string $date_paiement * @property string $date_paiement
* @property string $methode_paiement * @property string $methode_paiement
*/ */
class Facture extends \yii\db\ActiveRecord {
class Facture extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'facture'; return 'facture';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_etablissement', 'paye'], 'integer'], [['id_etablissement', 'paye'], 'integer'],
[['date', 'date_paiement'], 'safe'], [['date', 'date_paiement'], 'safe'],
]; ];
} }


public function getEtablissement() {
/*
* Relations
*/
public function getEtablissement()
{
return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']); return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_etablissement' => 'Id Etablissement', 'id_etablissement' => 'Id Etablissement',
]; ];
} }


public static function getLastFacture() {
/**
* Retourne la dernière facture émise.
*
* @return Facture
*/
public static function getLastFacture()
{
return Facture::find() return Facture::find()
->orderBy('reference DESC') ->orderBy('reference DESC')
->one(); ->one();

+ 17
- 7
common/models/LoginForm.php View File

/** /**
* Login form * Login form
*/ */
class LoginForm extends Model {
class LoginForm extends Model
{


public $username; public $username;
public $password; public $password;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [


['email', 'filter', 'filter' => 'trim'], ['email', 'filter', 'filter' => 'trim'],
* @param string $attribute the attribute currently being validated * @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule * @param array $params the additional name-value pairs given in the rule
*/ */
public function validatePassword($attribute, $params) {
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$user = $this->getUser(); $user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) { if (!$user || !$user->validatePassword($this->password)) {
* *
* @return boolean whether the user is logged in successfully * @return boolean whether the user is logged in successfully
*/ */
public function login() {
public function login()
{
if ($this->validate()) { if ($this->validate()) {
$this->updateDerniereConnexion(); $this->updateDerniereConnexion();
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
* *
* @return User|null * @return User|null
*/ */
public function getUser() {
public function getUser()
{
if ($this->_user === false) { if ($this->_user === false) {
$this->_user = User::findByEmail($this->email); $this->_user = User::findByEmail($this->email);
} }
return $this->_user; return $this->_user;
} }


public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'username' => 'Identifiant', 'username' => 'Identifiant',
]; ];
} }


public function updateDerniereConnexion() {
/**
* Met à jour la date de dernière connexion de l'utilisateur.
*/
public function updateDerniereConnexion()
{
$user = $this->getUser(); $user = $this->getUser();
$user->date_derniere_connexion = date('Y-m-d H:i:s'); $user->date_derniere_connexion = date('Y-m-d H:i:s');
$user->save(); $user->save();

+ 88
- 35
common/models/PointVente.php View File

* @property string $adresse * @property string $adresse
* @property integer $id_boulangerie * @property integer $id_boulangerie
*/ */
class PointVente extends \yii\db\ActiveRecord {
class PointVente extends \yii\db\ActiveRecord
{
var $commandes = []; var $commandes = [];
var $recettes = 0; var $recettes = 0;
var $recettes_pain = 0; var $recettes_pain = 0;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'point_vente'; return 'point_vente';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['nom'], 'required'], [['nom'], 'required'],
[['acces_restreint'], 'boolean'], [['acces_restreint'], 'boolean'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'nom' => 'Nom', 'nom' => 'Nom',
]; ];
} }


public function getPointVenteUser() {
/*
* Relations
*/
public function getPointVenteUser()
{
return $this->hasMany(PointVenteUser::className(), ['id_point_vente' => 'id']); return $this->hasMany(PointVenteUser::className(), ['id_point_vente' => 'id']);
} }


public function getProductionPointVente() {
public function getProductionPointVente()
{
return $this->hasMany(ProductionPointVente::className(), ['id_point_vente' => 'id']); return $this->hasMany(ProductionPointVente::className(), ['id_point_vente' => 'id']);
} }


public function initCommandes($commandes) {

/**
* Initialise les commandes liées au point de vente.
*
* @param array $commandes
*/
public function initCommandes($commandes)
{
$this->commandes = []; $this->commandes = [];
$this->recettes = 0; $this->recettes = 0;
$this->recettes_pain = 0; $this->recettes_pain = 0;
} }
} }


public function getCommandes() {
/**
* Retourne les commandes liées à ce point de vente.
*
* @return array
*/
public function getCommandes()
{
return $this->commandes; return $this->commandes;
} }

public function strListeVrac() {

$str = '';
$produits = Produit::find()->orderBy('order ASC')->all();

foreach ($produits as $p) {
if ($p->vrac) {
$quantite = Commande::getQuantiteProduit($p->id, $this->commandes);
if ($quantite) {
$str .= $quantite . ' ' . Html::encode($p->diminutif) . ', ';
}
}
}

return substr($str, 0, strlen($str) - 2);
}

public function save($runValidation = true, $attributeNames = NULL) {
/**
* Enregistre le point de vente.
*
* @param boolean $runValidation
* @param array $attributeNames
* @return type
*/
public function save($runValidation = true, $attributeNames = NULL)
{
$this->id_etablissement = Yii::$app->user->identity->id_etablissement; $this->id_etablissement = Yii::$app->user->identity->id_etablissement;
$this->pain = 1; $this->pain = 1;
return parent::save($runValidation, $attributeNames); return parent::save($runValidation, $attributeNames);
} }


public function gestionPointFabrication() {
/**
* Traite la mise à jour de l'attribut 'point_fabrication'.
*/
public function gestionPointFabrication()
{
if ($this->point_fabrication) { if ($this->point_fabrication) {
PointVente::updateAll( PointVente::updateAll(
['point_fabrication' => 0], ['id_etablissement' => $this->id_etablissement] ['point_fabrication' => 0], ['id_etablissement' => $this->id_etablissement]
} }
} }


public function gestionAccesRestreint() {
/**
* Traite les accès restreints d'un point de vente.
*/
public function gestionAccesRestreint()
{
PointVenteUser::deleteAll(['id_point_vente' => $this->id]); PointVenteUser::deleteAll(['id_point_vente' => $this->id]);


if (is_array($this->users) && count($this->users)) { if (is_array($this->users) && count($this->users)) {
$point_vente_user = new PointVenteUser; $point_vente_user = new PointVenteUser;
$point_vente_user->id_user = $val; $point_vente_user->id_user = $val;
$point_vente_user->id_point_vente = $this->id; $point_vente_user->id_point_vente = $this->id;
if (isset($this->users_commentaire[$val]) && strlen($this->users_commentaire[$val]))
if (isset($this->users_commentaire[$val]) && strlen($this->users_commentaire[$val])) {
$point_vente_user->commentaire = $this->users_commentaire[$val]; $point_vente_user->commentaire = $this->users_commentaire[$val];
}
$point_vente_user->save(); $point_vente_user->save();
} }
} }
} }
} }


public function getCommentaire() {
/**
* Retourne le commentaire de l'utilisateur courant lié au point de vente.
*
* @return string|null
*/
public function getCommentaire()
{
if (isset($this->pointVenteUser)) { if (isset($this->pointVenteUser)) {
foreach ($this->pointVenteUser as $pvu) { foreach ($this->pointVenteUser as $pvu) {
if ($pvu->id_user == Yii::$app->user->identity->id) { if ($pvu->id_user == Yii::$app->user->identity->id) {
} }
} }
} }
return null ;
} }


public static function count() {
/**
* Retourne le nombre de points de vente pour l'établissement courant.
*
* @return integer
*/
public static function count()
{
return PointVente::find() return PointVente::find()
->where([ ->where([
'id_etablissement' => Yii::$app->user->identity->id_etablissement 'id_etablissement' => Yii::$app->user->identity->id_etablissement
->count(); ->count();
} }


public function verifCode($code) {
/**
* Vérifie le code d'accès à un point de vente.
*
* @param string $code
* @return boolean
*/
public function verifCode($code)
{
if (strlen($this->code)) { if (strlen($this->code)) {
if (trim(strtolower($code)) == trim(strtolower($this->code))) { if (trim(strtolower($code)) == trim(strtolower($this->code))) {
return true; return true;
} }
} }
/**
* Retourne les jours de livraison du point de vente sous forme d'une chaine
* de caractères.
*
* @return string
*/
public function strJoursLivraison() { public function strJoursLivraison() {
$str = '' ; $str = '' ;
if($this->livraison_lundi) $str .= 'lundi, ' ; if($this->livraison_lundi) $str .= 'lundi, ' ;
return '' ; return '' ;
} }
/**
* Retourne un commentaire informant l'utilisateur sur les détails de
* livraison d'un point de vente et pour un jour donné.
*
* @param string $jour
* @return string
*/
public function strInfos($jour) { public function strInfos($jour) {
$str = '' ; $str = '' ;
$champs = 'horaires_'.$jour ; $champs = 'horaires_'.$jour ;

+ 8
- 4
common/models/PointVenteUser.php View File

* @property integer $id_point_vente * @property integer $id_point_vente
* @property integer $id_user * @property integer $id_user
*/ */
class PointVenteUser extends \yii\db\ActiveRecord {
class PointVenteUser extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'point_vente_user'; return 'point_vente_user';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_point_vente', 'id_user'], 'required'], [['id_point_vente', 'id_user'], 'required'],
[['id_point_vente', 'id_user'], 'integer'], [['id_point_vente', 'id_user'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_point_vente' => 'Id Point Vente', 'id_point_vente' => 'Id Point Vente',
'id_user' => 'Id User', 'id_user' => 'Id User',

+ 44
- 16
common/models/Production.php View File



use Yii; use Yii;
use common\models\Commande; use common\models\Commande;
use common\models\Production;


/** /**
* This is the model class for table "production". * This is the model class for table "production".
* @property string $date * @property string $date
* @property integer $actif * @property integer $actif
*/ */
class Production extends \yii\db\ActiveRecord {
class Production extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'production'; return 'production';
} }


public function getEtablissement() {
public function getEtablissement()
{
return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']); return $this->hasOne(Etablissement::className(), ['id' => 'id_etablissement']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['date'], 'required'], [['date'], 'required'],
[['date'], 'safe'], [['date'], 'safe'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'date' => 'Date', 'date' => 'Date',
]; ];
} }


public function getCommande() {
/*
* Relations
*/
public function getCommande()
{
return $this->hasMany(Commande::className(), ['id_production' => 'id']); return $this->hasMany(Commande::className(), ['id_production' => 'id']);
} }


public function getProductionProduit() {
public function getProductionProduit()
{
return $this->hasMany(ProductionProduit::className(), ['id_production' => 'id']); return $this->hasMany(ProductionProduit::className(), ['id_production' => 'id']);
} }


public function produitActif($id_produit) {
/**
* Retourne si un produit est actif ou non.
*
* @param integer $id_produit
* @return boolean
*/
public function produitActif($id_produit)
{
if ($id_produit && if ($id_produit &&
isset($this->productionProduit) &&
count($this->productionProduit) > 0) {
isset($this->productionProduit) &&
count($this->productionProduit) > 0)
{


foreach ($this->productionProduit as $production_produit) { foreach ($this->productionProduit as $production_produit) {
if ($production_produit['id_produit'] == $id_produit && if ($production_produit['id_produit'] == $id_produit &&
$production_produit['actif']) {
$production_produit['actif'])
{
return true; return true;
} }
} }
return false; return false;
} }
public static function initProduction($date) {
/**
* Initialise un jour de production.
*
* @param string $date
* @return Production
*/
public static function initProduction($date)
{
$production = null ; $production = null ;
if ($date != '') { if ($date != '') {
$production = Production::find() $production = Production::find()
// production_point_vente à définir s'ils ne sont pas initialisés // production_point_vente à définir s'ils ne sont pas initialisés
if ($production) { if ($production) {
$count_productions_point_vente = ProductionPointVente::find()-> $count_productions_point_vente = ProductionPointVente::find()->
where([
'id_production' => $production->id
])
->count();
where([
'id_production' => $production->id
])
->count();


if (!$count_productions_point_vente) { if (!$count_productions_point_vente) {
ProductionPointVente::setAll($production->id, true); ProductionPointVente::setAll($production->id, true);

+ 25
- 7
common/models/ProductionPointVente.php View File

* @property integer $id_point_vente * @property integer $id_point_vente
* @property integer $livraison * @property integer $livraison
*/ */
class ProductionPointVente extends \yii\db\ActiveRecord {
class ProductionPointVente extends \yii\db\ActiveRecord
{


var $productions_point_vente; var $productions_point_vente;


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'production_point_vente'; return 'production_point_vente';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_production', 'id_point_vente'], 'required'], [['id_production', 'id_point_vente'], 'required'],
[['id_production', 'id_point_vente', 'livraison'], 'integer'], [['id_production', 'id_point_vente', 'livraison'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_production' => 'Id Production', 'id_production' => 'Id Production',
'id_point_vente' => 'Id Point Vente', 'id_point_vente' => 'Id Point Vente',
]; ];
} }


public function getProduction() {
/*
* Relations
*/
public function getProduction()
{
return $this->hasOne(Production::className(), ['id' => 'id_production']); return $this->hasOne(Production::className(), ['id' => 'id_production']);
} }


public function getPointVente() {
public function getPointVente()
{
return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente']); return $this->hasOne(PointVente::className(), ['id' => 'id_point_vente']);
} }


public static function setAll($id_production, $bool_livraison) {
/**
* Définit les jours de livraisons des points de vente pour un jour de
* production donné.
*
* @param integer $id_production
* @param boolean $bool_livraison
*/
public static function setAll($id_production, $bool_livraison)
{
$count_productions_point_vente = self::find()-> $count_productions_point_vente = self::find()->
where([ where([
'id_production' => $id_production 'id_production' => $id_production

+ 20
- 5
common/models/ProductionProduit.php View File

* @property integer $id_produit * @property integer $id_produit
* @property integer $actif * @property integer $actif
*/ */
class ProductionProduit extends \yii\db\ActiveRecord {
class ProductionProduit extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'production_produit'; return 'production_produit';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_production', 'id_produit', 'actif', 'quantite_max'], 'integer'] [['id_production', 'id_produit', 'actif', 'quantite_max'], 'integer']
]; ];
} }


public function getProduit() {
/*
* Relations
*/
public function getProduit()
{
return $this->hasOne(Produit::className(), ['id' => 'id_produit']); return $this->hasOne(Produit::className(), ['id' => 'id_produit']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'id_production' => 'Id Production', 'id_production' => 'Id Production',
]; ];
} }


/**
* Recherche les enregistrement ProductionProduit liés à une production.
*
* @param integer $id_production
* @return array
*/
public static function findProduits($id_production) { public static function findProduits($id_production) {


$production_produits = ProductionProduit::find() $production_produits = ProductionProduit::find()

+ 52
- 10
common/models/Produit.php View File

* @property double $poids * @property double $poids
* @property string $recette * @property string $recette
*/ */
class Produit extends \yii\db\ActiveRecord {
class Produit extends \yii\db\ActiveRecord
{


var $total = 0; var $total = 0;


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'produit'; return 'produit';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['nom', 'id_etablissement'], 'required'], [['nom', 'id_etablissement'], 'required'],
[['actif', 'order', 'quantite_max', 'id_etablissement'], 'integer'], [['actif', 'order', 'quantite_max', 'id_etablissement'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'nom' => 'Nom', 'nom' => 'Nom',
]; ];
} }


public function getDescription() {
/**
* Retourne la description du produit.
*
* @return string
*/
public function getDescription()
{
$description = $this->description; $description = $this->description;
if (isset($this->poids) && is_numeric($this->poids) && $this->poids > 0) { if (isset($this->poids) && is_numeric($this->poids) && $this->poids > 0) {
if ($this->poids >= 1000) { if ($this->poids >= 1000) {
return $description; return $description;
} }


public function getLibelleAdmin() {
/**
* Retourne le libellé (admin) du produit.
* @return type
*/
public function getLibelleAdmin()
{
return $this->nom; return $this->nom;
} }


public function save($runValidation = true, $attributeNames = NULL) {
/**
* Enregistre le produit.
*
* @param boolean $runValidation
* @param array $attributeNames
* @return boolean
*/
public function save($runValidation = true, $attributeNames = NULL)
{
$this->id_etablissement = Yii::$app->user->identity->id_etablissement; $this->id_etablissement = Yii::$app->user->identity->id_etablissement;
return parent::save($runValidation, $attributeNames); return parent::save($runValidation, $attributeNames);
} }


public function getAll() {
/**
* Retourne les produits de l'établissement courant.
*
* @return array
*/
public function getAll()
{
return Produit::find() return Produit::find()
->where([ ->where([
'id_etablissement' => Yii::$app->user->identity->id_etablissement, 'id_etablissement' => Yii::$app->user->identity->id_etablissement,
->all(); ->all();
} }


public function getByProduction($id_production) {
/**
* Retourne les produits d'une production donnée.
*
* @param integer $id_production
* @return array
*/
public function getByProduction($id_production)
{
return Produit::find() return Produit::find()
->leftJoin('production_produit', 'produit.id = production_produit.id_produit') ->leftJoin('production_produit', 'produit.id = production_produit.id_produit')
->where([ ->where([
->all(); ->all();
} }


public static function count() {
/**
* Retourne le nombre de produits du producteur courant.
*
* @return integer
*/
public static function count()
{
return Produit::find() return Produit::find()
->where([ ->where([
'id_etablissement' => Yii::$app->user->identity->id_etablissement 'id_etablissement' => Yii::$app->user->identity->id_etablissement

+ 154
- 68
common/models/User.php View File

namespace common\models; namespace common\models;


use yii\web\IdentityInterface; use yii\web\IdentityInterface;
use yii\db\Query ;


/** /**
* User model * User model
* @property string $password write-only password * @property string $password write-only password
* @property boolean $confiance * @property boolean $confiance
*/ */
class User extends ActiveRecord implements IdentityInterface {
class User extends ActiveRecord implements IdentityInterface
{


const STATUS_DELETED = 0; const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10; const STATUS_ACTIVE = 10;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return '{{%user}}'; return '{{%user}}';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function behaviors() {
public function behaviors()
{
return [ return [
TimestampBehavior::className(), TimestampBehavior::className(),
]; ];
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['confiance', 'default', 'value' => 1], ['confiance', 'default', 'value' => 1],
[['no_mail', 'mail_prod_lundi', 'mail_prod_mardi', 'mail_prod_mercredi', 'mail_prod_jeudi', 'mail_prod_vendredi', 'mail_prod_samedi', 'mail_prod_dimanche'], 'boolean'], [['no_mail', 'mail_prod_lundi', 'mail_prod_mardi', 'mail_prod_mercredi', 'mail_prod_jeudi', 'mail_prod_vendredi', 'mail_prod_samedi', 'mail_prod_dimanche'], 'boolean'],
]; ];
} }


public function verifyPasswordOld($attribute, $params) {
/**
* Vérifie le mot de passe envoyé par l'utilisateur.
*
* @param string $attribute
* @param array $params
*/
public function verifyPasswordOld($attribute, $params)
{
if (strlen($this->password_old)) { if (strlen($this->password_old)) {
if (!$this->validatePassword($this->password_old)) { if (!$this->validatePassword($this->password_old)) {
$this->addError($attribute, 'Mot de passe invalide.'); $this->addError($attribute, 'Mot de passe invalide.');
} }
} }


public function verifyPasswordNew($attribute, $params) {
/**
* Vérifie le mot de passe de l'utilisateur.
*
* @param string $attribute
* @param array $params
*/
public function verifyPasswordNew($attribute, $params)
{
if (strlen($this->password_new) < 6) { if (strlen($this->password_new) < 6) {
$this->addError($attribute, 'Votre mot de passe doit comporter au moins 6 caractères.'); $this->addError($attribute, 'Votre mot de passe doit comporter au moins 6 caractères.');
} }
} }


public function verifyPasswordNewConfirm($attribute, $params) {
/**
* Vérifie la confirmation de mot de passe de l'utilisateur.
*
* @param string $attribute
* @param array $params
*/
public function verifyPasswordNewConfirm($attribute, $params)
{
if ($this->password_new != $this->password_new_confirm) { if ($this->password_new != $this->password_new_confirm) {
$this->addError($attribute, 'Les deux mots de passe doivent être identiques'); $this->addError($attribute, 'Les deux mots de passe doivent être identiques');
} }
} }


public function verifyEmail($attribute, $params) {
/**
* Vérifie l'email de l'utilisateur.
*
* @param string $attribute
* @param array $params
*/
public function verifyEmail($attribute, $params)
{
$user = User::find()->where("email LIKE :email AND id != :id")->params(array(':email' => '%' . $this->email . '%', ':id' => $this->id))->one(); $user = User::find()->where("email LIKE :email AND id != :id")->params(array(':email' => '%' . $this->email . '%', ':id' => $this->id))->one();


if ($user) if ($user)
$this->addError($attribute, 'Cette adresse email est déjà utilisée par un autre utilisateur '); $this->addError($attribute, 'Cette adresse email est déjà utilisée par un autre utilisateur ');
} }


public function getUserEtablissement() {
/*
* Relations
*/
public function getUserEtablissement()
{
return $this->hasMany(UserEtablissement::className(), ['id_user' => 'id']); return $this->hasMany(UserEtablissement::className(), ['id_user' => 'id']);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function findIdentity($id) {
public static function findIdentity($id)
{
return static::findOne(['id' => $id/* , 'status' => self::STATUS_ACTIVE */]); return static::findOne(['id' => $id/* , 'status' => self::STATUS_ACTIVE */]);
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function findIdentityByAccessToken($token, $type = null) {
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
} }


* @param string $username * @param string $username
* @return static|null * @return static|null
*/ */
public static function findByUsername($username) {
return static::findOne(['username' => $username/* , 'status' => self::STATUS_ACTIVE */]);
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
} }


public static function findByEmail($email) {
return static::findOne(['email' => $email /* , 'status' => self::STATUS_ACTIVE */]);
/**
* Recherche un utilisateur via son adresse email.
*
* @param string $email
* @return User
*/
public static function findByEmail($email)
{
return static::findOne(['email' => $email]);
} }


/** /**
* @param string $token password reset token * @param string $token password reset token
* @return static|null * @return static|null
*/ */
public static function findByPasswordResetToken($token) {
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) { if (!static::isPasswordResetTokenValid($token)) {
return null; return null;
} }
]); ]);
} }


public static function findBy($params = []) {
/**
* Recherche des utilisateurs suivant les paramètres : id_etablissement,
* inactifs, id_point_vente, nom, prenom, email, telephone.
*
* @param array $params
* @return Query
*/
public static function findBy($params = [])
{
if (!isset($params['id_etablissement'])) if (!isset($params['id_etablissement']))
$params['id_etablissement'] = Yii::$app->user->identity->id_etablissement; $params['id_etablissement'] = Yii::$app->user->identity->id_etablissement;
$query = (new \yii\db\Query())
$query = (new Query())
->select(['user.id AS user_id', 'user.prenom', 'user.nom', 'user.telephone', 'user.email', 'user.created_at', 'user.date_derniere_connexion', 'user_etablissement.*']) ->select(['user.id AS user_id', 'user.prenom', 'user.nom', 'user.telephone', 'user.email', 'user.created_at', 'user.date_derniere_connexion', 'user_etablissement.*'])
->from('user'); ->from('user');
->groupBy('user.id'); ->groupBy('user.id');
} }
if (isset($params['nom']))
if (isset($params['nom'])) {
$query->andFilterWhere(['like', 'nom', $params['nom']]); $query->andFilterWhere(['like', 'nom', $params['nom']]);
if (isset($params['prenom']))
}
if (isset($params['prenom'])) {
$query->andFilterWhere(['like', 'prenom', $params['prenom']]); $query->andFilterWhere(['like', 'prenom', $params['prenom']]);
if (isset($params['email']))
}
if (isset($params['email'])) {
$query->andFilterWhere(['like', 'email', $params['email']]); $query->andFilterWhere(['like', 'email', $params['email']]);
if (isset($params['telephone']))
}
if (isset($params['telephone'])) {
$query->andFilterWhere(['like', 'telephone', $params['telephone']]); $query->andFilterWhere(['like', 'telephone', $params['telephone']]);

}
return $query; return $query;
} }


* @param string $token password reset token * @param string $token password reset token
* @return boolean * @return boolean
*/ */
public static function isPasswordResetTokenValid($token) {
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) { if (empty($token)) {
return false; return false;
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getId() {
public function getId()
{
return $this->getPrimaryKey(); return $this->getPrimaryKey();
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function getAuthKey() {
public function getAuthKey()
{
return $this->auth_key; return $this->auth_key;
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function validateAuthKey($authKey) {
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey; return $this->getAuthKey() === $authKey;
} }


* @param string $password password to validate * @param string $password password to validate
* @return boolean if password provided is valid for current user * @return boolean if password provided is valid for current user
*/ */
public function validatePassword($password) {
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash); return Yii::$app->security->validatePassword($password, $this->password_hash);
} }


* *
* @param string $password * @param string $password
*/ */
public function setPassword($password) {
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password); $this->password_hash = Yii::$app->security->generatePasswordHash($password);
} }


/** /**
* Generates "remember me" authentication key * Generates "remember me" authentication key
*/ */
public function generateAuthKey() {
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString(); $this->auth_key = Yii::$app->security->generateRandomString();
} }


/** /**
* Generates new password reset token * Generates new password reset token
*/ */
public function generatePasswordResetToken() {
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time(); $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
} }


/** /**
* Removes password reset token * Removes password reset token
*/ */
public function removePasswordResetToken() {
public function removePasswordResetToken()
{
$this->password_reset_token = null; $this->password_reset_token = null;
} }


public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id' => 'ID', 'id' => 'ID',
'username' => 'Identifiant', 'username' => 'Identifiant',
]; ];
} }


public function isBoulanger() {
/**
* Retourne si l'utilisateur est un boulanger ou non.
*
* @return boolean
*/
public function isBoulanger()
{
return ($this->status == User::STATUS_ADMIN || $this->status == User::STATUS_BOULANGER) && $this->id_etablissement; return ($this->status == User::STATUS_ADMIN || $this->status == User::STATUS_BOULANGER) && $this->id_etablissement;
} }


public function getNomMagasin() {
/**
* Retourne le nom du producteur.
*
* @return string
*/
public function getNomMagasin()
{
$etablissement = Etablissement::findOne($this->id_etablissement); $etablissement = Etablissement::findOne($this->id_etablissement);
return $etablissement->nom; return $etablissement->nom;
} }


public function getEtablissementsFavoris() {
/**
* Retourne les établissements liés à l'utilisateur.
*
* @return array
*/
public function getEtablissementsFavoris()
{
$etabs = (new \yii\db\Query()) $etabs = (new \yii\db\Query())
->select('*') ->select('*')
->from(['user_etablissement', 'etablissement']) ->from(['user_etablissement', 'etablissement'])
return $etabs; return $etabs;
} }


public function etatPaiementEtablissement() {
$etablissement = Etablissement::findOne($this->id_etablissement);

if ($etablissement) {
return $etablissement->etatPaiement();
}
}

public function periodeEssai() {
$etablissement = Etablissement::findOne($this->id_etablissement);

if ($etablissement) {
$date_limite = strtotime($etablissement->date_creation) + 30 * 24 * 60 * 60;
$date = time();

if ($date < $date_limite) {
$date = $date_limite - $date;
return (int) ($date / (24 * 60 * 60));
} else {
return 0;
}
}
}

public function getCredit($id_etablissement) {
/**
* Retourne le crédit de l'utilisateur pour un producteur donné.
*
* @param integer $id_etablissement
* @return float
*/
public function getCredit($id_etablissement)
{
$user_etablissement = UserEtablissement::find() $user_etablissement = UserEtablissement::find()
->where([
'id_user' => $this->id,
'id_etablissement' => $id_etablissement
])
->one();
->where([
'id_user' => $this->id,
'id_etablissement' => $id_etablissement
])
->one();


if ($user_etablissement) { if ($user_etablissement) {
return $user_etablissement->credit; return $user_etablissement->credit;
return 0; return 0;
} }


public function updateDerniereConnexion() {
/**
* Met à jour la date de dernière connexion de l'utilisateur.
*/
public function updateDerniereConnexion()
{
$this->date_derniere_connexion = date('Y-m-d H:i:s'); $this->date_derniere_connexion = date('Y-m-d H:i:s');
$this->save(); $this->save();
} }
public function sendMailWelcome($password) {
/**
* Envoie un email de bienvenue à l'utilisateur lors de son inscription
* via le backend du site.
*
* @param string $password
*/
public function sendMailWelcome($password)
{
if (strlen($this->email)) { if (strlen($this->email)) {
$etablissement = Etablissement::findOne(Yii::$app->user->identity->id_etablissement); $etablissement = Etablissement::findOne(Yii::$app->user->identity->id_etablissement);
Yii::$app->mailer->compose(); Yii::$app->mailer->compose();

+ 8
- 4
common/models/UserEtablissement.php View File

* @property boolean $actif * @property boolean $actif
* @property boolean $favoris * @property boolean $favoris
*/ */
class UserEtablissement extends \yii\db\ActiveRecord {
class UserEtablissement extends \yii\db\ActiveRecord
{


/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() {
public static function tableName()
{
return 'user_etablissement'; return 'user_etablissement';
} }


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
[['id_user', 'id_etablissement'], 'required'], [['id_user', 'id_etablissement'], 'required'],
[['id_user', 'id_etablissement'], 'integer'], [['id_user', 'id_etablissement'], 'integer'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_user' => 'Id User', 'id_user' => 'Id User',
'id_etablissement' => 'Id Etablissement', 'id_etablissement' => 'Id Etablissement',

+ 8
- 4
frontend/models/AddEtablissementForm.php View File

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


public $id_etablissement; public $id_etablissement;
public $code; public $code;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['id_etablissement', 'integer'], ['id_etablissement', 'integer'],
['id_etablissement', 'required'], ['id_etablissement', 'required'],
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_etablissement' => 'Établissement', 'id_etablissement' => 'Établissement',
'code' => 'Code', 'code' => 'Code',
* @param string $email the target email address * @param string $email the target email address
* @return boolean whether the email was sent * @return boolean whether the email was sent
*/ */
public function add() {
public function add()
{
$etablissement = Etablissement::findOne($this->id_etablissement); $etablissement = Etablissement::findOne($this->id_etablissement);


$user_etablissement_exist = UserEtablissement::find() $user_etablissement_exist = UserEtablissement::find()

+ 6
- 3
frontend/models/PasswordResetRequestForm.php View File

/** /**
* Password reset request form * Password reset request form
*/ */
class PasswordResetRequestForm extends Model {
class PasswordResetRequestForm extends Model
{


public $email; public $email;


/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['email', 'filter', 'filter' => 'trim'], ['email', 'filter', 'filter' => 'trim'],
['email', 'required'], ['email', 'required'],
* *
* @return boolean whether the email was send * @return boolean whether the email was send
*/ */
public function sendEmail() {
public function sendEmail()
{
/* @var $user User */ /* @var $user User */
$user = User::findOne([ $user = User::findOne([
'email' => $this->email, 'email' => $this->email,

+ 6
- 3
frontend/models/ProducerCodeForm.php View File

/** /**
* Producer Code form * Producer Code form
*/ */
class ProducerCodeForm extends Model {
class ProducerCodeForm extends Model
{


public $id_producer ; public $id_producer ;
public $code; public $code;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['id_producer','required','message' => 'Champs obligatoire'], ['id_producer','required','message' => 'Champs obligatoire'],
['id_producer', 'integer'], ['id_producer', 'integer'],
]; ];
} }


public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'id_producer' => 'Producteur', 'id_producer' => 'Producteur',
'code' => 'Code de l\'établissement', 'code' => 'Code de l\'établissement',

+ 10
- 5
frontend/models/ResetPasswordForm.php View File

/** /**
* Password reset form * Password reset form
*/ */
class ResetPasswordForm extends Model {
class ResetPasswordForm extends Model
{


public $password; public $password;


* @param array $config name-value pairs that will be used to initialize the object properties * @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid * @throws \yii\base\InvalidParamException if token is empty or not valid
*/ */
public function __construct($token, $config = []) {
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) { if (empty($token) || !is_string($token)) {
throw new InvalidParamException('Password reset token cannot be blank.'); throw new InvalidParamException('Password reset token cannot be blank.');
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['password', 'required'], ['password', 'required'],
['password', 'string', 'min' => 6], ['password', 'string', 'min' => 6],
* *
* @return boolean if password was reset. * @return boolean if password was reset.
*/ */
public function resetPassword() {
public function resetPassword()
{
$user = $this->_user; $user = $this->_user;
$user->setPassword($this->password); $user->setPassword($this->password);
$user->removePasswordResetToken(); $user->removePasswordResetToken();
return $user->save(); return $user->save();
} }


public function attributeLabels() {
public function attributeLabels()
{
return [ return [
'password' => 'Mot de passe', 'password' => 'Mot de passe',
]; ];

+ 27
- 23
frontend/models/SignupForm.php View File

/** /**
* Signup form * Signup form
*/ */
class SignupForm extends Model {
class SignupForm extends Model
{


public $username; public $username;
public $email; public $email;
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() {
public function rules()
{
return [ return [
['email', 'filter', 'filter' => 'trim'], ['email', 'filter', 'filter' => 'trim'],
['email', 'required', 'message' => 'Champs obligatoire'], ['email', 'required', 'message' => 'Champs obligatoire'],
['prix_libre', 'number'], ['prix_libre', 'number'],
]; ];
} }
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Identifiant',
'password' => 'Mot de passe',
'rememberMe' => 'Se souvenir de moi',
'prenom' => 'Prénom',
'telephone' => 'Téléphone',
'is_boulanger' => "Je suis professionnel et souhaite mettre en place un système de réservation dans mon établissement",
'nom_magasin' => 'Nom de l\'établissement',
'siret' => 'Numéro SIRET',
'code_postal' => 'Code postal',
'ville' => 'Commune',
'id_etablissement' => 'Producteur',
'type' => 'Type d\'établissement',
'prix_libre' => 'Prix libre'
];
}


/** /**
* Signs user up. * Signs user up.
* *
* @return User|null the saved model or null if saving fails * @return User|null the saved model or null if saving fails
*/ */
public function signup() {
public function signup()
{
if ($this->validate()) { if ($this->validate()) {
$user = new User(); $user = new User();
$user->username = $this->email; $user->username = $this->email;


return null; return null;
} }

public function attributeLabels() {
return [
'id' => 'ID',
'username' => 'Identifiant',
'password' => 'Mot de passe',
'rememberMe' => 'Se souvenir de moi',
'prenom' => 'Prénom',
'telephone' => 'Téléphone',
'is_boulanger' => "Je suis professionnel et souhaite mettre en place un système de réservation dans mon établissement",
'nom_magasin' => 'Nom de l\'établissement',
'siret' => 'Numéro SIRET',
'code_postal' => 'Code postal',
'ville' => 'Commune',
'id_etablissement' => 'Producteur',
'type' => 'Type d\'établissement',
'prix_libre' => 'Prix libre'
];
}

} }

Loading…
Cancel
Save