|
- <?php
-
-
-
- namespace common\models;
-
- use common\helpers\GlobalParam;
- use yii\web\IdentityInterface;
- use yii\db\Query;
- use common\components\ActiveRecordCommon;
-
-
- class User extends ActiveRecordCommon implements IdentityInterface
- {
-
- const TYPE_INDIVIDUAL = 'individual' ;
- const TYPE_LEGAL_PERSON = 'legal-person' ;
-
- const STATUS_DELETED = 0;
- const STATUS_ACTIVE = 10;
- const STATUS_PRODUCER = 11;
- const STATUS_ADMIN = 13;
-
- const ID_USER_SYSTEM = 0;
-
- var $password_old;
- var $password_new;
- var $password_new_confirm;
- var $points_sale = [];
- var $one_name ;
-
-
-
- public static function tableName()
- {
- return '{{%user}}';
- }
-
-
-
- public function behaviors()
- {
- return [
- TimestampBehavior::className(),
- ];
- }
-
-
-
- public function rules()
- {
- return [
- [['no_mail', 'mail_distribution_monday', 'mail_distribution_tuesday', 'mail_distribution_wednesday', 'mail_distribution_thursday', 'mail_distribution_friday', 'mail_distribution_saturday', 'mail_distribution_sunday', 'is_main_contact'], 'boolean'],
- [['lastname', 'name', 'phone', 'address', 'type', 'name_legal_person'], 'string'],
- ['lastname', 'verifyOneName', 'skipOnError' => false, 'skipOnEmpty' => false],
- ['email', 'email', 'message' => 'Cette adresse email n\'est pas valide'],
- ['email', 'verifyEmail'],
- ['status', 'default', 'value' => self::STATUS_ACTIVE],
- ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED, self::STATUS_ADMIN, self::STATUS_PRODUCER]],
- ['password_old', 'verifyPasswordOld'],
- ['password_new', 'verifyPasswordNew'],
- ['password_new_confirm', 'verifyPasswordNewConfirm'],
- [['date_last_connection', 'password_old', 'password_new', 'password_new_confirm', 'password_hash', 'points_sale'], 'safe'],
- ];
- }
-
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'name' => 'Prénom',
- 'lastname' => 'Nom',
- 'phone' => 'Téléphone',
- 'address' => 'Adresse',
- 'username' => 'Identifiant',
- 'password' => 'Mot de passe',
- 'rememberMe' => 'Se souvenir de moi',
- 'no_mail' => 'Ne pas recevoir d\'email de la part du Chat des Noisettes',
- 'mail_distribution_monday' => 'Lundi',
- 'mail_distribution_tuesday' => 'Mardi',
- 'mail_distribution_wednesday' => 'Mercredi',
- 'mail_distribution_thursday' => 'Jeudi',
- 'mail_distribution_friday' => 'Vendredi',
- 'mail_distribution_saturday' => 'Samedi',
- 'mail_distribution_sunday' => 'Dimanche',
- 'password_old' => 'Ancien mot de passe',
- 'password_new' => 'Nouveau mot de passe',
- 'password_new_confirm' => 'Confirmation du nouveau mot de passe',
- 'points_sale' => 'Points de vente',
- 'type' => 'Type',
- 'name_legal_person' => 'Libellé',
- 'is_main_contact' => 'Contact principal'
- ];
- }
-
-
-
- public static function defaultOptionsSearch()
- {
- return [
- 'with' => [],
- 'join_with' => ['userProducer'],
- 'orderby' => 'user.name ASC, user.lastname ASC',
- 'attribute_id_producer' => ''
- ];
- }
-
-
-
- public function verifyPasswordOld($attribute, $params)
- {
- if (strlen($this->password_old)) {
- if (!$this->validatePassword($this->password_old)) {
- $this->addError($attribute, 'Mot de passe invalide.');
- }
- }
-
- if (!strlen($this->password_old) && (strlen($this->password_new) || strlen($this->password_new_confirm))) {
- $this->addError($attribute, 'Ce champs ne peut être vide');
- }
-
- if (!strlen($this->password_new) && (strlen($this->password_old) || strlen($this->password_new_confirm))) {
- $this->addError('password_new', 'Ce champs ne peut être vide');
- }
-
- if (!strlen($this->password_new_confirm) && (strlen($this->password_old) || strlen($this->password_new))) {
- $this->addError('password_new_confirm', 'Ce champs ne peut être vide');
- }
- }
-
-
-
- public function verifyPasswordNew($attribute, $params)
- {
- if (strlen($this->password_new) < 6) {
- $this->addError($attribute, 'Votre mot de passe doit comporter au moins 6 caractères.');
- }
- }
-
-
-
- public function verifyPasswordNewConfirm($attribute, $params)
- {
- if ($this->password_new != $this->password_new_confirm) {
- $this->addError($attribute, 'Les deux mots de passe doivent être identiques');
- }
- }
-
-
-
- public function verifyEmail($attribute, $params)
- {
- if($this->id) {
- $user = User::find()->where("email LIKE :email AND id != :id")->params(array(':email' => '%' . $this->email . '%', ':id' => $this->id))->one();
- }
- else {
- $user = User::find()->where("email LIKE :email")->params(array(':email' => '%' . $this->email . '%'))->one();
- }
-
- if ($user) {
- $this->addError($attribute, 'Cette adresse email est déjà utilisée par un autre utilisateur ');
- }
- }
-
-
-
- public function verifyOneName($attribute, $params)
- {
- if(strlen($this->lastname) == 0 && strlen($this->name_legal_person) == 0) {
- $this->addError('lastname', 'Vous devez saisir au moins un nom.');
- $this->addError('name_legal_person', 'Vous devez saisir au moins un nom.');
- }
- }
-
-
-
-
- public function getUserProducer()
- {
- return $this->hasMany(UserProducer::className(), ['id_user' => 'id']);
- }
-
- public function getOrder()
- {
- return $this->hasMany(Order::className(), ['id_user' => 'id']);
- }
-
-
-
- public static function findIdentity($id)
- {
- return static::findOne(['id' => $id]);
- }
-
-
-
- public static function findIdentityByAccessToken($token, $type = null)
- {
- throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
- }
-
-
-
- public static function findByUsername($username)
- {
- return static::findOne(['username' => $username]);
- }
-
-
-
- public static function findByEmail($email)
- {
- return static::findOne(['email' => $email]);
- }
-
-
-
- public static function findByPasswordResetToken($token)
- {
- if (!static::isPasswordResetTokenValid($token)) {
- return null;
- }
-
- return static::findOne([
- 'password_reset_token' => $token,
- ]);
- }
-
-
-
- public static function findBy($params = [])
- {
- if (!isset($params['id_producer'])) {
- $params['id_producer'] = GlobalParam::getCurrentProducerId();
- }
-
- $query = (new Query())
- ->select(['user.id AS user_id', 'user.name', 'user.lastname', 'user.phone', 'user.email', 'user.created_at', 'user.date_last_connection', 'user_producer.*', 'user.address', 'user.name_legal_person'])
- ->from('user');
-
- $active = (isset($params['inactive']) && $params['inactive']) ? 0 : 1;
- $query->innerJoin('user_producer', 'user.id = user_producer.id_user AND user_producer.active = ' . $active . ' AND user_producer.id_producer = :id_producer', [':id_producer' => $params['id_producer']]);
-
- if (isset($params['id_point_sale']) && $params['id_point_sale']) {
- $point_sale = PointSale::findOne(['id' => $params['id_point_sale']]);
-
- $conditionLinkUserPointSale = 'user.id = user_point_sale.id_user AND user_point_sale.id_point_sale = :id_point_sale';
-
- $usersPointSaleLink = false;
- $usersPointSaleHasOrder = false;
-
- if (isset($params['users_point_sale_link']) && $params['users_point_sale_link']) {
- $usersPointSaleLink = true;
- } elseif (isset($params['users_point_sale_has_order']) && $params['users_point_sale_has_order']) {
- $usersPointSaleHasOrder = true;
- } elseif ($point_sale->restricted_access) {
- $usersPointSaleLink = true;
- } else {
- $usersPointSaleHasOrder = true;
- }
-
- if ($usersPointSaleLink) {
- $query->innerJoin('user_point_sale', 'user.id = user_point_sale.id_user AND user_point_sale.id_point_sale = :id_point_sale', [':id_point_sale' => $params['id_point_sale']]);
- } elseif ($usersPointSaleHasOrder) {
- $query->innerJoin(
- 'order',
- 'user.id = order.id_user AND order.id_point_sale = :id_point_sale',
- [':id_point_sale' => $params['id_point_sale']]
- )->groupBy('user.id');
- }
- }
-
- if (isset($params['subscribers']) && $params['subscribers']) {
- $query->innerJoin(
- 'subscription',
- 'user.id = subscription.id_user AND subscription.id_producer = :id_producer',
- [':id_producer' => GlobalParam::getCurrentProducerId()]
- )->groupBy('user.id');
- }
-
- if (isset($params['inactive']) && $params['inactive']) {
- $query->innerJoin(
- 'order',
- 'user.id = order.id_user'
- )
- ->groupBy('user.id');
- }
-
- if (isset($params['name'])) {
- $query->andFilterWhere(['like', 'name', $params['name']]);
- }
-
- if (isset($params['lastname'])) {
- $query->andFilterWhere(['like', 'lastname', $params['lastname']]);
- }
-
- if (isset($params['email'])) {
- $query->andFilterWhere(['like', 'email', $params['email']]);
- }
-
- if (isset($params['phone'])) {
- $query->andFilterWhere(['like', 'phone', $params['phone']]);
- }
-
- $query->orderBy('user.lastname ASC, user.name ASC');
-
- return $query;
- }
-
-
-
- public static function isPasswordResetTokenValid($token)
- {
- if (empty($token)) {
- return false;
- }
- $expire = Yii::$app->params['user.passwordResetTokenExpire'];
- $parts = explode('_', $token);
- $timestamp = (int)end($parts);
- return $timestamp + $expire >= time();
- }
-
-
-
- public function getId()
- {
- return $this->getPrimaryKey();
- }
-
-
-
- public function getAuthKey()
- {
- return $this->auth_key;
- }
-
-
-
- public function validateAuthKey($authKey)
- {
- return $this->getAuthKey() === $authKey;
- }
-
-
-
- public function validatePassword($password)
- {
- return Yii::$app->security->validatePassword($password, $this->password_hash);
- }
-
-
-
- public function setPassword($password)
- {
- $this->password_hash = Yii::$app->security->generatePasswordHash($password);
- }
-
-
-
- public function generateAuthKey()
- {
- $this->auth_key = Yii::$app->security->generateRandomString();
- }
-
-
-
- public function generatePasswordResetToken()
- {
- $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
- }
-
-
-
- public function removePasswordResetToken()
- {
- $this->password_reset_token = null;
- }
-
-
-
- public static function getCurrent()
- {
- if (!Yii::$app->user->isGuest) {
- return Yii::$app->user->identity;
- }
-
- return false;
- }
-
-
-
- public static function isCurrentConnected()
- {
- return !Yii::$app->user->isGuest;
- }
-
-
-
- public function isProducer()
- {
- return ($this->status == User::STATUS_ADMIN || $this->status == User::STATUS_PRODUCER) && $this->id_producer;
- }
-
-
-
- public static function isCurrentProducer()
- {
- $user = User::getCurrent();
- if ($user) {
- return $user->isProducer();
- }
- return false;
- }
-
-
-
- public function isAdmin()
- {
- return $this->status == User::STATUS_ADMIN;
- }
-
-
-
- public static function isCurrentAdmin()
- {
- $user = User::getCurrent();
- if ($user) {
- return $user->isAdmin();
- }
- return false;
- }
-
-
-
- public function getNameProducer()
- {
- $producer = Producer::findOne($this->id_producer);
- return $producer->name;
- }
-
-
-
- public function getBookmarkedProducers()
- {
- $producers = (new \yii\db\Query())
- ->select('*')
- ->from(['user_producer', 'producer'])
- ->where('user_producer.id_producer = producer.id')
- ->andWhere(['user_producer.id_user' => $this->id])
- ->andWhere(['user_producer.active' => 1])
- ->all();
-
- return $producers;
- }
-
-
-
- public function getCredit($idProducer)
- {
- $userProducer = UserProducer::searchOne([
- 'id_user' => $this->id
- ]);
-
- if ($userProducer) {
- return $userProducer->credit;
- }
-
- return 0;
- }
-
-
-
- public function getFavoritePointSale()
- {
- $arrayUserPointSale = UserPointSale::find()
- ->innerJoinWith('pointSale', true)
- ->where([
- 'user_point_sale.id_user' => $this->id,
- 'point_sale.id_producer' => GlobalParam::getCurrentProducerId()
- ])
- ->all();
-
- if (count($arrayUserPointSale) == 1) {
- $pointSale = PointSale::findOne(['id' => $arrayUserPointSale[0]->id_point_sale]);
- } else {
- $lastOrder = Order::find()->innerJoinWith('pointSale', true)->where([
- 'order.id_user' => $this->id,
- 'point_sale.id_producer' => GlobalParam::getCurrentProducerId()
- ])
- ->orderBy('order.id DESC')
- ->one();
-
- if ($lastOrder) {
- $pointSale = PointSale::findOne(['id' => $lastOrder->id_point_sale]);
- }
- }
-
- if (isset($pointSale)) {
- return $pointSale;
- }
-
- return false;
- }
-
-
-
- public function updateLastConnection()
- {
- $this->date_last_connection = date('Y-m-d H:i:s');
- $this->save();
- }
-
-
-
- public function sendMailWelcome($password)
- {
- if (strlen($this->email)) {
- $producer = Producer::findOne(GlobalParam::getCurrentProducerId());
- Yii::$app->mailer->compose();
- $mail = Yii::$app->mailer->compose(
- ['html' => 'createUserAdmin-html', 'text' => 'createUserAdmin-text'], ['user' => $this, 'producer' => $producer, 'password' => $password]
- )
- ->setTo($this->email)
- ->setFrom(['contact@opendistrib.net' => 'distrib'])
- ->setSubject('[distrib] Inscription')
- ->send();
- }
- }
-
- public function getFullAddress($nl2br = false)
- {
- $address = '';
- if(isset($this->lastname) && isset($this->name) && strlen($this->lastname) && strlen($this->name)) {
- $address .= $this->lastname . ' ' . $this->name . "\n";
- }
- if(isset($this->name_legal_person) && strlen($this->name_legal_person)) {
- $address .= $this->name_legal_person. "\n";
- }
- $address .= $this->address;
-
- if($nl2br) {
- $address = nl2br($address) ;
- }
-
- return $address;
- }
-
- public function getUsername()
- {
- $username = '' ;
- if(isset($this->name_legal_person) && strlen($this->name_legal_person)) {
- $username = $this->name_legal_person ;
- }
- else {
- $username = $this->lastname.' '.$this->name ;
- }
-
- return $username ;
- }
-
-
-
- public static function getCurrentId()
- {
- if (!Yii::$app->user->isGuest) {
- return Yii::$app->user->identity->id;
- }
-
- return false;
- }
-
-
-
- public static function getCurrentStatus()
- {
- if (!Yii::$app->user->isGuest) {
- return Yii::$app->user->identity->status;
- }
-
- return false;
- }
-
- public static function hasAccessBackend()
- {
- return User::getCurrentStatus() == USER::STATUS_ADMIN || User::getCurrentStatus() == USER::STATUS_PRODUCER;
- }
-
-
- }
|