示例#1
0
 /**
  * The first step of creating page
  * Use the createBasic scenario
  **/
 public function actionCreate()
 {
     $params = $this->getParams();
     $accesstoken = $this->getAccessToken();
     $token = Token::getToken($accesstoken);
     $page = new Page(['scenario' => 'createBasic']);
     $page->attributes = $params;
     $page->_id = new \MongoId();
     $page->accountId = $token->accountId;
     $userId = $token->userId;
     $user = User::findByPk($userId);
     $page->creator = ['id' => $userId, 'name' => $user->name];
     $page->url = Yii::$app->request->hostinfo . '/msite/page/' . $page->_id;
     $shortUrl = Yii::$app->urlService->shortenUrl($page->url);
     $page->shortUrl = $shortUrl['Short'];
     if ($page->validate()) {
         // all inputs are valid
         if ($page->save()) {
             return $page;
         } else {
             throw new ServerErrorHttpException(Yii::t('common', 'save_fail'));
         }
     } else {
         // valid fail, return errors
         $errors = array_keys($page->errors);
         throw new InvalidParameterException([$errors[0] => Yii::t("microSite", $errors[0] . '_field_not_empty')]);
     }
 }
示例#2
0
 /**
  * Returns the list of all rules of ChatConversation.
  * This method must be overridden by child classes to define available attributes.
  *
  * @return array list of rules.
  */
 public function rules()
 {
     $currentUser = User::findByPk(new \MongoId(CURRENT_USER_ID));
     //get default channel
     if (empty($this->accountId)) {
         throw new ServerErrorHttpException('Account id of article cannot be blank');
     }
     $defaultChannel = ArticleChannel::getDefault($this->accountId);
     if (empty($defaultChannel)) {
         throw new ServerErrorHttpException('Can not found default channel');
     }
     return array_merge(parent::rules(), [[['name', 'content', 'url'], 'required'], ['createdBy', 'default', 'value' => $currentUser->name], ['fields', 'default', 'value' => []], ['fields', 'validateFields'], ['channel', 'default', 'value' => $defaultChannel->_id], ['channel', 'toMongoId']]);
 }
 /**
  * exchange the promotioncode
  */
 public function actionExchange()
 {
     $params = $this->getParams();
     if (empty($params['code']) || empty($params['memberId'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     //get email for user
     $accesstoken = $this->getAccessToken();
     $tokenInfo = Token::findOne(['accessToken' => $accesstoken]);
     $userInfo = User::findByPk($tokenInfo['userId']);
     $params['operaterEmail'] = empty($userInfo['email']) ? '' : $userInfo['email'];
     $params['userInfo'] = empty($userInfo) ? null : ['id' => $userInfo->_id, 'name' => $userInfo->name];
     $memberId = $params['memberId'];
     $params['memberId'] = new MongoId($memberId);
     if (!empty($params['exchangeTime'])) {
         $params['exchangeTime'] = TimeUtil::ms2sTime($params['exchangeTime']);
     }
     //exchange the promotion code
     $accountId = $this->getAccountId();
     if (is_array($params['code'])) {
         //exchaneg code offline
         $codes = $params['code'];
         $successCode = [];
         foreach ($codes as $code) {
             $params['code'] = strtoupper($code);
             $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_OFFLINE);
             if ('success' == $result['result']) {
                 $successCode[] = $code;
             }
         }
         list($codeNumber, $score) = CampaignLog::getCodeRecord($successCode);
         if (!empty($params['useWebhook'])) {
             $eventData = ['type' => Webhook::EVENT_PROMOTION_CODE_REDEEMED, 'member_id' => $memberId, 'codes' => $params['code'], 'redeemed_codes' => $successCode, 'score' => $score, 'origin' => Member::PORTAL, 'account_id' => (string) $accountId, 'created_at' => TimeUtil::msTime2String($params['exchangeTime'], \DateTime::ATOM)];
             Yii::$app->webhook->triggerEvent($eventData);
         }
         //fix data
         $this->fixData($accountId, $params['memberId'], $successCode);
         return ['result' => 'success', 'codeNumber' => $codeNumber, 'totalScore' => $score, 'codes' => $successCode];
     } else {
         $params['code'] = strtoupper($params['code']);
         $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_MOBILE);
         if ('error' == $result['result']) {
             throw new InvalidParameterException($result['message']);
         } else {
             return $result;
         }
     }
 }
示例#4
0
 /**
  * Give points to member
  *
  * <b>Request Type: </b>POST<br/>
  * <b>Request Endpoint: </b>http://{server-domain}/api/member/score/give<br/>
  * <b>Content-type: </b>application/json<br/>
  * <b>Summary: </b>This api is for give scores to specific members or conditions to filter member.<br/>
  *
  * <b>Request Parameters: </b>
  *     scores: int, the value of the scores to give, required<br/>
  *     filterType: string, the type of the filter, "name" or "number" or "tag", required<br/>
  *     names: array<string>, the array of the names for filter, required only if the filterType is "name"<br/>
  *     numbers: array<string>, the array of the numbers to filter members, required only if the filterType is "number"<br/>
  *     tags: array<string>, the array of the tags fo filter members, required only if the filterType is "tag"<br/>
  *     description: string, the description. optional. <br/>
  *
  * <b>Request Example</b><br/>
  * <pre>
  * {"score":100, "filterType":"name", "names":["Zhang San", "Li Si"]}
  * </pre>
  *
  */
 public function actionGive()
 {
     $filterType = $this->getParams('filterType');
     $score = $this->getParams('score');
     $description = $this->getParams('description');
     if (empty($filterType) || empty($score)) {
         throw new BadRequestHttpException('Missing required parameters');
     }
     $userId = $this->getUserId();
     $user = User::findByPk($userId);
     $user = ['id' => $userId, 'name' => $user->name];
     $filterKey = $filterType . 's';
     $filterValue = $this->getParams($filterKey);
     if (empty($filterValue)) {
         throw new BadRequestHttpException("Missing required parameters");
     }
     $function = "giveScoreBy" . $filterKey;
     $memberList = Member::$function($score, $filterValue);
     if (empty($memberList)) {
         throw new InvalidParameterException(['member-' . $filterType => \Yii::t('member', 'no_member_find')]);
     }
     if ($memberList) {
         foreach ($memberList as $member) {
             $scoreHistory = new ScoreHistory();
             $scoreHistory->assigner = ScoreHistory::ASSIGNER_ADMIN;
             $scoreHistory->increment = $score;
             $scoreHistory->memberId = $member;
             $scoreHistory->brief = $score >= 0 ? ScoreHistory::ASSIGNER_ADMIN_ISSUE_SCORE : ScoreHistory::ASSIGNER_ADMIN_DEDUCT_SCORE;
             $scoreHistory->description = $description;
             $scoreHistory->channel = ['origin' => ScoreHistory::PORTAL];
             $scoreHistory->user = $user;
             $scoreHistory->accountId = $this->getAccountId();
             if (!$scoreHistory->save()) {
                 LogUtil::error(['message' => 'save scoreHistory failed', 'data' => $scoreHistory->toArray()], 'member');
             }
         }
         return ['status' => 'ok'];
     }
 }
示例#5
0
 public function actionUpdate($id)
 {
     $params = $this->getParams();
     $user = User::findByPk($id);
     $token = $this->getAccessToken();
     $name = $this->getParams('name');
     if (empty($name)) {
         throw new InvalidParameterException(['name' => Yii::t('common', 'required_filed')]);
     }
     $user->load($params, '');
     $lauguage = $user->language;
     if ($user->save() && Token::channgeLanguage($token, $lauguage)) {
         $user->_id .= '';
         return $user;
     } else {
         throw new ServerErrorHttpException('Fail to update user');
     }
 }
示例#6
0
 public function actionResetpassword()
 {
     $code = $this->getParams('code');
     $newPassword = $this->getParams('password');
     $result = Validation::validateCode($code);
     if ($result == Validation::LINK_INVALID) {
         throw new BadRequestHttpException(Yii::t('common', 'link_invalid'));
     } else {
         if ($result == Validation::LINK_EXPIRED) {
             throw new BadRequestHttpException(Yii::t('common', 'link_expired'));
         }
     }
     $userId = $result;
     $user = User::findByPk($userId);
     if (empty($user)) {
         throw new BadRequestHttpException(Yii::t('commmon', 'incorrect_userid'));
     }
     // update the user password
     $user->password = User::encryptPassword($newPassword, $user->salt);
     if (!$user->save()) {
         throw new ServerErrorHttpException("Save user failed!");
     }
     Validation::deleteAll(['userId' => $userId]);
     return ['status' => 'ok'];
 }
示例#7
0
 public function actionOfflineExchange()
 {
     $params = $this->getParams();
     if (empty($params['goods']) || empty($params['memberId']) || !isset($params['usedScore']) || empty($params['address']) || empty($params['receiveMode'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $userId = $this->getUserId();
     $user = User::findByPk($userId);
     $user = ['id' => $user->_id, 'name' => $user->name];
     if ($params['usedScore'] < 0) {
         throw new BadRequestHttpException(Yii::t('common', 'data_error'));
     }
     $member = Member::findByPk(new \MongoId($params['memberId']));
     if (empty($member) || $member->isDisabled) {
         throw new InvalidParameterException(Yii::t('member', 'invalid_member_id'));
     }
     $goodsExchangeMap = [];
     $goodsIds = [];
     foreach ($params['goods'] as $item) {
         if ($item['count'] <= 0) {
             throw new BadRequestHttpException(Yii::t('common', 'data_error'));
         }
         $goodsExchangeMap[$item['id']] = $item['count'];
         $goodsIds[] = new \MongoId($item['id']);
     }
     $allExchangeGoods = Goods::getByIds($goodsIds);
     if (count($allExchangeGoods) != count($goodsIds)) {
         throw new InvalidParameterException(Yii::t('product', 'product_deleted'));
     }
     $usedScore = $params['usedScore'];
     $expectedScore = 0;
     $exchanges = [];
     foreach ($allExchangeGoods as $goods) {
         $exchangeCount = $goodsExchangeMap[(string) $goods->_id];
         if ($goods->total === 0) {
             throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_sold_out')]);
         } else {
             if (!empty($goods->total) && $exchangeCount > $goods->total) {
                 throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_not_enough')]);
             }
         }
         $expectedScore += $goods->score * $exchangeCount;
         $exchanges[] = ['goods' => $goods, 'count' => $exchangeCount];
     }
     $params['expectedScore'] = $expectedScore;
     if ($member->score < $usedScore) {
         throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough'));
     }
     $successExchange = [];
     foreach ($exchanges as $exchangeItem) {
         $goods = $exchangeItem['goods'];
         $count = $exchangeItem['count'];
         $goodsCondition = ['_id' => $goods->_id];
         $goodsModifier = ['$inc' => ['usedCount' => $count]];
         $goodsRollbackModifier = ['$inc' => ['usedCount' => 0 - $count]];
         if ($goods->total !== '') {
             $goodsCondition['total'] = ['$gte' => $count];
             $goodsModifier['$inc']['total'] = 0 - $count;
             $goodsRollbackModifier['$inc']['total'] = $count;
         }
         $goodsUpdatedCount = Goods::updateAll($goodsModifier, $goodsCondition);
         if ($goodsUpdatedCount !== 1) {
             $this->_rollBackUsedCount($successExchange);
             throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_not_enough')]);
         } else {
             $goodsId = (string) $goods->_id;
             $successExchange[$goodsId] = $goodsRollbackModifier;
         }
     }
     $memberUpdatedCount = Member::updateAll(['$inc' => ['score' => 0 - $usedScore]], ['_id' => $member->_id, 'score' => ['$gte' => $usedScore]]);
     if ($memberUpdatedCount === 1) {
         $this->_saveLog($member, $exchanges, $params, $user);
         if (!empty($params['useWebhook'])) {
             $eventData = ['type' => Webhook::EVENT_PRODUCT_REDEEMED, 'member_id' => $params['memberId'], 'products' => $params['goods'], 'address' => $params['address'], 'postcode' => $params['postcode'], 'used_score' => $params['usedScore'], 'origin' => Member::PORTAL, 'account_id' => (string) $member->accountId, 'created_at' => TimeUtil::msTime2String(time() * TimeUtil::MILLI_OF_SECONDS, \DateTime::ATOM)];
             Yii::$app->webhook->triggerEvent($eventData);
         }
     } else {
         $this->_rollBackUsedCount($successExchange);
         throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough'));
     }
 }