Exemplo n.º 1
0
 public function actionIndex()
 {
     $dependency = new CDbCacheDependency('SELECT COUNT(0) FROM {{referals_profit}} WHERE referer_id = :referer_id');
     $dependency->params = array('referer_id' => user()->getId());
     $model = ReferalsProfit::model()->cache(3600 * 24, $dependency, 2);
     $dataProvider = new CActiveDataProvider($model, array('criteria' => array('order' => 'created_at DESC'), 'pagination' => array('pageSize' => (int) config('cabinet.referals.limit'), 'pageVar' => 'page')));
     $this->render('//cabinet/referrals', array('dataProvider' => $dataProvider, 'countReferals' => Referals::model()->count('referer = :referer', array(':referer' => user()->getId()))));
 }
Exemplo n.º 2
0
 public function actionIndex()
 {
     if (isset($_REQUEST)) {
         Yii::import('application.modules.deposit.extensions.Deposit.Deposit');
         $deposit = new Deposit();
         if (!$deposit->init()) {
             app()->end();
         }
         try {
             /**
              * @var Transactions $transaction
              */
             $transaction = $deposit->processed();
             $percents = (double) config('referral_program.percent');
             Yii::log("Deposit::log\n" . print_r($_REQUEST, TRUE), CLogger::LEVEL_INFO, 'application.modules.deposit.controllers.DefaultController::' . __LINE__);
             // Начисляю партнёрку
             if ($percents > 0 && $transaction) {
                 // Смотрю есть ли реферер
                 $referer = Referals::model()->find('referal = :referal', array(':referal' => $transaction->user_id));
                 if ($referer !== NULL) {
                     $refererProfile = UserProfiles::model()->with('user')->find('t.user_id = :user_id', array(':user_id' => $referer->referer));
                     if ($refererProfile) {
                         $gsModel = Gs::model()->findByPk($transaction->getGsId());
                         // Кол-во предметов которые были куплены, от них будет считаться % рефералу
                         $countItems = $transaction->getSum() / $gsModel->deposit_course_payments;
                         $profit = $countItems / 100 * $percents;
                         $refererProfile->balance += $profit;
                         $refererProfile->save(FALSE, array('balance', 'updated_at'));
                         // Логирую
                         $dataDb = array('referer_id' => $refererProfile->user_id, 'referal_id' => $transaction->getUserId(), 'profit' => $profit, 'sum' => $transaction->getSum(), 'percent' => $percents, 'transaction_id' => $transaction->getPrimaryKey(), 'created_at' => date('Y-m-d H:i:s'));
                         db()->createCommand()->insert('{{referals_profit}}', $dataDb);
                         // Отправляю письмо что баланс реферера был пополнен
                         notify()->rechargeBalanceByReferal($refererProfile->user->email, array('profit' => $profit));
                         // Логирую действие юзера
                         if (app()->params['user_actions_log']) {
                             $log = new UserActionsLog();
                             $log->user_id = $transaction->getUserId();
                             $log->action_id = UserActionsLog::ACTION_DEPOSIT_SUCCESS;
                             $log->params = json_encode($dataDb);
                             $log->save();
                         }
                     }
                 }
             }
             echo $deposit->success(Yii::t('main', 'Ваш баланс успешно пополнен.'));
         } catch (Exception $e) {
             echo $deposit->error($e->getMessage());
         }
     } else {
         $this->redirect(array('/index/default/index'));
     }
 }
Exemplo n.º 3
0
 /**
  * Если пользователь зарегистрировался и сохранился то возвращаем //тру
  *
  * @return boolean
  */
 public function checkAndLoginNewplayer()
 {
     if ($this->validate()) {
         // Если пароли не совпадают выдадим ошибку
         if ($this->password != $this->password_repeat) {
             $this->addError('password', 'Вы указали разные значения в поле пароль');
             return false;
         } else {
             $this->password = md5($this->password);
             $this->date_regist = time();
             if ($this->save()) {
                 // Отправить письмо с подтверждением email
                 $this->sendAndCheckEmail();
                 // Проверка и создание реферала
                 $session = new CHttpSession();
                 $session->open();
                 if (isset($session['ref_id'])) {
                     $player = Player::model()->findByAttributes(array('id' => (int) $session['ref_id']));
                     if ($player != null) {
                         $referal = new Referals();
                         $referal->id_player = $player->id;
                         $referal->id_referal = $this->id;
                         $referal->is_active = Referals::$NOT_ACTIVE;
                         $referal->save();
                     }
                 }
                 $statistic = new Statistic();
                 $statistic->id_player = $this->id;
                 $statistic->invest_summ = 0;
                 $statistic->out_sum = 0;
                 $statistic->questions_summ_complette = 0;
                 $statistic->referals = 0;
                 $statistic->save();
                 $identity = new UserIdentity($this->email, $this->password);
                 $identity->authenticate();
                 Yii::app()->user->login($identity, 0);
                 return true;
             } else {
                 return false;
             }
         }
     } else {
         return false;
     }
 }
