Пример #1
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);
 }
Пример #2
0
 /**
  * Clear card expired time if account's card all are auto upgrade
  */
 public function actionClearCardExpiredTime()
 {
     $accounts = Account::findAll(['enabledMods' => 'member']);
     foreach ($accounts as $account) {
         $unAutoUpgradeCards = MemberShipCard::findAll(['isAutoUpgrade' => false, 'accountId' => $account->_id]);
         if (empty($unAutoUpgradeCards)) {
             Member::updateAll(['$unset' => ['cardExpiredAt' => true]], ['accountId' => $account->_id]);
         }
     }
 }
Пример #3
0
 /**
  * Reward shake score
  * @param MongoId $memberId
  * @param int $score
  */
 public function shakeScore($memberId, $score, $channelInfo)
 {
     ModelMember::updateAll(['$inc' => ['score' => $score, 'totalScore' => $score, 'totalScoreAfterZeroed' => $score]], ['_id' => $memberId]);
     $scoreHistory = new ScoreHistory();
     $scoreHistory->assigner = ScoreHistory::ASSIGNER_SHAKE_SCORE;
     $scoreHistory->increment = $score;
     $scoreHistory->memberId = $memberId;
     $scoreHistory->brief = ScoreHistory::ASSIGNER_SHAKE_SCORE;
     $scoreHistory->description = '';
     $scoreHistory->channel = $channelInfo;
     $scoreHistory->user = null;
     $scoreHistory->accountId = $this->accountId;
     if (!$scoreHistory->save()) {
         LogUtil::error(['message' => 'Failed to save the history for unknown problem', 'scoreHistory' => $scoreHistory->toArray()], 'resque');
     }
 }
 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;
 }
