Exemplo n.º 1
0
 /**
  * Update company info
  *
  * <b>Request Type</b>: PUT<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/management/company/{id}<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used to update company info
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     captcha: string<br/>
  *     company: string<br/>
  *     name: string<br/>
  *     phone: string<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  *  {
  *      'message' => 'OK';
  *  }
  * </pre>
  */
 public function actionUpdate($id)
 {
     $account = Account::findByPk(new \MongoId($id));
     $company = $this->getParams('company');
     $name = $this->getParams('name');
     $phone = $this->getParams('phone');
     $code = $this->getParams('captcha');
     if (empty($company) && empty($name) && empty($phone)) {
         throw new BadRequestHttpException('Missing require params');
     }
     !empty($company) ? $account->company = $company : '';
     !empty($name) ? $account->name = $name : '';
     if (!empty($phone)) {
         if (empty($code)) {
             throw new InvalidParameterException(['captcha' => \Yii::t('management', 'empty_captcha_error')]);
         }
         $this->attachBehavior('CaptchaBehavior', new CaptchaBehavior());
         $this->checkCaptcha($phone, $code);
         $account->phone = $phone;
     }
     if ($account->save()) {
         return ['message' => 'ok'];
     } else {
         throw new ServerErrorHttpException('Comapny save fail');
     }
 }