Exemplo n.º 4
0
 /**
  * Создание аккаунта на сайте
  *
  * @return Users
  */
 private function _createAccount()
 {
     $transaction = db()->beginTransaction();
     $login = $this->getLogin();
     try {
         // Создаю нового юзера
         $user = new Users();
         $user->login = $login;
         $user->password = $this->password;
         $user->email = $this->email;
         $user->activated = config('register.confirm_email') ? Users::STATUS_INACTIVATED : Users::STATUS_ACTIVATED;
         $user->role = Users::ROLE_DEFAULT;
         $user->ls_id = $this->gs_list[$this->gs_id]['login_id'];
         $user->save(FALSE);
         // Referer
         if ($this->referer != '' && $this->refererInfo) {
             $referals = new Referals();
             $referals->referer = $this->refererInfo->getPrimaryKey();
             $referals->referal = $user->getPrimaryKey();
             $referals->save(FALSE);
         }
         // Удаляю реферальную куку
         if (isset(request()->cookies[app()->params['cookie_referer_name']])) {
             unset(request()->cookies[app()->params['cookie_referer_name']]);
         }
         $transaction->commit();
         return $user;
     } catch (Exception $e) {
         $transaction->rollback();
         // Удаляю созданный аккаунт на сервере
         $this->l2->getDb()->createCommand("DELETE FROM {{accounts}} WHERE login = :login LIMIT 1")->bindParam('login', $login, PDO::PARAM_STR)->execute();
         user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.'));
         return FALSE;
     }
 }
Exemplo n.º 5
0
 public function actionResult()
 {
     $rc = Yii::app()->robokassa;
     // Коллбэк для события "оплата произведена"
     $rc->onSuccess = function ($event) {
         // Запишем в модель оплаты что оплата прошла
         $payForm = Yii::app()->robokassa->params['order'];
         $payForm->status = 'succes';
         $payForm->save();
         // получим пользователя из модели оплаты
         $player = Player::model()->findByPk($payForm->id_player);
         // Прибавим в статистике пользователя параметр инвестиции
         $statistic = Statistic::model()->findByAttributes(array('id_player' => $player->id));
         $statistic->invest_summ += $payForm->summ;
         $statistic->save();
         // Добавим пользователю сумму на счет оплаты !!!*1000!!!
         $player->setSummBuyPlus($payForm->summ);
         // Увеличим лемит вывода
         $current_summ_limit = $payForm->summ * 0.4;
         $player->setSummLimitPlus($current_summ_limit);
         // Получить реферала, если есть(?)
         $referal = Referals::model()->findByAttributes(array('id_referal' => $player->id));
         if ($referal != null) {
             // Получить пригласившего
             $parent_referal = Player::model()->findByAttributes(array('id' => $referal->id_player));
             // Получить статистику пригласившего и записать в базу
             $statistic_referal = Statistic::model()->findByAttributes(array('id_player' => $parent_referal->id));
             // Если еще не оплачивал, отметить что оплатил, добавить реферала в сумму рефералов прегласившего
             if ($referal->is_active == 0) {
                 $referal->is_active = 1;
                 $statistic_referal->referals += 1;
             }
             $summ_pay = $payForm->summ;
             $parent_referal->setReferalBonuses($summ_pay, $statistic_referal);
         }
     };
     // Коллбэк для события "отказ от оплаты"
     $rc->onFail = function ($event) {
         $InvId = Yii::app()->request->getParam('InvId');
         $payForm = Pays::model()->findByAttributes(array('id' => $InvId));
         if ($payForm != null) {
             $payForm->status = 'fail';
             $payForm->save();
         }
     };
     // Обработка ответа робокассы
     $rc->result();
 }
Exemplo n.º 6
0
 public function actionMyReferals()
 {
     $player = Player::model()->findByAttributes(array('email' => Yii::app()->user->id));
     $criteria = new CDbCriteria();
     $criteria->addCondition('id_player = :id_player');
     $criteria->params = array(':id_player' => $player->id);
     $count = Referals::model()->count($criteria);
     $pages = new CPagination($count);
     // элементов на страницу
     $pages->pageSize = 10;
     $pages->applyLimit($criteria);
     $referals = Referals::model()->findAll($criteria);
     $this->render('my_referals', array('player' => $player, 'referals' => $referals));
 }