Пример #5
0
 /**
  * Follower bind to be a member.
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/mobile/bind<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for follower bind.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     mobile: string<br/>
  *     openId: string<br/>
  *     unionId: string<br/>
  *     channelId: string<br/>
  *     captcha: string<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *  "message": "OK",
  *  "data": "http://wm.com?memberId=55d29e86d6f97f72618b4569"
  * </pre>
  */
 public function actionBind()
 {
     //set language zh_cn when bind
     Yii::$app->language = LanguageUtil::LANGUAGE_ZH;
     $params = $this->getParams();
     if (empty($params['mobile']) || empty($params['openId']) || empty($params['channelId']) || empty($params['captcha'])) {
         throw new BadRequestHttpException('missing param');
     }
     $isTest = false;
     if ($params['mobile'] == self::TEST_PHONE && $params['captcha'] == self::TEST_CODE) {
         $isTest = true;
     } else {
         $this->attachBehavior('CaptchaBehavior', new CaptchaBehavior());
         $this->checkCaptcha($params['mobile'], $params['captcha']);
     }
     //get accountId
     $openId = $params['openId'];
     $channel = Channel::getEnableByChannelId($params['channelId']);
     $origin = $channel->origin;
     $accountId = $channel->accountId;
     //create accessToken
     $token = Token::createForMobile($accountId);
     if (empty($token['accessToken'])) {
         throw new ServerErrorHttpException('Failed to create token for unknown reason.');
     }
     $accessToken = $token['accessToken'];
     $this->setAccessToken($accessToken);
     //if member has bind
     if (empty($params['unionId'])) {
         $member = Member::getByOpenId($openId);
     } else {
         $unionId = $params['unionId'];
         $member = Member::getByUnionid($unionId);
     }
     if (!empty($member)) {
         $memberId = (string) $member->_id;
         $url = $this->buildBindRedirect($memberId, $params);
         return ['message' => 'OK', 'data' => $url];
     }
     //check mobile has been bind
     $member = Member::getByMobile($params['mobile'], new \MongoId($accountId));
     if (!empty($member)) {
         throw new InvalidParameterException(['phone' => Yii::t('common', 'phone_has_been_bound')]);
     }
     $follower = Yii::$app->weConnect->getFollowerByOriginId($openId, $params['channelId']);
     $originScene = empty($follower['firstSubscribeSource']) ? '' : $follower['firstSubscribeSource'];
     //init avatar and location
     $avatar = !empty($follower['headerImgUrl']) ? $follower['headerImgUrl'] : Yii::$app->params['defaultAvatar'];
     $location = [];
     !empty($follower['city']) ? $location['city'] = $follower['city'] : null;
     !empty($follower['province']) ? $location['province'] = $follower['province'] : null;
     !empty($follower['country']) ? $location['country'] = $follower['country'] : null;
     LogUtil::info(['message' => 'get follower info', 'follower' => $follower], 'channel');
     //init member properties
     $memberProperties = MemberProperty::getByAccount($accountId);
     $propertyMobile = [];
     $propertyGender = [];
     $propertyName = [];
     $properties = [];
     foreach ($memberProperties as $memberProperty) {
         if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_MOBILE) {
             $propertyMobile['id'] = $memberProperty['_id'];
             $propertyMobile['name'] = $memberProperty['name'];
             $propertyMobile['value'] = $params['mobile'];
             $properties[] = $propertyMobile;
         }
         if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_GENDER) {
             $propertyGender['id'] = $memberProperty['_id'];
             $propertyGender['name'] = $memberProperty['name'];
             $propertyGender['value'] = !empty($follower['gender']) ? strtolower($follower['gender']) : 'male';
             $properties[] = $propertyGender;
         }
         if ($memberProperty['name'] == Member::DEFAULT_PROPERTIES_NAME) {
             $propertyName['id'] = $memberProperty['_id'];
             $propertyName['name'] = $memberProperty['name'];
             $propertyName['value'] = $follower['nickname'];
             $properties[] = $propertyName;
         }
     }
     //get default card
     $card = MemberShipCard::getDefault($accountId);
     $memberId = new \MongoId();
     $memberAttribute = ['$set' => ['_id' => $memberId, 'avatar' => $avatar, 'cardId' => $card['_id'], 'location' => $location, 'score' => 0, 'socialAccountId' => $params['channelId'], 'properties' => $properties, 'openId' => $openId, 'origin' => $origin, 'originScene' => $originScene, 'unionId' => empty($unionId) ? '' : $unionId, 'accountId' => $accountId, 'cardNumber' => Member::generateCardNumber($card['_id']), 'cardProvideTime' => new \MongoDate(), 'createdAt' => new \MongoDate(), 'socials' => [], 'isDeleted' => false]];
     if (!$isTest) {
         $result = Member::updateAll($memberAttribute, ['openId' => $openId], ['upsert' => true]);
     } else {
         $result = true;
     }
     if ($result) {
         // reword score first bind card
         $this->attachBehavior('MemberBehavior', new MemberBehavior());
         $this->updateItemByScoreRule(Member::findByPk($memberId));
         Yii::$app->qrcode->create(Yii::$app->request->hostInfo, Qrcode::TYPE_MEMBER, $memberId, $accountId);
         $memberId = (string) $memberId;
         $url = $this->buildBindRedirect($memberId, $params);
         return ['message' => 'OK', 'data' => $url];
     } else {
         LogUtil::error(['error' => 'member save error', 'params' => Json::encode($member)], 'member');
         throw new ServerErrorHttpException("bind fail");
     }
 }
