Example #1
0
 /**
  * Get channel by channelId, if the $one is true,this api only return a array,otherwise it will return multi arrays
  * @param $channelId, array, channel id array
  * @param $one, boolean,
  * @return array
  */
 public function getById($channelId, $one = true)
 {
     if ($one) {
         return ModelChannel::findOne(['channelId' => ['$in' => $channelId]]);
     } else {
         return ModelChannel::findAll(['channelId' => ['$in' => $channelId]]);
     }
 }
 /**
  * Get channel_id -> name map
  * @return array
  * @example ['54dbfc44e4b09d7f7799e96d' => 'hankliu62', '54d9c475e4b0abe717853ee6' => '群游汇']
  */
 private function _getChannelNameMap()
 {
     $channelNameMap = [];
     $channels = Channel::findAll([]);
     foreach ($channels as $channel) {
         $channelNameMap[$channel->channelId] = $channel->name;
     }
     return $channelNameMap;
 }
Example #3
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;
     }
 }
 /**
  * Get accountId and company when bind
  * @param array $params
  * @throws BadRequestHttpException
  * @throws InvalidParameterException
  * @return array
  */
 public function bind($params)
 {
     \Yii::$app->language = LanguageUtil::LANGUAGE_ZH;
     $this->checkCode($params);
     $mobile = $params['mobile'];
     if (empty($params['channelId']) || empty($params['openId'])) {
         throw new BadRequestHttpException('Missing params');
     }
     $channelId = $params['channelId'];
     $channel = Channel::getEnableByChannelId($channelId);
     $member = Member::getByMobile($mobile, $channel->accountId);
     if (!empty($member)) {
         throw new InvalidParameterException(['phone' => \Yii::t('common', 'phone_has_been_bound')]);
     }
     $account = Account::findByPk($channel->accountId);
     return ['accountId' => $channel->accountId, 'company' => empty($account->company) ? null : $account->company];
 }
