/** * receive copon through oauth recall this api */ public function actionReceivedCoupon() { $params = $this->getQuery(); $defaultId = -1; $message = ''; if (empty($params['couponId']) || empty($params['memberId']) || empty($params['channelId'])) { LogUtil::error(['message' => 'missing params when receive coupon', 'params' => $params], 'product'); exit; } $number = !empty($params['number']) && intval($params['number']) > 1 ? intval($params['number']) : 1; $couponId = new MongoId($params['couponId']); $coupon = Coupon::findByPk($couponId); if (empty($coupon)) { LogUtil::error(['message' => 'invalid couponIdi when receive coupon', 'params' => $params], 'product'); exit; } $memberId = new MongoId($params['memberId']); $member = Member::findByPk($memberId); if (empty($member)) { LogUtil::error(['message' => 'invalid memberId when receive coupon', 'params' => $params], 'product'); exit; } $args = ['mainDomain' => Yii::$app->request->hostInfo . '/mobile/product/coupon', 'couponId' => $params['couponId'], 'id' => $defaultId, 'memberId' => $params['memberId'], 'result' => 'fail', 'channelId' => $params['channelId']]; //check the total if ($coupon->total < $number) { $message = Yii::t('product', 'coupon_no_exists'); return $this->_redirectCouponDetail($message, $args, $params); } //check limit $couponNumber = CouponLog::count(['couponId' => $couponId, 'member.id' => $memberId]); if ($couponNumber >= $coupon->limit) { $message = Yii::t('product', 'coupon_is_received'); return $this->_redirectCouponDetail($message, $args, $params); } //check the time $current = new MongoDate(strtotime(date('Y-m-d'))); if ($coupon->time['type'] == Coupon::COUPON_RELATIVE_TIME && $coupon->time['endTime'] < $current) { $message = Yii::t('product', 'coupon_expired'); return $this->_redirectCouponDetail($message, $args, $params); } //receive coupon $where = ['total' => ['$gte' => $number], '_id' => $couponId]; $number -= 2 * $number; if (Coupon::updateAll(['$inc' => ['total' => $number]], $where)) { $membershipDiscount = MembershipDiscount::transformMembershipDiscount($coupon, $member); if (false === $membershipDiscount->save()) { //to avoid the error show to user LogUtil::error(['message' => 'Failed to save couponLog error:' . $membershipDiscount->getErrors()], 'product'); $message = Yii::t('common', 'save_fail'); return $this->_redirectCouponDetail($message, $args, $params); } $args['id'] = isset($membershipDiscount->_id) ? $membershipDiscount->_id : $defaultId; $args['result'] = 'success'; } else { $message = '优惠券库存不足!'; } return $this->_redirectCouponDetail($message, $args, $params); }
public function actionAddress($id) { $member = Member::findByPk(new \MongoId($id)); if (empty($member)) { throw new InvalidParameterException(Yii::t('member', 'no_member_find')); } $goodsExchangeLog = GoodsExchangeLog::getLastExpressByMember($member->_id); $address = empty($goodsExchangeLog->address) ? '' : $goodsExchangeLog->address; $postcode = empty($goodsExchangeLog->postcode) ? '' : $goodsExchangeLog->postcode; return ['address' => $address, 'postcode' => $postcode]; }
private function preProcessDrawMembers($condition, $accountId) { $rows = array(); $scores = EarlybirdSmsUtil::getExchangeGoodsScore($condition['startDate'], $condition['endDate'], $accountId); asort($scores); foreach ($scores as $key => $value) { $row = array(); if (abs($value) >= $condition['pointsThree']) { $member = Member::findByPk(new \MongoId($key)); if (!$member->isDeleted) { $row['id'] = $key; $row['exchangeGoodsScore'] = abs($value); $row['cardNumber'] = $member->cardNumber; //拿到符合一等奖条件的人 if (abs($value) >= $condition['pointsOne']) { //eg: points>=2000 $row['prizeName'] = $condition['prizeNameOne']; $row['prizeLevel'] = '一等獎資格'; } //拿到符合二等奖条件的人 if (abs($value) < $condition['pointsOne'] && abs($value) >= $condition['pointsTwo']) { //eg: 1000<=points<2000 $row['prizeName'] = $condition['prizeNameTwo']; $row['prizeLevel'] = '二等獎資格'; } //拿到符合三等奖条件的人 if (abs($value) < $condition['pointsTwo'] && abs($value) >= $condition['pointsThree']) { //eg: 200<=points<1000 $row['prizeName'] = $condition['prizeNameThree']; $row['prizeLevel'] = '三等獎資格'; } if (!empty($member->properties)) { foreach ($member->properties as $property) { if ($property['name'] == 'tel') { $row['mobile'] = "'" . $property['value']; } if ($property['name'] == 'name') { $row['name'] = $property['value']; } } } } } $rows[] = $row; unset($row, $member); } return $rows; }
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; }
public function actionIndex() { $params = $this->getQuery(); if (empty($params['memberId'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } //get members openIds $member = Member::findByPk(new MongoId($params['memberId'])); $openIds = empty($member->socials) ? [] : ArrayHelper::getColumn($member->socials, 'openId'); $openIds[] = $member->openId; //get lastChatDate $lastConversation = ChatConversation::getLastByOpenIds($openIds); $lastChatDate = empty($lastConversation) ? '' : $lastConversation->date; //get conversations $params['openIds'] = $openIds; $accountId = $this->getAccountId(); $conversations = ChatConversation::search($params, $accountId); $result = $this->serializeData($conversations); $result['lastChatDate'] = $lastChatDate; return $result; }
/** * 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'); }
/** * Get member by birth according score rule trigger time * @param string $triggerTime * @return member list */ private function getMembers($accountId, $triggerTime, $memberId = null) { $timeCondition = $this->getTimeCondition($triggerTime); $memberIds = []; if (!empty($timeCondition['timeFrom']) && !empty($timeCondition['timeTo'])) { if (empty($memberId)) { $members = Member::searchByBirth($timeCondition['timeFrom'], $timeCondition['timeTo'], $accountId); $memberIds = Member::getIdList($members); } else { $condition = ['birth' => ['$gte' => $timeCondition['timeFrom'], '$lte' => $timeCondition['timeTo']]]; $member = Member::findByPk($memberId, $condition); if (!empty($member)) { $memberIds = [$member->_id]; } } } return $memberIds; }
public function actionMerge() { $params = $this->getParams(); if (empty($params['main']) || empty($params['others'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } if (!is_array($params['others']) || in_array($params['main'], $params['others'])) { throw new BadRequestHttpException(Yii::t('common', 'data_error')); } $accountId = $this->getAccountId(); $mainMember = Member::findByPk(new \MongoId($params['main']), ['accountId' => $accountId]); if (empty($mainMember)) { throw new InvalidParameterException(Yii::t('member', 'no_member_find')); } //get mongoIds $otherMemberIds = []; foreach ($params['others'] as $otherId) { $otherMemberIds[] = new \MongoId($otherId); } $otherMembers = Member::findAll(['_id' => ['$in' => $otherMemberIds], 'accountId' => $accountId]); if (empty($otherMembers) || count($otherMembers) != count($params['others'])) { throw new InvalidParameterException(Yii::t('member', 'no_member_find')); } $mainProperties = []; $mainPropertyIds = []; foreach ($mainMember->properties as $mainProperty) { if (!empty($mainProperty['value'])) { $mainPropertyIds[] = $mainProperty['id']; $mainProperties[] = $mainProperty; } } $mainMemberLocation = $mainMember->location; $otherMemberLocation = []; $newMemberTag = empty($mainMember->tags) ? [] : $mainMember->tags; foreach ($otherMembers as $otherMember) { $mainMember->score += $otherMember->score; $mainMember->totalScore += $otherMember->totalScore; $mainMember->totalScoreAfterZeroed += $otherMember->totalScoreAfterZeroed; $newMemberTag = array_merge($newMemberTag, empty($otherMember->tags) ? [] : $otherMember->tags); $location = $otherMember->location; if (empty($otherMemberLocation['country']) && !empty($location['country'])) { $otherMemberLocation = $location; } foreach ($otherMember->properties as $otherProperty) { if (!in_array($otherProperty['id'], $mainPropertyIds) && !empty($otherProperty['value'])) { $mainPropertyIds[] = $otherProperty['id']; $mainProperties[] = $otherProperty; } } } $mainMember->properties = $mainProperties; $mainMember->tags = array_values(array_unique($newMemberTag)); if (empty($mainMemberLocation['country']) && !empty($otherMemberLocation)) { $mainMember->location = $otherMemberLocation; } $updateMember = $mainMember->save(false); $deleteMember = Member::deleteAll(['_id' => ['$in' => $otherMemberIds]]); if ($updateMember && $deleteMember) { $mainMember->upgradeCard(); $jobArgs = ['mainMember' => serialize($mainMember), 'otherMemberIds' => serialize($otherMemberIds)]; Yii::$app->job->create('backend\\modules\\member\\job\\MergeMember', $jobArgs); return ['message' => 'OK', 'data' => '']; } else { throw new ServerErrorHttpException('Merge member fail'); } }
/** * @param $condition array (抽奖设置的数据) * @return array (eg: [['mobile'=>'0933431025','content'=>'..您已獲得7-11超市200商品兌換劵抽獎資格..'], ...] ) */ public static function getSmsForMemberCanDraw($condition) { $members = self::getMemberCanDraw($condition); $smsArr = array(); foreach ($members as $key => $value) { $memberId = new \MongoId($key); $member = Member::findByPk($memberId); if (!empty($member->properties)) { $mobile = ''; $name = ''; foreach ($member->properties as $property) { if ($property['name'] == 'tel') { $mobile = $property['value']; } if ($property['name'] == 'name') { $name = $property['value']; } } if (!empty($mobile)) { $smsContent = self::EARLY_BIRD_FOUR_TEMPLATE; $smsContent = str_replace("%username%", $name, $smsContent); $smsContent = str_replace("%prizeName%", $value, $smsContent); $sms['mobile'] = $mobile; $sms['content'] = $smsContent; $smsArr[] = $sms; unset($memberId, $member, $mobile, $name, $smsContent, $sms); } } } return $smsArr; }
public function actionCnyPromotion() { $params = $this->getParams('data', null); $accountId = new \MongoId($params['account_id']); if (empty($params) || empty($params['member_id']) || empty($params['type']) || empty($params['score']) || empty($accountId)) { throw new BadRequestHttpException("params are missing."); } if ($params['type'] != 'promotion_code_redeemed') { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['message' => 'Not promotion_code_redeemed']; } //get memberInfo $member = Member::findByPk(new \MongoId($params['member_id'])); $memberInfo = ['addScore' => $params['score'], 'id' => new \MongoId($params['member_id']), 'score' => $member->score]; if (!empty($member->properties)) { foreach ($member->properties as $propertie) { if ($propertie['name'] == 'name') { $memberInfo['name'] = $propertie['value']; } if ($propertie['name'] == 'tel') { $memberInfo['mobile'] = $propertie['value']; } } } unset($member, $params); // get CNY Info $activity = Activity::findOne(['name' => 'cny', 'accountId' => $accountId]); if (empty($activity)) { throw new ServerErrorHttpException("Get CNY information failed or No CNY"); } $needPoints = $activity->luckyDrawInfo['needPoints']; $drawDates = $activity->luckyDrawInfo['drawDate']; $conditionForOdds = ['member.id' => $memberInfo['id'], 'redeemTime' => ['$gte' => $activity->startDate, '$lte' => $activity->endDate]]; unset($activity); // get day // sort($drawDates); // $currentDate = new \mongoDate(); // $targetDate = null; // $day = 0; // foreach ($drawDates as $drawDate) { // if ($drawDate > $currentDate) { // $targetDate = $drawDate; // break; // } // } // if (!empty($targetDate)) { // $offsetTime = MongodbUtil::MongoDate2msTimeStamp($targetDate) - MongodbUtil::MongoDate2msTimeStamp($currentDate); // $day = ceil($offsetTime / (1000 * 60 * 60 * 24)); // unset($drawDates, $currentDate, $targetDate); // } // get odds $oddsCount = 0; $checkDouble = []; $canDouble = false; $redeemRecords = CampaignLog::find()->where($conditionForOdds)->all(); if (!empty($redeemRecords)) { foreach ($redeemRecords as $redeemRecord) { $product = $redeemRecord['productName']; $oddsCount += $redeemRecord['member']['scoreAdded']; if (!$canDouble) { if ($product == '2015 雞粉2.2kg' || $product == '2015 雞粉1.1kg' || $product == '2016 康寶雞粉 1.1KG' || $product == '2016 康寶雞粉 2.2KG') { $checkDouble['chickenPowder'] = true; } if ($product == '2015 鮮雞汁' || $product == '2016 康寶濃縮鮮雞汁') { $checkDouble['chickenJuice'] = true; } if ($product == '2015 鰹魚粉1kg' || $product == '2015 鰹魚粉1.5kg' || $product == '2016 康寶鰹魚粉 1KG' || $product == '2016 康寶鰹魚粉 1.5KG') { $checkDouble['fishmeal'] = true; } if (count($checkDouble) == 3) { $canDouble = true; } } unset($product); } } $oddsCount = intval($oddsCount / $needPoints); if ($canDouble) { $oddsCount = $oddsCount * 2; } unset($checkDouble, $canDouble, $needPoints, $redeemRecords, $conditionForOdds); //$memberInfo:id,name,mobile,addScore,score; $day; $oddsCount $mobile = BulkSmsUtil::processSmsMobile($accountId, $memberInfo['mobile']); $smsContent = null; $currentDate = MongodbUtil::MongoDate2msTimeStamp(new \mongoDate()); $topPrizeDate = MongodbUtil::MongoDate2msTimeStamp(new \MongoDate(strtotime("2016-02-29 00:00:00"))); $offsetDay = ceil(($topPrizeDate - $currentDate) / (1000 * 60 * 60 * 24)); if ($offsetDay > 10) { // 還沒倒計時 $smsContent = $memberInfo['name'] . '您好,您郵寄的點數已入點完成,此次共入點' . $memberInfo['addScore'] . '點,您目前點數為' . $memberInfo['score'] . '點。恭喜您同時累積活動『年年好味不能沒有你』' . $oddsCount . '次抽獎機會,累積點數越多,中獎機會越大,詳細活動辦法請見http://bit.ly/1P4yZEA'; } elseif ($offsetDay > 3 && $offsetDay < 11) { $smsContent = $memberInfo['name'] . '您好,您郵寄的點數已入點完成,此次共入點' . $memberInfo['addScore'] . '點,您目前點數為' . $memberInfo['score'] . '點。恭喜您同時累積活動『年年好味不能沒有你』' . $oddsCount . '次抽獎機會,距離30萬元紅包抽獎,只剩' . $offsetDay . '天,詳細活動辦法請見http://bit.ly/1P4yZEA'; } elseif ($offsetDay >= 0 && $offsetDay <= 3) { $smsContent = $memberInfo['name'] . '您好,您郵寄的點數已入點完成,此次共入點' . $memberInfo['addScore'] . '點,您目前點數為' . $memberInfo['score'] . '點。恭喜您同時累積活動『年年好味不能沒有你』' . $oddsCount . '次抽獎機會,距離30萬元紅包抽獎,倒數' . abs($offsetDay) . '天,詳細活動辦法請見http://bit.ly/1P4yZEA'; } Smslog::createSmsLog($mobile, $smsContent, 'CNY webhook SMS', 'sending', $accountId); MessageUtil::sendMobileMessage($mobile, $smsContent, $accountId); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['mobile' => $mobile, 'smsContent' => $smsContent]; }
/** * @param $memberId string * @param $prizeLevel string (eg: 'one'表示一等奖) * @param $exchangeGoodsScores array (eg:['560399d6475df4c7378b4572'=>-200, ...]) * @return array (eg: ['id'=>'5604f..', 'mobile'=>'0912345678', 'name'=>'用戶名', 'exchangeGoodsScore'=>200, 'prizeLevel'=>'three']) */ private function _getMemberInfo($memberId, $prizeLevel, $exchangeGoodsScores = null) { $memberId = new \MongoId($memberId); $member = Member::findByPk($memberId); $result = array(); if (!empty($member->properties)) { $result['id'] = (string) $memberId; foreach ($member->properties as $property) { if ($property['name'] == 'tel') { $result['mobile'] = $property['value']; } if ($property['name'] == 'name') { $result['name'] = $property['value']; } } if (!empty($exchangeGoodsScores)) { foreach ($exchangeGoodsScores as $key => $value) { if ($key == $result['id']) { $result['exchangeGoodsScore'] = abs($value); break; } } } $result['prizeLevel'] = $prizeLevel; } unset($member); return $result; }
public function actionMyTest() { // Add members // $tels = array(); // for ($i=1; $i < 10000 ; $i++) { // $n = rand(10000000,99999999); // if (!in_array($n, $tels)) { // $tels[] = $n; // } // unset($n); // } // for ($i=1;$i<10000;$i++) { // $properties = [ // ['name'=>'name','value'=>'用戶名'.($i+1),'id'=>new \MongoId('56033cad475df4ce0c8b456e')], // ['name'=>'tel','value'=>'09'. (string)$tels[$i], 'id'=>new \MongoId('56033cad475df4ce0c8b456f')] // ]; // $member = new Member(); // $member->score = 2000 + $i; // $member->totalScore = 2000 + $i; // $member->totalScoreAfterZeroed = 2000 + $i; // $member->avatar = ''; // $member->location = null; // $member->tags = []; // $member->properties = $properties; // $member->accountId = new \MongoId("56028cda475df4aa048b4567"); // $defaultCard = \backend\modules\member\models\MemberShipCard::getDefault($member->accountId); // $member->cardId = $defaultCard->_id; // $member->cardNumber = Member::generateCardNumber(); // $member->origin = Member::PORTAL; // if (!$member->save()) { // return false; // } // } // $sms['mobile'] = '0912345678'; // $sms['mobile'] = '886' . substr($sms['mobile'], 1, strlen($sms['mobile'])); // var_dump($sms['mobile']); $id = $this->getQuery('id'); $member = Member::findByPk(new \MongoId($id)); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return ['member' => $member]; }
public static function getMobileVar($params) { if (empty($params['memberId'])) { throw new BadRequestHttpException('missing params'); } $type = $params['type']; if (!in_array($type, [self::REDEMPTION_TYPE, self::PROMOCODE_TYPE])) { throw new BadRequestHttpException('type is invaild'); } $params['memberId'] = new \MongoId($params['memberId']); $member = Member::getMemberInfo($params['memberId'], ['name', 'gender', 'email', 'tel', 'birthday', 'score']); if ('male' == $member['gender']) { $gender = '男'; } else { $gender = '女'; } $product = $promoCode = ''; if (!empty($params['data'])) { //create product list foreach ($params['data'] as $data) { if (isset($data['productName'])) { $product .= $data['productName'] . ','; } else { $promoCode = implode(',', $params['data']); break; } } $product = rtrim($product, ','); } $memberInfo = Member::findByPk($params['memberId']); $vars = ['address' => !empty($params['address']) ? $params['address'] : '', 'pointBalance' => !isset($memberInfo->score) ? 0 : $memberInfo->score, 'product' => $product, 'promoCode' => $promoCode, 'username' => $member['name'], 'gender' => $gender, 'email' => $member['email'], 'phone' => $member['tel'], 'birthday' => date('Y-m-d', $member['birthday'] / TimeUtil::MILLI_OF_SECONDS), 'total' => empty($params['total']) ? 0 : $params['total'], 'totalScore' => empty($params['totalScore']) ? 0 : $params['totalScore'], 'number' => count($params['data']), 'amount' => empty($params['usedScore']) ? 0 : $params['usedScore']]; //to suport member propertyId $properties = MemberProperty::getMemberProperty($memberInfo->accountId, $memberInfo->properties); $vars = array_merge($vars, $properties); return $vars; }
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')); } }
/** * get value from member * @param $memberId, mongoId * @param $name, string or array */ public static function getMemberInfo($memberId, $name = 'name') { $member = Member::findByPk($memberId); $result = []; if (is_string($name)) { $name = explode(',', $name); } if (!empty($member->properties)) { foreach ($member->properties as $property) { foreach ($name as $value) { if ($value == $property['name']) { $result[$value] = $property['value']; } if (empty($result[$value])) { $result[$value] = ''; } } } } else { foreach ($name as $value) { $result[$value] = ''; } } return $result; }
/** * Get member's openId * @param string $memberId * @param string $channelId * @return string $openId */ public function getOpenId($memberId, $channelId) { if (is_string($memberId)) { $memberId = new MongoId($memberId); } $member = ModelMember::findByPk($memberId); if (empty($member)) { throw new BadRequestHttpException(Yii::t('common', 'data_error')); } if (!empty($member['socialAccountId']) && $member['socialAccountId'] == $channelId) { return $member['openId']; } if (!empty($member['socials'])) { foreach ($member['socials'] as $value) { if ($value['channelId'] == $channelId) { return $value['openId']; } } } }
/** * 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"); } }
/** * Update member card after save member. * @see \yii\db\BaseActiveRecord::afterSave($insert, $changedAttributes) */ public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); if ($insert) { $member = Member::findByPk($this->memberId); if (!empty($member)) { $member->upgradeCard(); } } }