Пример #6
0
 public static function renameTag($accountId, $name, $newName)
 {
     //add new tag to member
     Member::updateAll(['$addToSet' => ['tags' => $newName]], ['accountId' => $accountId, 'tags' => $name]);
     //remove old tags from member
     Member::updateAll(['$pull' => ['tags' => $name]], ['accountId' => $accountId, 'tags' => $name]);
 }
 /**
  * This function is just for fix error promotionCode redeem data
  * @param MongoId $accountId
  * @param MongoId $memberId
  * @param Array $codes
  * @return boolean, true, if there is no error data
  */
 private function fixData($accountId, $memberId, $codes)
 {
     $condition = ['accountId' => $accountId, 'member.id' => $memberId, 'code' => ['$in' => $codes]];
     $pipeline = [['$match' => $condition], ['$group' => ['_id' => ['campaignId' => '$campaignId', 'code' => '$code'], 'count' => ['$sum' => 1]]], ['$match' => ['count' => ['$gt' => 1]]]];
     $stats = CampaignLog::getCollection()->aggregate($pipeline);
     if (empty($stats)) {
         return true;
     }
     $logCondition = ['accountId' => $accountId, 'member.id' => $memberId];
     $failedMessages = [];
     $successMessages = [];
     foreach ($stats as $stat) {
         $code = $stat['_id']['code'];
         //get campaign log
         $logCondition = array_merge($logCondition, $stat['_id']);
         $logs = CampaignLog::find()->where($logCondition)->orderBy(['createdAt' => SORT_ASC])->all();
         $memberId = $logs[0]['member']['id'];
         $productName = $logs[0]['productName'];
         //get score history
         $description = $productName . ' ' . $code;
         $scoreHistoryCondition = ['memberId' => $memberId, 'brief' => ScoreHistory::ASSIGNER_EXCHANGE_PROMOTION_CODE, 'description' => $description];
         $scoreHistorys = ScoreHistory::find()->where($scoreHistoryCondition)->orderBy(['createdAt' => SORT_ASC])->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 not enough, log continue
         if ($member->score <= $deduct || $member->totalScore <= $deduct || $member->totalScoreAfterZeroed <= $deduct) {
             $failedMessages[] = ['Failed' => 'Member score not enough', 'member' => $member->toArray(), 'deduct' => $deduct];
             continue;
         }
         //fix member score
         $deductScore = 0 - $deduct;
         Member::updateAll(['$inc' => ['score' => $deductScore, 'totalScore' => $deductScore, 'totalScoreAfterZeroed' => $deductScore]], ['_id' => $memberId]);
         //remove scorehistory
         ScoreHistory::deleteAll(['_id' => ['$in' => $removeScoreHistoryIds]]);
         //remove campaignlog
         $logIds = ArrayHelper::getColumn($logs, '_id');
         $keepLogId = $logIds[0];
         unset($logIds[0]);
         CampaignLog::deleteAll(['_id' => ['$in' => array_values($logIds)]]);
         $successMessages[] = ['Success' => $productName . ' ' . $code . ' ' . $stat['count'], 'memberId' => $memberId, 'deduct' => $deduct];
     }
     LogUtil::error(['Failed' => $failedMessages, 'Success' => $successMessages], 'fix-campaign-data');
 }
 /**
  * Delete member property
  * <b>Request Type: </b>DELETE<br/>
  * <b>Request Endpoint: </b>http://{{server-domain}}/api/common/member-property/{id}<br/>
  * <b>Summary</b> This api is for delete property for member.
  */
 public function actionDelete($id)
 {
     $propertyId = new \MongoId($id);
     if (MemberProperty::deleteByPk($propertyId, ['isDefault' => false])) {
         //update member
         Member::updateAll(['$pull' => ['properties' => ['id' => $propertyId]]]);
         Yii::$app->getResponse()->setStatusCode(204);
         return;
     }
     throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');
 }