Exemplo n.º 2
0
 /**
  * @args {"description": "Delay: Clean offline client and helpdesk every minute"}
  */
 public function perform()
 {
     $accounts = Account::findAll([]);
     foreach ($accounts as $account) {
         $accountId = $account->_id;
         $setting = HelpDeskSetting::findOne(['accountId' => $accountId]);
         if (!empty($setting)) {
             $maxWaitTime = $setting->maxWaitTime;
             // Close timeout conversation
             $chatConversations = ChatConversation::findAll(['accountId' => $accountId, 'status' => ChatConversation::STATUS_OPEN, 'lastChatTime' => ['$lt' => TimeUtil::msTime(time() - $maxWaitTime * 60)]]);
             foreach ($chatConversations as $chatConversation) {
                 HelpDesk::disconnect($chatConversation->_id, ['type' => 'brake']);
             }
             // Delete timeout pending client
             $pendingClients = PendingClient::findAll(['accountId' => $accountId, 'lastPingTime' => ['$lt' => TimeUtil::msTime(time() - PendingClient::PING_THRESHOLD)]]);
             foreach ($pendingClients as $pendingClient) {
                 $pendingClient->delete();
             }
             // Clean offline helpdesk
             $cache = Yii::$app->cache;
             $onlineHelpDesks = $cache->get(HelpDesk::CACHE_PREFIX_HELPDESK_PING . $accountId);
             if (!empty($onlineHelpDesks)) {
                 foreach ($onlineHelpDesks as $deskId => $lastPingTime) {
                     if ($lastPingTime < TimeUtil::msTime(time() - HelpDesk::PING_THRESHOLD)) {
                         HelpDesk::leave($deskId, $accountId, ['type' => 'droping']);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 3
0
 /**
  *  Check expired membership card.
  */
 public function actionCheckCardExpiredTime()
 {
     $accounts = Account::find()->where(['isDeleted' => Account::NOT_DELETED])->all();
     if (!empty($accounts)) {
         $nowTimestamp = strtotime(date('Y-m-d')) * 1000;
         $oneDayTimestamp = 24 * 60 * 60 * 1000;
         foreach ($accounts as $account) {
             $accountId = $account->_id;
             for ($day = 0; $day <= 7; $day++) {
                 $startDayTimestamp = $nowTimestamp + $oneDayTimestamp * ($day - 1);
                 $endDayTimestamp = $nowTimestamp + $oneDayTimestamp * $day;
                 if ($day === 0) {
                     $startDayTimestamp = 0;
                 }
                 $expiredCount = Member::find()->where(['accountId' => $accountId, 'cardExpiredAt' => ['$lte' => $endDayTimestamp, '$gt' => $startDayTimestamp], 'isDeleted' => Member::NOT_DELETED])->count();
                 if ($expiredCount > 0) {
                     if ($day === 0) {
                         $content = "有 {$expiredCount} 个会员的会员卡已过期, <a href='/member/member?cardState=3'>(点击查看)</a>";
                     } else {
                         if ($day === 1) {
                             $content = "有 {$expiredCount} 个会员的会员卡即将于1天内过期, <a href='/member/member?cardState=1'>(点击查看)</a>";
                         } else {
                             $date = date("Y-m-d", $startDayTimestamp / 1000);
                             $content = "有 {$expiredCount} 个会员的会员卡即将于 {$date} 过期, <a href='/member/member?cardState=2'>(点击查看)</a>";
                         }
                     }
                     $this->_recordMessage($accountId, $content);
                 }
             }
         }
     }
 }
 /**
  * delete muti redemption template and promotion template(delete-product-template)
  */
 public function actionDeleteProductTemplate()
 {
     $accountInfos = Account::findAll(['enabledMods' => ['$all' => ['product']]]);
     if ($accountInfos) {
         $redemptionTemplate = $promotionTemplate = [];
         foreach ($accountInfos as $accountInfo) {
             if (empty($redemptionTemplate) || empty($promotionTemplate)) {
                 $datas = MessageTemplate::getDefaultTemplateData($accountInfo['_id']);
                 foreach ($datas as $data) {
                     if ($data['name'] == MessageTemplate::REDEMPTION_TITLE) {
                         $redemptionTemplate = ['name' => $data['name'], 'weChat' => $data['weChat'], 'email' => $data['email'], 'mobile' => $data['mobile']];
                     }
                     if ($data['name'] == MessageTemplate::PROMOTIONCODE_TITLE) {
                         $promotionTemplate = ['name' => $data['name'], 'weChat' => $data['weChat'], 'email' => $data['email'], 'mobile' => $data['mobile']];
                     }
                 }
             }
             $redemptionTemplate['accountId'] = $accountInfo['_id'];
             $promotionTemplate['accountId'] = $accountInfo['_id'];
             $redemptionDatas = MessageTemplate::findAll($redemptionTemplate);
             if (count($redemptionDatas) >= 2) {
                 MessageTemplate::deleteAll(['_id' => $redemptionDatas[0]->_id]);
                 echo 'delete redemptionTemplate id:' . $redemptionDatas[0]->_id . PHP_EOL;
             }
             $promotionDatas = MessageTemplate::findAll($promotionTemplate);
             if (count($promotionDatas) >= 2) {
                 MessageTemplate::deleteAll(['_id' => $promotionDatas[0]->_id]);
                 echo 'delete promotionTemplate id:' . $promotionDatas[0]->_id . PHP_EOL;
             }
         }
     }
     echo 'over' . PHP_EOL;
 }
 /**
  * @args {"description": "Delay: Stats of StatsMemberGrowthMonthly every day"}
  * @author Rex Chen
  */
 public function perform()
 {
     $args = $this->args;
     $date = empty($args['date']) ? '' : $args['date'];
     $datetime = TimeUtil::getDatetime($date);
     $dateStr = date('Y-m', $datetime);
     $startTime = new \MongoDate(strtotime($dateStr . '-01'));
     $endTime = new \MongoDate(strtotime($dateStr . '-01 +1 month'));
     $accounts = Account::findAll(['enabledMods' => 'member']);
     foreach ($accounts as $account) {
         $accountId = $account->_id;
         $totalMember = Member::countByAccount($accountId, null, $endTime);
         $totalActive = MemberLogs::getTotalActiveByAccount($accountId, $startTime, $endTime);
         $totalNew = Member::countByAccount($accountId, $startTime, $endTime);
         $statsGrowth = ModelStatsMemberGrowthMonthly::getByMonthAndAccount($accountId, $dateStr);
         if (empty($statsGrowth)) {
             $statsGrowth = new ModelStatsMemberGrowthMonthly();
             $statsGrowth->accountId = $accountId;
             $statsGrowth->month = $dateStr;
         }
         $statsGrowth->totalNew = $totalNew;
         $statsGrowth->totalActive = $totalActive;
         $statsGrowth->totalInactive = $totalMember - $totalActive;
         try {
             $statsGrowth->save();
         } catch (Exception $e) {
             ResqueUtil::log(['Update StatsMemberGrowthMonthly error' => $e->getMessage(), 'StatsMemberGrowthMonthly' => $statsGrowth]);
             continue;
         }
     }
     return true;
 }
 public function perform()
 {
     $args = $this->args;
     if (empty($args['language']) || empty($args['header']) || empty($args['key']) || empty($args['accountId']) || empty($args['condition'])) {
         ResqueUtil::log(['status' => 'fail to export code', 'message' => 'missing params', 'args' => $args]);
         return false;
     }
     //set the language
     Yii::$app->language = empty($args['language']) ? LanguageUtil::DEFAULT_LANGUAGE : $args['language'];
     $header = $args['header'];
     $fileName = $args['key'];
     $filePath = ExcelUtil::getFile($fileName, 'csv');
     $condition = unserialize($args['condition']);
     $object = GoodsExchangeLog::find();
     $classFunction = '\\backend\\modules\\product\\models\\GoodsExchangeLog::preProcessExportData';
     $backendUser = Account::findByPk(new \MongoId($args['accountId']));
     ExcelUtil::processMultiData($header, $filePath, $backendUser, $condition, $object, $classFunction, ['changeTostring' => ['goods']]);
     $hashKey = ExcelUtil::setQiniuKey($filePath, $fileName);
     if ($hashKey) {
         //notice frontend the job is finished
         \Yii::$app->tuisongbao->triggerEvent(Message::EVENT_EXPORT_FINISH, ['key' => $fileName], [Message::CHANNEL_GLOBAL . $args['accountId']]);
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 7
0
 public function deleteTag($accountId, $name)
 {
     Account::updateAll(['$pull' => ['tags' => ['name' => $name]]], ['_id' => $accountId]);
     Member::updateAll(['$pull' => ['tags' => $name]], ['accountId' => $accountId, 'tags' => $name]);
     Campaign::updateAll(['$pull' => ['tags' => $name]], ['accountId' => $accountId, 'tags' => $name]);
     $data = ['type' => 'tag_deleted', 'account_id' => $accountId, 'name' => $name];
     $this->notifyModules($data);
 }
Exemplo n.º 8
0
 /**
  * Create tags
  * @param  array $tags
  * @return boolean
  */
 public function create($tags)
 {
     if (empty($tags) || !is_array($tags)) {
         return false;
     }
     $addTags = [];
     foreach ($tags as $tagName) {
         $addTags[] = ['name' => $tagName];
     }
     return (bool) Account::updateAll(['$addToSet' => ['tags' => ['$each' => $addTags]]], ['_id' => $this->accountId]);
 }
Exemplo n.º 9
0
 public function perform()
 {
     $args = $this->args;
     if (empty($args['accountId']) || empty($args['key']) || empty($args['header'])) {
         ResqueUtil::log(['status' => 'fail to export member', 'message' => 'missing params', 'args' => $args]);
         return false;
     }
     Yii::$app->language = empty($args['language']) ? LanguageUtil::DEFAULT_LANGUAGE : $args['language'];
     $accountId = new \MongoId($args['accountId']);
     $header = $args['header'];
     // get member's customized properties
     $memberProperties = MemberProperty::getByAccount($accountId);
     foreach ($memberProperties as $memberProperty) {
         if ($memberProperty->isDefault) {
             $header[$memberProperty->name] = Yii::t('member', $memberProperty->name);
         } else {
             $header[$memberProperty->name] = $memberProperty->name;
         }
     }
     $socialAccountsMap = [];
     $account = Account::findByPk($accountId);
     $channelIds = Channel::getEnableChannelIds($accountId);
     if (!empty($channelIds)) {
         $socialAccounts = \Yii::$app->weConnect->getAccounts($channelIds);
         foreach ($socialAccounts as $socialAccount) {
             $socialAccountsMap[$socialAccount['id']] = $socialAccount['name'];
         }
     }
     $cardMap = [];
     $cards = MemberShipCard::getByAccount($accountId);
     foreach ($cards as $card) {
         $cardMap[(string) $card->_id] = $card->name;
     }
     $condition = unserialize($args['condition']);
     //get properties
     $memberProperties = MemberProperty::findAll(['accountId' => $accountId]);
     $base = ['cardMap' => $cardMap, 'socialAccountsMap' => $socialAccountsMap, 'memberProperties' => $memberProperties];
     $fileName = $args['key'];
     $filePath = ExcelUtil::getFile($fileName, 'csv');
     $orderBy = Member::normalizeOrderBy($args['params']);
     $object = Member::find();
     $classFunction = '\\backend\\modules\\member\\models\\Member::preProcessMemberData';
     ExcelUtil::processMultiData($header, $filePath, $base, $condition, $object, $classFunction, [], $orderBy);
     $hashKey = ExcelUtil::setQiniuKey($filePath, $fileName);
     if ($hashKey) {
         //notice frontend the job is finished
         \Yii::$app->tuisongbao->triggerEvent(Message::EVENT_EXPORT_FINISH, ['key' => $fileName], [Message::CHANNEL_GLOBAL . $args['accountId']]);
         return true;
     } else {
         return false;
     }
 }
 public function actionIndex()
 {
     $accounts = Account::findAll([]);
     if (!empty($accounts)) {
         foreach ($accounts as $account) {
             $options = Yii::$app->params['sensitive_options'];
             foreach ($options as $name => $options) {
                 SensitiveOperation::initOptions($name, $options, $account->_id);
             }
         }
     }
     echo "Fininsh init the sensitive operation.\n";
 }
Exemplo n.º 11
0
 /**
  * @args {"description": "Delay: Issue birthday score every day"}
  */
 public function perform()
 {
     $args = $this->args;
     //Delay issue birthday score every day
     if (empty($args['memberId']) || empty($args['accountId'])) {
         $accounts = Account::findAll(['enabledMods' => 'member']);
         foreach ($accounts as $account) {
             $this->getBirthDayReward($account->_id);
         }
     } else {
         //issue birthday score when update member profile
         $this->getBirthDayReward(new MongoId($args['accountId']), new MongoId($args['memberId']));
     }
     return true;
 }
Exemplo n.º 12
0
 public function actionFixData($startData, $endData)
 {
     $accounts = Account::findAll(['enabledMods' => 'product']);
     foreach ($accounts as $account) {
         $accountId = $account->_id;
         $condition = ['accountId' => $accountId, 'createdAt' => ['$gte' => new MongoDate(strtotime($startData)), '$lt' => new Mongodate(strtotime($endData))]];
         $pipeline = [['$match' => $condition], ['$group' => ['_id' => ['campaignId' => '$campaignId', 'code' => '$code'], 'count' => ['$sum' => 1]]], ['$match' => ['count' => ['$gt' => 1]]]];
         $stats = CampaignLog::getCollection()->aggregate($pipeline);
         if (!empty($stats)) {
             foreach ($stats as $stat) {
                 $code = $stat['_id']['code'];
                 $logCondition = array_merge($condition, $stat['_id']);
                 $logs = CampaignLog::find()->where($logCondition)->orderBy(['createdAt' => 1])->all();
                 $memberId = $logs[0]['member']['id'];
                 $productName = $logs[0]['productName'];
                 $description = $productName . ' ' . $code;
                 $scoreHistoryCondition = ['memberId' => $memberId, 'brief' => ScoreHistory::ASSIGNER_EXCHANGE_PROMOTION_CODE, 'description' => $description];
                 $scoreHistorys = ScoreHistory::find()->where($scoreHistoryCondition)->orderBy(['createdAt' => 1])->all();
                 $keepScoreHistory = $scoreHistorys[0];
                 unset($scoreHistorys[0]);
                 $removeScoreHistoryIds = [];
                 $deduct = 0;
                 foreach ($scoreHistorys as $scoreHistory) {
                     $removeScoreHistoryIds[] = $scoreHistory->_id;
                     $deduct += $scoreHistory->increment;
                 }
                 $member = Member::findByPk($memberId);
                 if ($member->score <= $deduct || $member->totalScore <= $deduct || $member->totalScoreAfterZeroed <= $deduct) {
                     echo 'Failed : Member' . $memberId . ' score not enough ' . 'score: ' . $member->score;
                     echo ' totalScore: ' . $member->totalScore;
                     echo ' totalScoreAfterZeroed: ' . $member->totalScoreAfterZeroed . PHP_EOL;
                     continue;
                 }
                 $deductScore = 0 - $deduct;
                 Member::updateAll(['$inc' => ['score' => $deductScore, 'totalScore' => $deductScore, 'totalScoreAfterZeroed' => $deductScore]], ['_id' => $memberId]);
                 ScoreHistory::deleteAll(['_id' => ['$in' => $removeScoreHistoryIds]]);
                 $logIds = ArrayHelper::getColumn($logs, '_id');
                 $keepLogId = $logIds[0];
                 unset($logIds[0]);
                 CampaignLog::deleteAll(['_id' => ['$in' => array_values($logIds)]]);
                 echo 'Success: ' . $productName . ' ' . $code . ' ' . $stat['count'];
                 echo ' Deduct member ' . $memberId . ' score ' . $deduct . PHP_EOL;
             }
         }
     }
     echo 'Success' . PHP_EOL;
 }
Exemplo n.º 13
0
 public function actionRemove()
 {
     $name = $this->getParams('name', '');
     if ($name === '') {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $accountId = $this->getAccountId();
     $account = Account::findByPk($accountId);
     $channels = Channel::getEnableChannelIds($accountId);
     if (!defined('KLP') || !KLP) {
         if (!empty($channels)) {
             $followerTags = Yii::$app->weConnect->deleteTag($channels, $name);
         }
     }
     $this->attachBehavior('TagBehavior', new TagBehavior());
     $this->deleteTag($accountId, $name);
     return ['message' => 'OK', 'data' => null];
 }
Exemplo n.º 14
0
 /**
  * @args {"description": "Delay: Send member expired message every day"}
  */
 public function perform()
 {
     $accounts = Account::find()->where(['isDeleted' => Account::NOT_DELETED])->all();
     if (!empty($accounts)) {
         $nowTimestamp = strtotime(date('Y-m-d')) * 1000;
         $oneDayTimestamp = 24 * 60 * 60 * 1000;
         foreach ($accounts as $account) {
             $accountId = $account->_id;
             for ($day = 0; $day <= 7; $day++) {
                 $startDayTimestamp = $nowTimestamp + $oneDayTimestamp * ($day - 1);
                 $endDayTimestamp = $nowTimestamp + $oneDayTimestamp * $day;
                 if ($day === 0) {
                     $startDayTimestamp = 0;
                 }
                 $expiredCount = Member::find()->where(['accountId' => $accountId, 'cardExpiredAt' => ['$lte' => $endDayTimestamp, '$gt' => $startDayTimestamp], 'isDeleted' => Member::NOT_DELETED])->count();
                 if ($expiredCount > 0) {
                     if ($day === 0) {
                         if ($expiredCount == 1) {
                             $content = "msg_have {$expiredCount} msg_had_expired <a href='/member/member?cardState=3'> msg_click_read </a>";
                         } else {
                             $content = "msg_have {$expiredCount} msg_had_expireds <a href='/member/member?cardState=3'> msg_click_read </a>";
                         }
                     } else {
                         if ($day === 1) {
                             if ($expiredCount == 1) {
                                 $content = "msg_have {$expiredCount} msg_having_expired <a href='/member/member?cardState=1'> msg_click_read </a>";
                             } else {
                                 $content = "msg_have {$expiredCount} msg_had_expireds <a href='/member/member?cardState=1'> msg_click_read </a>";
                             }
                         } else {
                             $date = date("Y-m-d", $startDayTimestamp / 1000);
                             if ($expiredCount == 1) {
                                 $content = "msg_have {$expiredCount} msg_having {$date} msg_expired <a href='/member/member?cardState=2'> msg_click_read </a>";
                             } else {
                                 $content = "msg_have {$expiredCount} msg_havings {$date} msg_expired <a href='/member/member?cardState=2'> msg_click_read </a>";
                             }
                         }
                     }
                     $this->recordMessage($accountId, $content);
                 }
             }
         }
     }
 }
Exemplo n.º 15
0
 /**
  * @args {"description": "Delay: Statistics of location info and scores issued by rule every day"}
  */
 public function perform()
 {
     $args = $this->args;
     $accounts = Account::findAll(['enabledMods' => 'member']);
     foreach ($accounts as $account) {
         $accountId = $account->_id;
         //score rule statistics
         $scoreRules = ScoreRule::getByAccount($accountId);
         foreach ($scoreRules as $scoreRule) {
             $this->updateScoreRuleStatistics($scoreRule->name, $accountId);
         }
         //location statistics
         $result = $this->updateLocationStatistics($accountId);
         if (!$result) {
             LogUtil::error(['message' => 'statistics location error', 'date' => date('Y-m-d H:i:s'), 'args' => $args], 'resque');
         }
     }
     return true;
 }
Exemplo n.º 16
0
 /**
  * @args {"description": "Delay: stats of member orders", "runNextJob": true}
  * @author Rex Chen
  */
 public function perform()
 {
     $dateStr = date('Y-m-d');
     $operateTimeTo = new MongoDate(strtotime($dateStr));
     $accounts = Account::findAll([]);
     foreach ($accounts as $account) {
         $modelStatsOrder = StatsOrder::getLatestByAccount($account->_id);
         if (empty($modelStatsOrder)) {
             $operateTimeFrom = null;
         } else {
             //ensure Y-m-d mongodate
             $operateDate = MongodbUtil::MongoDate2String($modelStatsOrder->createdAt, 'Y-m-d');
             if ($dateStr === $operateDate) {
                 return true;
             }
             $operateTimeFrom = new MongoDate(strtotime($operateDate));
         }
         $this->statsMemberOrder($account->_id, $operateTimeFrom, $operateTimeTo);
         $this->updateMemberRecentTransactionCount($account->_id);
     }
 }
Exemplo n.º 17
0
 /**
  * Init the channel menus config
  * @param  string $channelId
  * @param  MongoId $accountId
  */
 protected function initConfig($channelId, $accountId)
 {
     $account = Account::findByPk($accountId);
     $modules = $account->enabledMods;
     $basePath = Yii::getAlias('@backend');
     if (!empty($modules)) {
         foreach ($modules as $module) {
             if (!empty($module)) {
                 $file = $basePath . '/modules/' . $module . '/config/channelMenu.php';
                 if (is_file($file)) {
                     $config = (require $file);
                     if (is_array($config)) {
                         if ($this->_isNotAssoc($config)) {
                             $this->config = array_merge((array) $this->config, (array) $config);
                         } else {
                             $this->config[$module] = $config;
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 18
0
 /**
  * create default category base on the account id(create-default-category)
  * @param $accountId, string; if this value is all,it will support all accounts,otherwise it only support this account
  */
 public function actionCreateDefaultCategory($accountId)
 {
     $where = ['enabledMods' => ['$all' => ['helpdesk']]];
     if (empty($accountId)) {
         echo 'AccountId can not be empty' . PHP_EOL;
         exit;
     } elseif ($accountId == 'all') {
         $accounts = Account::findAll($where);
         if (!empty($accounts)) {
             foreach ($accounts as $account) {
                 $this->_createDefaultCategory($account->_id);
             }
         }
     } else {
         $accountId = new MongoId($accountId);
         $account = Account::findOne(array_merge(['_id' => $accountId], $where));
         if (empty($account)) {
             echo 'Can not find the account by ' . $accountId . PHP_EOL;
             exit;
         }
         $this->_createDefaultCategory($accountId);
     }
     echo 'Create default value successfully' . PHP_EOL;
 }
Exemplo n.º 19
0
 /**
  * Register billing account
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/site/register<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for registering user.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     name: string, the user name<br/>
  *     email: string, the user email<br/>
  *     password: string, the user password<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     ack: integer, mark the create result, 1 means create successfully, 0 means create fail<br/>
  *     message: string, if create fail, it contains the error message<br/>
  *     data: array, json array to describe all users detail information<br/>
  *     <br/><br/>
  *
  * <b>Request Example:</b><br/>
  * <pre>
  * {
  *     "name" : "harrysun",
  *     "email" : "*****@*****.**",
  *     "password" : "abc123_"
  * }
  * </pre>
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *    'ack' : 1,
  *    'message': ''
  * }
  * </pre>
  */
 public function actionRegister()
 {
     $data = $this->getParams();
     $account = new Account();
     $account->save();
     $user = new User();
     $user->name = $data['name'];
     $user->email = $data['email'];
     $user->salt = StringUtil::rndString(6);
     $user->password = User::encryptPassword($data['password'], $user->salt);
     $user->accountId = $account->_id;
     $user->role = User::ROLE_ADMIN;
     $user->isActivated = User::NOT_ACTIVATED;
     $user->avatar = Yii::$app->params['defaultAvatar'];
     $user->language = 'zh_cn';
     if ($user->validate()) {
         // all inputs are valid
         if ($user->save()) {
             $validation = new Validation();
             $validation->userId = $user->_id;
             $validation->code = StringUtil::uuid();
             $validation->expire = new \MongoDate(strtotime('+1 day'));
             if ($validation->save()) {
                 $mail = Yii::$app->mail;
                 $host = Yii::$app->request->hostInfo;
                 $vars = ['name' => $user->name, 'link' => $host . '/api/old-site/activate?code=' . $validation->code, 'host' => $host];
                 $mail->setView('//mail/register', $vars, '//layouts/email');
                 $mail->sendMail($user->email, '欢迎注册WeMarketing');
                 return ["ack" => 1, "message" => 'Register success.'];
             } else {
                 return ["ack" => 0, "message" => 'Validation save fail.'];
             }
         } else {
             return ["ack" => 0, "message" => 'Register user fail.'];
         }
     } else {
         // validation failed: $errors is an array containing error messages
         $errors = $user->errors;
         //revert the accout data
         Account::deleteAll(['_id' => $account->_id]);
         return ["ack" => 0, "message" => $errors];
     }
 }
Exemplo n.º 20
0
 /**
  * Generate app private key
  */
 public function generateKey()
 {
     $account = Account::findByPk($this->accountId);
     $token = ['uid' => (string) $this->accountId, 'scopes' => [], 'app' => (string) $this->_id];
     $this->privateKey = \JWT::encode($token, $account->secretKey, self::DEFAULT_ALG, $account->accessKey);
 }
Exemplo n.º 21
0
 /**
  * create default page cover base on account id and host info(域名)(create-default-page-cover)
  * @param $accountId, string; if this value is all,it will support all accounts,otherwise it only support this account
  * @param $hostinfo, string, domain name example:http://wm.com
  */
 public function actionCreateDefaultPageCover($accountId, $hostinfo)
 {
     $where = ['enabledMods' => ['$all' => ['microsite']]];
     if (empty($accountId) || empty($hostinfo)) {
         echo 'accountId and hostinfo can not be empty' . PHP_EOL;
         exit;
     } elseif ($accountId == 'all') {
         $accounts = Account::findAll($where);
         if (!empty($accounts)) {
             foreach ($accounts as $account) {
                 $this->_createDefaultPageCover($account->_id, $hostinfo);
             }
         }
     } else {
         $accountId = new MongoId($accountId);
         $account = Account::findOne(array_merge(['_id' => $accountId], $where));
         if (empty($account)) {
             echo 'Can not find the account by ' . $accountId . PHP_EOL;
             exit;
         }
         $this->_createDefaultPageCover($accountId, $hostinfo);
     }
     echo 'Create default value successfully' . PHP_EOL;
 }
Exemplo n.º 22
0
 public function actionCheckRefund()
 {
     $params = $this->getParams();
     $accountId = $this->getAccountId();
     $account = Account::findByPk($accountId);
     if (empty($params['outTradeNo']) || empty($params['refundFee'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $condition = ['quncrmAccountId' => (string) $accountId, 'outTradeNo' => $params['outTradeNo'], 'outRefundNo' => $params['outTradeNo'], 'totalFee' => (int) $params['refundFee'], 'refundFee' => (int) $params['refundFee'], 'opUserId' => $account['name']];
     $result = Yii::$app->weConnect->checkRefund($condition);
     return $result;
 }
Exemplo n.º 23
0
 /**
  * delete member log when the member is deleted(delete-member-log)
  */
 public function actionDeleteMemberLog()
 {
     $accounts = Account::findAll(['enabledMods' => 'member']);
     foreach ($accounts as $account) {
         $deletedMembers = Member::find()->where(['isDeleted' => Member::DELETED, 'accountId' => $account->_id])->all();
         $deletedMemberIds = ArrayHelper::getColumn($deletedMembers, '_id');
         MemberLogs::deleteAll(['memberId' => ['$in' => $deletedMemberIds]]);
     }
 }
Exemplo n.º 24
0
 /**
  * Get accountId and company when exchange
  * @param array $params
  * @return array
  */
 public function exchange($params)
 {
     $token = Token::getToken();
     \Yii::$app->language = empty($token->language) ? LanguageUtil::DEFAULT_LANGUAGE : $token->language;
     $this->checkCode($params);
     $accountId = $params['accountId'];
     $account = Account::findByPk($accountId);
     return ['accountId' => $accountId, 'company' => empty($account->company) ? null : $account->company];
 }
Exemplo n.º 25
0
 /**
  * Create tag
  *
  * <b>Request Type: </b> POST<br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/channel/tags<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary </b>: This api is used for create tag.
  *
  * <b>Request Parameters: </b><br/>
  *      name: the name of the tag
  *
  * <b>Response Params:</b><br/>
  *     msg: string, if create fail, it contains the error message<br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *   "msg": "OK"
  * }
  * </pre>
  */
 public function actionCreate()
 {
     $result = ['msg' => 'OK'];
     $tags = $this->getParams('tags');
     $isAutoScanFollower = $this->getParams('isAutoScanFollower');
     $accountId = $this->getAccountId();
     $account = Account::findOne(['_id' => new \MongoId($accountId)]);
     if (empty($account)) {
         throw new GoneHttpException("no such account");
     }
     if (!empty($isAutoScanFollower) && $isAutoScanFollower == true) {
         if (empty($tags) || !is_array($tags)) {
             throw new BadRequestHttpException("Error Processing Request", 1);
         }
     }
     $tag = [];
     foreach ($tags as $item) {
         $tag[] = ['name' => $item];
     }
     if (!Account::updateAll(['$addToSet' => ['tags' => ['$each' => $tag]]], ['_id' => $accountId])) {
         throw new ServerErrorHttpException("update tags failed");
     }
     return $result;
 }
Exemplo n.º 26
0
 /**
  * Get all accountId
  * @return array
  */
 public static function getAllAccount()
 {
     $accounts = Account::findAll([]);
     $ids = [];
     foreach ($accounts as $account) {
         $ids[] = $account->_id;
     }
     return $ids;
 }
Exemplo n.º 27
0
 /**
  * Create a new account and initialize it
  * @param string $company
  * @param string $mobile
  * @param string $priceType
  * @throws ServerErrorHttpException
  * @return MongoId
  */
 public static function create($company, $phone, $name, $priceType = self::PRICE_TYPE_FREE)
 {
     $account = new Account();
     $account->priceType = $priceType;
     $account->company = $company;
     $account->phone = $phone;
     $account->name = $name;
     $account->availableExtMods = ['member', 'product', 'microsite', 'helpdesk'];
     // add 4 basic mods into extensions #3191
     $account->generateKey();
     $enabledMods = Yii::$app->params['coreMods'];
     $result = Yii::$app->extModule->getMergedConfig($enabledMods);
     $account->menus = $result['menus'];
     $account->mods = $result['mods'];
     if ($account->save()) {
         self::afterCreateAccount($account);
         return $account->_id;
     }
     throw new ServerErrorHttpException("Save account failed");
 }
Exemplo n.º 28
0
 /**
  * Sync the stores data from wechat
  */
 public function actionSync()
 {
     $accountId = Token::getAccountId();
     $result = ['finished' => true];
     $account = Account::find()->select(['syncWechat'])->where(['_id' => $accountId, 'isDeleted' => Account::NOT_DELETED])->one();
     $wechat = Channel::getWechatByAccount($accountId, false);
     if (!empty($wechat)) {
         $unsyncWechat = array_diff($wechat, (array) $account->syncWechat);
         if (!empty($unsyncWechat)) {
             $args = ['accountId' => $accountId . '', 'channels' => $unsyncWechat, 'description' => 'Direct: Sync the stores data from wechat'];
             $token = Yii::$app->job->create('backend\\modules\\channel\\job\\StoreSync', $args);
             $result = ['finished' => false, 'token' => $token];
         }
     }
     return $result;
 }
Exemplo n.º 29
0
 public static function createForWechat($accountId)
 {
     $account = Account::findByPk($accountId);
     if (empty($account)) {
         throw new Exception("Illegal accountId");
     }
     $expire = 3600 * 24 * 10000;
     //never expired
     $token = new Token();
     $token->accessToken = StringUtil::uuid();
     $token->expireTime = new \MongoDate(time() + $expire);
     $token->userId = '';
     $token->accountId = $account['_id'];
     $token->language = self::DEFAULT_LANGUAGE;
     $token->enabledMods = ['chat'];
     $token->role = User::ROLE_WECONNECT;
     if ($token->save()) {
         return $token;
     }
     throw new Exception("Faile to create token for database problems");
 }
Exemplo n.º 30
0
 /**
  * Validate code when activate user
  * @param $code, String.
  * @return String, error code or userId
  *
  * @author Sara Zhang
  */
 public static function validateCode($code, $isDeleted = true)
 {
     if (empty($code)) {
         return self::LINK_INVALID;
     }
     $validation = Validation::findOne(['code' => $code]);
     if (empty($validation)) {
         return self::LINK_INVALID;
     }
     if (empty($validation->expire) || MongodbUtil::isExpired($validation->expire)) {
         return self::LINK_EXPIRED;
     }
     $userId = $validation->userId;
     if ($validation->toValidateAccount) {
         $user = User::findOne(['_id' => $userId]);
         $attributes = ['status' => Account::STATUS_ACTIVATED, 'trialStartAt' => new \MongoDate(), 'trialEndAt' => new \MongoDate(strtotime("+30 day"))];
         Account::updateAll($attributes, ['_id' => $user->accountId]);
     }
     if ($isDeleted) {
         $validation->delete();
     }
     return $userId;
 }