Example #5
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];
 }
 public function actionSignupSummary()
 {
     $params = $this->getQuery();
     if (!isset($params['start']) || !isset($params['end'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     if ($params['start'] > $params['end']) {
         throw new BadRequestHttpException(Yii::t('common', 'data_error'));
     }
     $accountId = $this->getAccountId();
     $startDate = TimeUtil::msTime2String($params['start'], 'Y-m');
     $endDate = TimeUtil::msTime2String($params['end'], 'Y-m');
     $statsData = StatsMemberMonthly::getByDate($startDate, $endDate, $accountId);
     $data = [];
     foreach ($statsData as $item) {
         $date = $item->month;
         $data[$item->origin][$date] = empty($data[$item->origin][$date]) ? 0 : $data[$item->origin][$date];
         $data[$item->origin][$date] += $item->total;
     }
     //ensure origins
     $channelOrigins = Channel::getOriginsByAccount($accountId);
     $origins = array_merge(StatsMemberMonthly::$originWithoutChannels, $channelOrigins);
     foreach ($origins as $origin) {
         if (empty($data[$origin])) {
             $data[$origin] = [];
         }
     }
     $endTime = strtotime($endDate);
     $dates = [];
     $totals = [];
     $dateTime = strtotime($startDate);
     while ($dateTime <= $endTime) {
         $date = date('Y-m', $dateTime);
         $dates[] = $date;
         foreach ($data as $origin => $dateTotal) {
             $totals[$origin][] = empty($dateTotal[$date]) ? 0 : $dateTotal[$date];
         }
         $dateTime = strtotime('+1 month', $dateTime);
     }
     return ['date' => $dates, 'data' => $totals];
 }
 /**
  * Synchroniz account channels, remove disable channels
  * @param Account $account
  * @throws ServerErrorHttpException
  * @return array
  */
 public function syncAccountChannels($accountId)
 {
     $channelIds = Channel::getEnableChannelIds($accountId);
     $channelInfo = ['wechat' => [], 'weibo' => [], 'alipay' => []];
     if (empty($channelIds)) {
         return $channelInfo;
     }
     $weChannels = \Yii::$app->weConnect->getAccounts($channelIds);
     $this->syncWebHookChannels($accountId, $weChannels);
     $enbaleChannel = [];
     foreach ($weChannels as $weChannel) {
         if ($weChannel['channel'] == Account::WECONNECT_CHANNEL_WEIXIN && !empty($weChannel['refreshToken'])) {
             $channelInfo['wechat'][] = $weChannel;
             $enbaleChannel[] = $weChannel['id'];
         } else {
             if ($weChannel['channel'] == Account::WECONNECT_CHANNEL_WEIXIN && !empty($weChannel['appSecret'])) {
                 $channelInfo['wechat'][] = $weChannel;
                 $enbaleChannel[] = $weChannel['id'];
             } else {
                 if ($weChannel['channel'] == Account::WECONNECT_CHANNEL_WEIBO) {
                     $weChannel['appkey'] = WEIBO_APP_KEY;
                     $channelInfo['weibo'][] = $weChannel;
                     $enbaleChannel[] = $weChannel['id'];
                 } else {
                     if ($weChannel['channel'] == Account::WECONNECT_CHANNEL_ALIPAY) {
                         $channelInfo['alipay'][] = $weChannel;
                         $enbaleChannel[] = $weChannel['id'];
                     }
                 }
             }
         }
         Channel::updateAll(['$set' => ['name' => $weChannel['name'], 'type' => empty($weChannel['accountType']) ? '' : $weChannel['accountType']]], ['channelId' => $weChannel['id'], 'accountId' => $accountId]);
     }
     $disableChannelIds = array_diff($channelIds, $enbaleChannel);
     if (!empty($disableChannelIds)) {
         $disableChannelIds = array_values($disableChannelIds);
         Channel::disableByChannelIds($accountId, $disableChannelIds);
     }
     return $channelInfo;
 }
 /**
  * Delete test wechat account
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/management/channel/delete-test-wechat<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used to delete test wechat account.
  * <br/><br/>
  *
  * <b>Request Params:</b>
  * <pre>
  * {
  *     "accountId": "55546fc8e4b0d8376000b858"
  * }
  * </pre>
  */
 public function actionDeleteTestWechat()
 {
     $wechatAccountId = $this->getParams('accountId');
     $accountId = $this->getAccountId();
     if (empty($wechatAccountId)) {
         throw new BadRequestHttpException(\Yii::t('common', 'parameters_missing'));
     }
     $result = Yii::$app->weConnect->deleteAccount($wechatAccountId);
     Channel::disableByChannelIds($accountId, [$wechatAccountId]);
     return $result;
 }
 /**
  * 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;
 }
Example #10
0
 /**
  * Get member channels
  * @return array
  */
 public function getChannels($memberId)
 {
     $channelItem = $channels = [];
     $memberSocials = $this->socialAccountId;
     $openIdItem = $this->openId;
     if (!empty($memberSocials) && !empty($openIdItem)) {
         $channel = Channel::findOne(['channelId' => $memberSocials]);
         $channelItem = array_merge($channel->toArray(), ["openId" => $openIdItem, "memberId" => $memberId]);
         $channels[] = $channelItem;
     }
     if (!empty($this->socials) && count($this->socials) > 0) {
         foreach ($this->socials as $social) {
             $openId = $social['openId'];
             $channel = Channel::findOne(['channelId' => $social['channelId']]);
             $channelItem = array_merge($channel->toArray(), ["openId" => $openId, "memberId" => $memberId]);
             $channels[] = $channelItem;
         }
     }
     return $channels;
 }
 public static function preProcessData($condition)
 {
     $stats = self::findAll($condition);
     $statsData = [];
     foreach ($stats as $item) {
         $date = $item->month;
         $statsData[$item->origin][$date] = empty($statsData[$item->origin][$date]) ? 0 : $statsData[$item->origin][$date];
         $statsData[$item->origin][$date] += $item->total;
     }
     //ensure origins
     $channelOrigins = Channel::getOriginsByAccount($condition['accountId']);
     $origins = array_merge(StatsMemberMonthly::$originWithoutChannels, $channelOrigins);
     foreach ($origins as $origin) {
         if (empty($statsData[$origin])) {
             $statsData[$origin] = [];
         }
     }
     $endDate = $condition['month']['$lte'];
     $startDate = $condition['month']['$gte'];
     $endTime = strtotime($endDate);
     $dateTime = strtotime($startDate);
     $data = [];
     while ($dateTime <= $endTime) {
         $date = date('Y-m', $dateTime);
         foreach ($statsData as $origin => $dateTotal) {
             $data[] = ['month' => $date, 'channel' => Yii::t('common', $origin), 'number' => empty($dateTotal[$date]) ? 0 : $dateTotal[$date]];
         }
         $dateTime = strtotime('+1 month', $dateTime);
     }
     return $data;
 }
Example #12
0
 /**
  * get coupon qrcode info,this function will return three arrays,
  * 1.old qrcode,2.new qrcode,3.show qrcode to fronted
  * @param $params, array
  * @param $coupon, object
  * @param $exitsQrcode, array
  */
 public static function getCouponQrcode($params, $coupon, $existsQrcode)
 {
     $data = $result = [];
     $channels = array_unique($params['channels']);
     $channelInfos = Channel::findAll(['channelId' => ['$in' => $channels]]);
     $existsChannelInfos = [];
     foreach ($channelInfos as $channelInfo) {
         $existsChannelInfos[$channelInfo['channelId']] = $channelInfo;
     }
     foreach ($channels as $channel) {
         //if the qrcode is exists in any channel,not need to create a new qrcode for this channel
         if (isset($existsQrcode[$channel])) {
             $qrcodeId = $existsQrcode[$channel]['id'];
             $origin = $existsQrcode[$channel]['origin'];
             $channelName = $existsQrcode[$channel]['channelName'];
             $qiniuKey = $existsQrcode[$channel]['qiniuKey'];
             unset($existsQrcode[$channel]);
         } else {
             //redirect url
             $mainDomain = Yii::$app->request->hostInfo;
             $content = $mainDomain . '/api/mobile/coupon?channelId=' . $channel . '&couponId=' . $params['couponId'];
             $qrcode = Yii::$app->qrcode->create($content, Coupon::COUPON_QRCODE_RECEIVED, $coupon->_id, $coupon->accountId, false);
             $qrcodeId = $qrcode->_id;
             $origin = $existsChannelInfos[$channel]['origin'];
             $channelName = $existsChannelInfos[$channel]['name'];
             $qiniuKey = $qrcode->qiniuKey;
         }
         $data[] = ['id' => $qrcodeId, 'origin' => $origin, 'channelName' => $channelName, 'channelId' => $channel, 'qiniuKey' => $qiniuKey];
         $result[$origin][] = ['id' => (string) $qrcodeId, 'origin' => $origin, 'channelName' => $channelName, 'fileName' => $qiniuKey, 'channelId' => $channel, 'url' => Yii::$app->qrcode->getUrl($qiniuKey)];
     }
     return [$existsQrcode, $data, $result];
 }
Example #13
0
 /**
  * create a attention qrcode
  * @return string. qrcode id
  */
 public static function createAttentionQrcode($channelId, $accessWeibo = false)
 {
     try {
         //defined a special name for qrcodeName,this param must be pass
         $qrcodeName = Channel::ATTENTION_QRCODE . '_' . $channelId;
         $channelInfo = Channel::getByChannelId($channelId);
         if (empty($channelInfo['qrcodeId'])) {
             if ($channelInfo['origin'] != self::WEIBO || $accessWeibo) {
                 $qrcode = ['type' => 'CHANNEL', 'name' => $qrcodeName];
                 $qrcodeInfo = Yii::$app->weConnect->createQrcode($channelId, $qrcode);
                 if (!empty($qrcodeInfo)) {
                     return $qrcodeInfo['id'];
                 }
             }
             return '';
         } else {
             return $channelInfo['qrcodeId'];
         }
     } catch (Exception $e) {
         return '';
     }
 }
 /**
  * migrate account channel(channel-migration)
  */
 public function actionChannelMigration()
 {
     $accounts = Account::findAll([]);
     $channels = [];
     foreach ($accounts as $account) {
         $channelIds = $account->channels;
         $testWechat = empty($channelIds['testWechat']) ? [] : $channelIds['testWechat'];
         $channelIds = array_merge($channelIds['wechat'], $channelIds['weibo'], $testWechat);
         if (empty($channelIds)) {
             continue;
         }
         try {
             $weChannels = Yii::$app->weConnect->getAccounts($channelIds);
         } catch (\Exception $e) {
             echo 'error channel' . json_encode($channelIds) . PHP_EOL;
             continue;
         }
         foreach ($weChannels as $weChannel) {
             $channelOrigin = $weChannel['channel'];
             switch ($channelOrigin) {
                 case 'WEIXIN':
                     $origin = Channel::WECHAT;
                     break;
                 case 'WEIBO':
                     $origin = Channel::WEIBO;
                     break;
                 case 'ALIPAY':
                     $origin = Channel::ALIPAY;
                     break;
                 default:
                     $origin = strtolower($weChannel['channel']);
                     echo $weChannel['id'] . ' ' . $origin . PHP_EOL;
                     break;
             }
             $type = empty($weChannel['accountType']) ? '' : $weChannel['accountType'];
             $channel = Channel::getByAccountAndChannelId($account->_id, $weChannel['id']);
             $isTest = $origin == Channel::WECHAT && !empty($weChannel['appSecret']) ? true : false;
             if (!empty($channel)) {
                 $channel->origin = $origin;
                 $channel->name = $weChannel['name'];
                 $channel->type = $type;
                 $channel->status = strtolower($weChannel['status']);
                 $channel->isTest = $isTest;
                 if (!$channel->save()) {
                     echo 'update-' . $weChannel['id'] . ' ' . $origin . PHP_EOL;
                 }
             } else {
                 $channels[] = ['channelId' => $weChannel['id'], 'origin' => $origin, 'name' => $weChannel['name'], 'type' => $type, 'status' => strtolower($weChannel['status']), 'isTest' => $isTest, 'accountId' => $account->_id];
             }
         }
     }
     if (Channel::batchInsert($channels)) {
         echo 'success' . PHP_EOL;
     } else {
         echo 'fail' . PHP_EOL;
     }
 }
Example #15
0
 public static function getChannelInfo($params)
 {
     $scoreHistoryChannel = [];
     if (!empty($params['channelId'])) {
         $channelInfo = Channel::getByChannelId($params['channelId']);
         $scoreHistoryChannel = ['id' => $channelInfo->channelId, 'name' => $channelInfo->name, 'origin' => $channelInfo->origin];
         $channelType = $channelInfo->origin;
         $channelName = $channelInfo->name;
     } else {
         $scoreHistoryChannel = ['origin' => PromotionCode::PORTAL];
         $channelName = '';
         $channelType = PromotionCode::PROMOTION_CODE_EXCHANGE;
     }
     return ['scoreHistoryChannel' => $scoreHistoryChannel, 'channelName' => $channelName, 'channelType' => $channelType];
 }
Example #16
0
 /**
  * @return string
  * @param $channelId, string, channel ID
  */
 public static function getAttentionQrcode($channelId)
 {
     $imageUrl = $qrcodeId = '';
     $channelInfo = Channel::getEnableByChannelId($channelId);
     if (empty($channelInfo['qrcodeId'])) {
         $qrcodeId = Channel::createAttentionQrcode($channelId);
         if (!empty($qrcodeId)) {
             Channel::updateAll(['qrcodeId' => $qrcodeId], ['channelId' => $channelId]);
         }
     } else {
         $qrcodeId = $channelInfo['qrcodeId'];
     }
     if (!empty($qrcodeId)) {
         $qrcodeInfo = Yii::$app->weConnect->getQrcode($channelId, $qrcodeId);
         $imageUrl = $qrcodeInfo['imageUrl'];
     }
     return $imageUrl;
 }
Example #17
0
 /**
  * delete store data
  * @param $channelId,string
  */
 public static function deleteStoreQrcode($channelId, $qrcodeId)
 {
     $channelInfo = Channel::getEnableByChannelId($channelId);
     if (empty($channelInfo->origin)) {
         throw new InvalidParameterException('invaild channelId');
     }
     $field = $channelInfo->origin;
     $where = [$field . '.qrcodeId' => $qrcodeId];
     Store::updateAll([$field => null], $where);
 }
 /**
  * Query all channels
  *
  * <b>Request Type</b>: GET<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/common/channel/channels-all<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for querying all channels.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     ack: integer, mark the query result, 0 means query fail, 1 means query successfully<br/>
  *     msg: string, if query fail, it contains the error message<br/>
  *     data: array, json array to queried channels detail information<br/>
  *     <br/><br/>
  *
  * <b>Request Example:</b><br/>
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * [
  *    {
  *        "id": "55ba03f6e9c2fbf3348b4567",
  *        "channelId": "54d9c155e4b0abe717853ee1",
  *        "origin": "wechat",
  *        "name": "熊猫Baby",
  *        "type": "SERVICE_AUTH_ACCOUNT",
  *        "status": "disable",
  *        "isTest": true
  *     }
  * ]
  * </pre>
  */
 public function actionChannelsAll()
 {
     $accountId = $this->getAccountId();
     return Channel::getAllByAccount($accountId);
 }
 /**
  * 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");
     }
 }
Example #20
0
 private function _saveLog(Member $member, $exchanges, $params, $user = null)
 {
     $goodsExchangeLog = new GoodsExchangeLog();
     $allGoods = [];
     $totalCount = 0;
     $scoreHistoryDescription = '';
     foreach ($exchanges as $exchange) {
         $goods = $exchange['goods'];
         $count = $exchange['count'];
         $pictures = $goods->pictures;
         $allGoods[] = ['id' => $goods->_id, 'productId' => $goods->productId, 'sku' => $goods->sku, 'picture' => empty($pictures[0]) ? '' : $pictures[0], 'productName' => $goods->productName, 'count' => $count];
         $totalCount += $count;
         $scoreHistoryDescription .= $goods->productName . "({$count}); ";
     }
     $scoreHistoryDescription = trim($scoreHistoryDescription, '; ');
     $goodsExchangeLog->goods = $allGoods;
     $goodsExchangeLog->memberId = $member->_id;
     $properties = $member->properties;
     $name = '';
     foreach ($properties as $property) {
         if ($property['name'] == Member::DEFAULT_PROPERTIES_NAME) {
             $name = $property['value'];
         }
         if ($property['name'] == Member::DEFAULT_PROPERTIES_MOBILE) {
             $mobile = $property['value'];
         }
     }
     $goodsExchangeLog->memberName = $name;
     $goodsExchangeLog->telephone = empty($params['phone']) ? $mobile : $params['phone'];
     $goodsExchangeLog->usedScore = $params['usedScore'];
     $goodsExchangeLog->expectedScore = $params['expectedScore'];
     $goodsExchangeLog->count = $totalCount;
     $goodsExchangeLog->address = $params['address'];
     $goodsExchangeLog->receiveMode = $params['receiveMode'];
     $goodsExchangeLog->postcode = empty($params['postcode']) ? '' : $params['postcode'];
     $goodsExchangeLog->isDelivered = false;
     $scoreHistoryChannel = [];
     if (!empty($params['channelId'])) {
         $channelInfo = Channel::getByChannelId($params['channelId'], $member->accountId);
         $scoreHistoryChannel = ['id' => $channelInfo->channelId, 'name' => $channelInfo->name, 'origin' => $channelInfo->origin];
         $goodsExchangeLog->usedFrom = ['id' => $params['channelId'], 'type' => $channelInfo->origin, 'name' => $channelInfo->name];
     } else {
         $scoreHistoryChannel = ['origin' => GoodsExchangeLog::PORTAL];
         $goodsExchangeLog->usedFrom = ['id' => '', 'type' => GoodsExchangeLog::PORTAL, 'name' => GoodsExchangeLog::OFFLINE_EXCHANGE];
     }
     $goodsExchangeLog->accountId = $member->accountId;
     $scoreHistory = new ScoreHistory();
     $scoreHistory->assigner = ScoreHistory::ASSIGNER_EXCHAGE_GOODS;
     $scoreHistory->increment = 0 - $params['usedScore'];
     $scoreHistory->memberId = $member->_id;
     $scoreHistory->brief = ScoreHistory::ASSIGNER_EXCHAGE_GOODS;
     $scoreHistory->description = $scoreHistoryDescription;
     $scoreHistory->accountId = $member->accountId;
     $scoreHistory->channel = $scoreHistoryChannel;
     $scoreHistory->user = $user;
     if ($goodsExchangeLog->save(true) && $scoreHistory->save(true)) {
         MemberLogs::record($member->_id, $member->accountId, MemberLogs::OPERATION_REDEEM);
         return true;
     } else {
         LogUtil::error(['exchange fail' => [$scoreHistory->getErrors(), $goodsExchangeLog->getErrors()]]);
         return false;
     }
 }