Пример #9
0
 /**
  * Provide card
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/member/card/provide-card<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for provide card.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     cardId: string<br/>
  *     cardNumbers: Array, card number<br/>
  *     names: Array
  *     tags: Array<br/>
  *     cardExpiredAt: timestamp<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     message:
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  *  {"message" : "OK"}
  * </pre>
  */
 public function actionProvideCard()
 {
     $params = $this->getParams();
     $accountId = $this->getAccountId();
     $params['accountId'] = $accountId . '';
     if (empty($params['cardId'])) {
         throw new BadRequestHttpException('param error');
     }
     if (empty($params['cardExpiredAt'])) {
         throw new InvalidParameterException(['schedule-picker' => \Yii::t('common', 'required_filed')]);
     }
     $cardId = new \MongoId($params['cardId']);
     $card = MemberShipCard::findByPk($cardId);
     if (empty($card)) {
         throw new BadRequestHttpException(\Yii::t('member', 'no_card_find'));
     }
     if ($card->isAutoUpgrade) {
         throw new InvalidParameterException(Yii::t('member', 'error_issue_auto_card'));
     }
     if ($params['cardExpiredAt'] < TimeUtil::msTime()) {
         throw new InvalidParameterException(['schedule-picker' => \Yii::t('member', 'not_less_than_current')]);
     }
     $members = [];
     if (!empty($params['cardNumbers']) && is_array($params['cardNumbers'])) {
         $members = Member::getByCardNumbers($params['cardNumbers']);
         if (empty($members)) {
             throw new InvalidParameterException(['cardNumber' => \Yii::t('member', 'no_member_find')]);
         }
     } else {
         if (!empty($params['names']) && is_array($params['names'])) {
             $members = Member::getByNames($params['names']);
             if (empty($members)) {
                 throw new InvalidParameterException(['memberNames' => \Yii::t('member', 'no_member_find')]);
             }
         } else {
             if (!empty($params['tags']) && is_array($params['tags'])) {
                 $members = Member::getByTags($params['tags']);
                 if (empty($members)) {
                     throw new InvalidParameterException(['memberTags' => \Yii::t('member', 'no_member_find')]);
                 }
             }
         }
     }
     $memberIds = Member::getIdList($members);
     Member::updateAll(['$set' => ['cardId' => $cardId, 'cardExpiredAt' => $params['cardExpiredAt']]], ['_id' => ['$in' => $memberIds]]);
     return ['message' => 'OK'];
 }
Пример #10
0
 /**
  * @param $scoreAdd, int
  * @param $memberId, mongoId
  */
 public static function addMemberScore($scoreAdded, $memberId)
 {
     $scoreAdded = intval($scoreAdded);
     $data = ['$inc' => ['score' => $scoreAdded, 'totalScore' => $scoreAdded, 'totalScoreAfterZeroed' => $scoreAdded]];
     Member::updateAll($data, ['_id' => $memberId]);
 }
Пример #11
0
 public function perform()
 {
     # Run task
     $args = $this->args;
     //the key for wrong number for store in redis
     $wrongKey = self::MEMBER_WRONG;
     switch ($args['type']) {
         case self::JOB_DELETE_REDIS_CODE:
             if (!isset($args['filename']) || !isset($args['accountId'])) {
                 ResqueUtil::log(['error' => 'missing param', 'param' => $args]);
                 return false;
             }
             $redis = \Yii::$app->cache->redis;
             $cacheSetInsert = self::SET_HEAD_INSERT . md5($args['accountId'] . "_" . $args['fileName']);
             $cacheSetUpdate = self::SET_HEAD_UPDATE . md5($args['accountId'] . "_" . $args['fileName']);
             $redis->del($cacheSetInsert);
             $redis->del($cacheSetUpdate);
             unset($commonKey, $cacheTotalKey, $count);
             break;
         case self::JOB_INSERT:
             if (!isset($args['accountId']) || empty($args['filename']) || empty($args['hostInfo'])) {
                 ResqueUtil::log(['error' => 'missing params', 'param' => $args]);
             }
             $redis = Yii::$app->cache->redis;
             $cacheKey = $args['accountId'] . "_" . $args['filename'];
             $createdAt = new \MongoDate(time());
             $redis->expire($cacheKey, self::EXPIRE);
             $cacheSetInsert = self::SET_HEAD_INSERT . md5($cacheKey);
             $cacheSetUpdate = self::SET_HEAD_UPDATE . md5($cacheKey);
             // status
             $cacheSetLackProperties = self::MEMBER_IMPORT_NO_PROPERTY . md5($cacheKey);
             // get total of excel.
             $totalInsert = $redis->scard($cacheSetInsert);
             $totalUpdate = $redis->scard($cacheSetUpdate);
             // batch insert member.
             $memberInsert = [];
             $keyInsert = $redis->smembers($cacheSetInsert);
             // update member.
             $keyUpdate = $redis->smembers($cacheSetUpdate);
             // unserialize.
             if (count($keyInsert) > 0) {
                 $defaultCard = MemberShipCard::getDefault(new MongoId($args['accountId']));
                 if (empty($defaultCard)) {
                     ResqueUtil::log('Lack of default MemberShip Card');
                     // 0
                     $redis->Hset($cacheSetLackProperties, $wrongKey, self::MEMBER_NO_DEFAULT_PROPERTIES);
                     return false;
                 }
                 $cardId = $defaultCard->_id;
                 $origin = Member::PORTAL;
                 $tels = [];
                 for ($rowIndex = 0; $rowIndex < $totalInsert; $rowIndex++) {
                     $memberKey = unserialize($keyInsert[$rowIndex]);
                     $cardNumber = Member::generateCardNumber();
                     $properties = [];
                     $memberTag = [];
                     foreach ($memberKey[0] as $item) {
                         if (!empty($item['name'])) {
                             if ($item['name'] == Member::DEFAULT_PROPERTIES_MOBILE) {
                                 $telItem = $item;
                             }
                             $properties[] = $item;
                         } else {
                             $memberTag[] = $item['tags'];
                         }
                     }
                     $tels[] = $telItem;
                     $memberMessage = ["properties" => $properties, "tags" => $memberTag, "cardId" => $cardId, "origin" => $origin, "cardNumber" => empty($cardNumber) ? 0 : $cardNumber, "location" => ["country" => "", "province" => "", "city" => "", "detail" => ""], "avatar" => Yii::$app->params['defaultAvatar'], "score" => 0, "totalScore" => 0, "socials" => [], "qrcodeViewed" => false, "isDisabled" => false, "totalScoreAfterZeroed" => 0, "accountId" => new MongoId($args['accountId']), "cardProvideTime" => new \MongoDate()];
                     $memberInsert[] = $memberMessage;
                 }
                 // batch insert member.
                 $insertMemberResult = Member::batchInsert($memberInsert);
                 if ($insertMemberResult) {
                     ResqueUtil::log(['ok' => 'Batch insert member is success', 'data' => $memberInsert]);
                 } else {
                     ResqueUtil::log(['error' => 'Batch insert member is fail', 'data' => $memberInsert]);
                     $redis->Hset($cacheSetLackProperties, $wrongKey, self::MEMBER_NO_DEFAULT_PROPERTIES);
                 }
                 //create qrcode.
                 foreach ($tels as $param) {
                     $member = Member::findOne(['properties' => ['$elemMatch' => ['name' => $param['name'], 'value' => $param['value']]], 'accountId' => new MongoId($args['accountId'])]);
                     Member::webhookEvent($member);
                     MemberLogs::record($member->_id, new MongoId($args['accountId']), MemberLogs::OPERATION_VIEWED);
                     if (!defined('KLP') || !KLP) {
                         $a = Yii::$app->qrcode->create($args['hostInfo'], Qrcode::TYPE_MEMBER, $member->_id, new MongoId($args['accountId']));
                     }
                     Member::birthdayScore($member);
                 }
             }
             // update member.
             if (count($keyUpdate) > 0) {
                 for ($rowIndex = 0; $rowIndex < $totalUpdate; $rowIndex++) {
                     $memberKey = unserialize($keyUpdate[$rowIndex]);
                     $memberProperty = $memberKey[0];
                     $condition = [];
                     $updateData = [];
                     $memberUpdate = [];
                     $memberTag = [];
                     foreach ($memberProperty as $member) {
                         if (!empty($member['name'])) {
                             if ($member['name'] == Member::DEFAULT_PROPERTIES_MOBILE) {
                                 $condition = ["properties.value" => $member['value']];
                             }
                             $memberUpdate[] = $member;
                         } else {
                             $memberTag[] = $member['tags'];
                         }
                     }
                     $updateData[] = ["properties" => $memberUpdate, "tags" => $memberTag];
                     $updateMemberResult = Member::updateAll(['$set' => $updateData[0]], $condition);
                     if ($updateMemberResult) {
                         ResqueUtil::log(['ok' => 'Update member is success', 'data' => $memberInsert]);
                     } else {
                         ResqueUtil::log(['error' => 'Update member is fail', 'data' => $memberInsert]);
                         $redis->Hset($cacheSetLackProperties, $wrongKey, self::MEMBER_NO_DEFAULT_PROPERTIES);
                     }
                 }
             }
             break;
         default:
             break;
     }
 }
Пример #12
0
 public function actionExchange()
 {
     $params = $this->getParams();
     if (empty($params['memberId']) || empty($params['goodsId']) || empty($params['channelId']) || empty($params['receiveMode']) || empty($params['phone']) || empty($params['captcha']) || !isset($params['count']) || empty($params['address'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     if ($params['count'] < 0) {
         throw new BadRequestHttpException(Yii::t('common', 'data_error'));
     }
     $this->attachBehavior('CaptchaBehavior', new CaptchaBehavior());
     $this->checkCaptcha($params['phone'], $params['captcha']);
     $member = Member::findByPk(new \MongoId($params['memberId']));
     if (empty($member) || $member->isDisabled) {
         throw new BadRequestHttpException(Yii::t('member', 'invalid_member_id'));
     }
     $goods = Goods::findByPk(new \MongoId($params['goodsId']));
     if (empty($goods)) {
         throw new BadRequestHttpException(Yii::t('product', 'invalid_goods_id'));
     }
     if ((string) $goods->accountId !== (string) $member->accountId) {
         throw new BadRequestHttpException(Yii::t('product', 'different_account'));
     }
     if ($goods->status === Goods::STATUS_OFF) {
         throw new InvalidParameterException(Yii::t('product', 'goods_not_on_shelves'));
     }
     if (!is_array($goods->receiveModes) || !in_array($params['receiveMode'], $goods->receiveModes)) {
         throw new InvalidParameterException(Yii::t('product', 'receive_mode_invalid'));
     }
     $usedScore = $goods->score * $params['count'];
     $params['usedScore'] = $usedScore;
     $params['expectedScore'] = $usedScore;
     if ($member->score < $usedScore) {
         throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough'));
     }
     //if $goods->total is '', means no limit
     if ($goods->total === 0) {
         throw new InvalidParameterException(Yii::t('product', 'goods_sold_out'));
     }
     if (!empty($goods->total) && $params['count'] > $goods->total) {
         throw new InvalidParameterException(Yii::t('product', 'goods_not_enough'));
     }
     $goodsCondition = ['_id' => $goods->_id];
     $goodsModifier = ['$inc' => ['usedCount' => $params['count']]];
     $goodsRollbackModifier = ['$inc' => ['usedCount' => 0 - $params['count']]];
     if ($goods->total !== '') {
         $goodsCondition['total'] = ['$gte' => $params['count']];
         $goodsModifier['$inc']['total'] = 0 - $params['count'];
         $goodsRollbackModifier['$inc']['total'] = $params['count'];
     }
     $goodsUpdatedCount = Goods::updateAll($goodsModifier, $goodsCondition);
     if ($goodsUpdatedCount === 1) {
         $memberUpdatedCount = Member::updateAll(['$inc' => ['score' => 0 - $usedScore]], ['_id' => $member->_id, 'score' => ['$gte' => $usedScore]]);
         if ($memberUpdatedCount === 1) {
             $exchanges = [['goods' => $goods, 'count' => $params['count']]];
             if ($this->_saveLog($member, $exchanges, $params)) {
                 return ['message' => 'OK', 'data' => null];
             } else {
                 Goods::updateAll($goodsRollbackModifier, ['_id' => $goods->_id]);
                 Member::updateAll(['$inc' => ['score' => $usedScore]], ['_id' => $member->_id]);
                 LogUtil::error(['message info' => 'save exchange log error', 'params' => $params, 'goods' => $goods->toArray(), 'member' => $member->toArray()], 'product');
             }
         } else {
             Goods::updateAll($goodsRollbackModifier, ['_id' => $goods->_id]);
             throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough'));
         }
     } else {
         throw new InvalidParameterException(Yii::t('product', 'goods_sold_out'));
     }
 }
Пример #13
0
 public function actionCheckQrcodeHelp()
 {
     $memberId = $this->getParams('memberId');
     if (empty($memberId)) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     Member::updateAll(['$set' => ['qrcodeViewed' => true]], ['_id' => new \MongoId($memberId)]);
     return ['message' => 'OK', 'data' => ''];
 }