private function _transformMessages($result, $channelId) { $items = $item = []; if (!empty($result) && !empty($result['results']) && count($result['results']) > 0) { foreach ($result['results'] as $message) { $messages = $message['message']; if (!empty($messages)) { $item = ['id' => empty($messages['messageId']) ? '' : $messages['messageId'], 'channelId' => $channelId, 'message' => !isset($messages['content']) ? '' : $messages['content'], 'msgType' => $messages['msgType'], 'keycode' => !isset($message['keycode']) ? '' : $message['keycode'], 'interactTime' => TimeUtil::msTime2String($messages['createTime'], 'Y-m-d H:i:s')]; $items[] = $item; } } } return $items; }
public function actionStatsMenusHits() { $openId = $this->getQuery('openId'); $channelId = $this->getQuery('channelId'); $count = 0; $lastTime = ''; $results = []; if (empty($openId) || empty($channelId)) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $resultItem = Yii::$app->weConnect->statsMenusHits($openId, $channelId); if (!empty($resultItem)) { if (!empty($resultItem['profiles']) && !empty($resultItem['profiles']['menus']) && count($resultItem['profiles']['menus']) > 0) { $raw = $resultItem['profiles']['menus']; $count = !isset($raw['hitCount']) ? 0 : $raw['hitCount']; $lastTime = empty($raw['lastHitTime']) ? '' : TimeUtil::msTime2String($raw['lastHitTime'], 'Y-m-d H:i:s'); } } $item = ['hitCount' => $count, 'lastHitTime' => $lastTime]; return $item; }
public function actionStatsCoupon() { $params = $this->getQuery(); if (empty($params['id']) || !isset($params['startTime']) || !isset($params['endTime'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $id = new MongoId($params['id']); $couponLog = Coupon::findOne(["_id" => $id]); if (empty($couponLog)) { throw new BadRequestHttpException(Yii::t('product', 'membershipDiscount_is_deleted')); } //turn unix timestamp to string $startTime = TimeUtil::msTime2String($params['startTime'], 'Y-m-d'); $endTime = TimeUtil::msTime2String($params['endTime'], 'Y-m-d'); $couponPeriodInfo = StatsCouponLogDaily::getCouponLogStats($id, $startTime, $endTime); ArrayHelper::multisort($couponPeriodInfo, 'date', SORT_ASC); $dateCouPonStats = ArrayHelper::index($couponPeriodInfo, 'date'); $item = $redeemedNum = $recievedNum = $date = []; $startDate = strtotime($startTime); $endDate = strtotime($endTime); if (!empty($couponPeriodInfo) && count($couponPeriodInfo) > 0) { while ($startDate <= $endDate) { $dateStr = date('Y-m-d', $startDate); if (!empty($dateCouPonStats[$dateStr])) { $date[] = $dateStr; $recievedNum[] = $dateCouPonStats[$dateStr]['recievedNum']; $redeemedNum[] = $dateCouPonStats[$dateStr]['redeemedNum']; } else { $date[] = $dateStr; $recievedNum[] = 0; $redeemedNum[] = 0; } $startDate = strtotime($dateStr . ' +1 day'); } } $item = ['date' => $date, 'count' => ['recievedNum' => $recievedNum, 'redeemedNum' => $redeemedNum]]; return $item; }
/** * Get question option answer's stats info * @throws BadRequestHttpException * @return array, [{"option": "Yes", "count": 12}] */ public function actionAnswers() { $params = $this->getQuery(); if (empty($params['questionId'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $question = Question::findByPk(new MongoId($params['questionId'])); if (empty($question) || $question->type === Question::TYPE_INPUT) { throw new InvalidParameterException(Yii::t('content', 'invalid_question')); } //turn unix timestamp to string $startDateStr = isset($params['startTime']) ? TimeUtil::msTime2String($params['startTime'], 'Y-m-d') : null; $endDateStr = isset($params['endTime']) ? TimeUtil::msTime2String($params['endTime'], 'Y-m-d') : null; $stats = StatsQuestionnaireAnswerDaily::getQuestionOptionStats(new MongoId($params['questionId']), $startDateStr, $endDateStr); $statsMap = ArrayHelper::map($stats, 'option', 'count'); $options = []; $count = []; foreach ($question->options as $option) { $options[] = $option['content']; $count[] = empty($statsMap[$option['content']]) ? 0 : $statsMap[$option['content']]; } return ['options' => $options, 'count' => $count]; }
/** * deal with the data before export * @param $member,object * @param $args,array */ public static function preProcessMemberData($members, $args) { $cardMap = $args['cardMap']; $socialAccountsMap = $args['socialAccountsMap']; $memberProperties = $args['memberProperties']; $memberData = []; foreach ($memberProperties as $memberProperty) { $memberData[(string) $memberProperty['_id']] = $memberProperty['type']; } $rows = []; foreach ($members as $member) { $memberTag = ''; if (!empty($member->tags)) { $memberTag = implode(',', $member->tags); } $row = ['tag' => $memberTag, 'cardNumber' => $member->cardNumber, 'cardName' => empty($cardMap[(string) $member->cardId]) ? '' : $cardMap[(string) $member->cardId], 'score' => $member->score, 'totalScore' => $member->totalScore, 'totalScoreAfterZeroed' => intval($member->totalScoreAfterZeroed), 'costScoreAfterZeroed' => intval($member->totalScoreAfterZeroed) - $member->score, 'channel' => empty($socialAccountsMap[(string) $member->socialAccountId]) ? Yii::t('common', $member->origin) : $socialAccountsMap[(string) $member->socialAccountId], 'createdAt' => MongodbUtil::MongoDate2String($member->createdAt)]; foreach ($member->properties as $property) { if (isset($memberData[(string) $property['id']]) && $memberData[(string) $property['id']] == MemberProperty::TYPE_DATE) { $dateFormate = $property['name'] == 'birthday' ? 'Y-m-d' : 'Y-m-d H:i:s'; $row[$property['name']] = empty($property['value']) ? '' : TimeUtil::msTime2String($property['value'], $dateFormate); } else { if (is_array($property['value'])) { $row[$property['name']] = implode($property['value'], ','); } else { if ($property['name'] == self::DEFAULT_PROPERTIES_GENDER) { $property['value'] = Yii::t('member', $property['value']); } $row[$property['name']] = $property['value']; } } } $rows[] = $row; } return $rows; }
/** * search coupon */ public static function search($params) { $query = Coupon::find(); $condition = ['accountId' => $params['accountId'], 'isDeleted' => self::NOT_DELETED]; if (!empty($params['title'])) { $key = $params['title']; $key = StringUtil::regStrFormat(trim($key)); $keyReg = new MongoRegex("/{$key}/i"); $search = ['title' => $keyReg]; $condition = array_merge($condition, $search); unset($search); } if (!empty($params['unexpired'])) { $time = new MongoDate(strtotime(TimeUtil::msTime2String($params['unexpired'], 'Y-m-d'))); $search = ['$or' => [['time.type' => self::COUPON_ABSOLUTE_TIME, 'time.endTime' => ['$gte' => $time]], ['time.type' => self::COUPON_RELATIVE_TIME]]]; $condition = array_merge($condition, $search); unset($search, $time); } $query->orderBy(self::normalizeOrderBy($params)); $query->where($condition); $unlimited = Yii::$app->request->get('unlimited', false); if ($unlimited) { return ['items' => $query->all()]; } return new ActiveDataProvider(['query' => $query]); }
/** * exchange the promotioncode */ public function actionExchange() { $params = $this->getParams(); if (empty($params['code']) || empty($params['memberId'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } //get email for user $accesstoken = $this->getAccessToken(); $tokenInfo = Token::findOne(['accessToken' => $accesstoken]); $userInfo = User::findByPk($tokenInfo['userId']); $params['operaterEmail'] = empty($userInfo['email']) ? '' : $userInfo['email']; $params['userInfo'] = empty($userInfo) ? null : ['id' => $userInfo->_id, 'name' => $userInfo->name]; $memberId = $params['memberId']; $params['memberId'] = new MongoId($memberId); if (!empty($params['exchangeTime'])) { $params['exchangeTime'] = TimeUtil::ms2sTime($params['exchangeTime']); } //exchange the promotion code $accountId = $this->getAccountId(); if (is_array($params['code'])) { //exchaneg code offline $codes = $params['code']; $successCode = []; foreach ($codes as $code) { $params['code'] = strtoupper($code); $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_OFFLINE); if ('success' == $result['result']) { $successCode[] = $code; } } list($codeNumber, $score) = CampaignLog::getCodeRecord($successCode); if (!empty($params['useWebhook'])) { $eventData = ['type' => Webhook::EVENT_PROMOTION_CODE_REDEEMED, 'member_id' => $memberId, 'codes' => $params['code'], 'redeemed_codes' => $successCode, 'score' => $score, 'origin' => Member::PORTAL, 'account_id' => (string) $accountId, 'created_at' => TimeUtil::msTime2String($params['exchangeTime'], \DateTime::ATOM)]; Yii::$app->webhook->triggerEvent($eventData); } //fix data $this->fixData($accountId, $params['memberId'], $successCode); return ['result' => 'success', 'codeNumber' => $codeNumber, 'totalScore' => $score, 'codes' => $successCode]; } else { $params['code'] = strtoupper($params['code']); $result = PromotionCode::exchangeCampaignCode($params, $accountId, self::EXCHANEG_TYPE_MOBILE); if ('error' == $result['result']) { throw new InvalidParameterException($result['message']); } else { return $result; } } }
public function actionExportSignupSummary() { $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'); $condition = ['accountId' => $accountId, 'month' => ['$lte' => $endDate, '$gte' => $startDate]]; $key = Yii::t('member', 'signup_summary') . '_' . date('Ymd'); $headerTitle = Yii::t('member', 'signup_summary_export_title'); $headerValue = explode(',', $headerTitle); $header = ['month', 'channel', 'number']; $showHeader = array_combine($header, $headerValue); $exportArgs = ['key' => $key, 'header' => $showHeader, 'condition' => serialize($condition), 'classFunction' => '\\backend\\modules\\member\\models\\StatsMemberMonthly::preProcessData', 'description' => 'Direct: Export Signup Summary']; $jobId = Yii::$app->job->create('backend\\modules\\common\\job\\ExportStats', $exportArgs); return ['result' => 'success', 'data' => ['jobId' => $jobId, 'key' => $key]]; }
/** * The default implementation returns the names of the columns whose values have been populated into ChatConversation. */ public function fields() { return array_merge(parent::fields(), ['conversation', 'status', 'desk', 'client', 'lastChatTime' => function () { return TimeUtil::msTime2String($this->lastChatTime); //millisecond time stamp to string }]); }
public function actionExportMemberMonthly() { $startDate = $this->getQuery('start'); $endDate = $this->getQuery('end'); if (empty($startDate) || empty($endDate)) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $startDate = TimeUtil::msTime2String($startDate, 'Y-m'); $endDate = TimeUtil::msTime2String($endDate, 'Y-m'); $accountId = $this->getAccountId(); $condition = ['accountId' => $accountId, 'month' => ['$gte' => $startDate, '$lte' => $endDate]]; $key = 'FT_and_Pull_Participant_Summary_' . date('Ymd'); $header = ['month' => 'Month', 'operate' => 'Operate', 'number' => 'Number']; $exportArgs = ['key' => $key, 'header' => $header, 'condition' => serialize($condition), 'classFunction' => '\\backend\\models\\StatsMemberPropMonthly::preProcessData', 'description' => 'Direct: Export FT and Pull Participant Summary']; $jobId = \Yii::$app->job->create('backend\\modules\\common\\job\\ExportStats', $exportArgs); return ['result' => 'success', 'data' => ['jobId' => $jobId, 'key' => $key]]; }
public function actionOfflineExchange() { $params = $this->getParams(); if (empty($params['goods']) || empty($params['memberId']) || !isset($params['usedScore']) || empty($params['address']) || empty($params['receiveMode'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $userId = $this->getUserId(); $user = User::findByPk($userId); $user = ['id' => $user->_id, 'name' => $user->name]; if ($params['usedScore'] < 0) { throw new BadRequestHttpException(Yii::t('common', 'data_error')); } $member = Member::findByPk(new \MongoId($params['memberId'])); if (empty($member) || $member->isDisabled) { throw new InvalidParameterException(Yii::t('member', 'invalid_member_id')); } $goodsExchangeMap = []; $goodsIds = []; foreach ($params['goods'] as $item) { if ($item['count'] <= 0) { throw new BadRequestHttpException(Yii::t('common', 'data_error')); } $goodsExchangeMap[$item['id']] = $item['count']; $goodsIds[] = new \MongoId($item['id']); } $allExchangeGoods = Goods::getByIds($goodsIds); if (count($allExchangeGoods) != count($goodsIds)) { throw new InvalidParameterException(Yii::t('product', 'product_deleted')); } $usedScore = $params['usedScore']; $expectedScore = 0; $exchanges = []; foreach ($allExchangeGoods as $goods) { $exchangeCount = $goodsExchangeMap[(string) $goods->_id]; if ($goods->total === 0) { throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_sold_out')]); } else { if (!empty($goods->total) && $exchangeCount > $goods->total) { throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_not_enough')]); } } $expectedScore += $goods->score * $exchangeCount; $exchanges[] = ['goods' => $goods, 'count' => $exchangeCount]; } $params['expectedScore'] = $expectedScore; if ($member->score < $usedScore) { throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough')); } $successExchange = []; foreach ($exchanges as $exchangeItem) { $goods = $exchangeItem['goods']; $count = $exchangeItem['count']; $goodsCondition = ['_id' => $goods->_id]; $goodsModifier = ['$inc' => ['usedCount' => $count]]; $goodsRollbackModifier = ['$inc' => ['usedCount' => 0 - $count]]; if ($goods->total !== '') { $goodsCondition['total'] = ['$gte' => $count]; $goodsModifier['$inc']['total'] = 0 - $count; $goodsRollbackModifier['$inc']['total'] = $count; } $goodsUpdatedCount = Goods::updateAll($goodsModifier, $goodsCondition); if ($goodsUpdatedCount !== 1) { $this->_rollBackUsedCount($successExchange); throw new InvalidParameterException([(string) $goods->_id => Yii::t('product', 'goods_not_enough')]); } else { $goodsId = (string) $goods->_id; $successExchange[$goodsId] = $goodsRollbackModifier; } } $memberUpdatedCount = Member::updateAll(['$inc' => ['score' => 0 - $usedScore]], ['_id' => $member->_id, 'score' => ['$gte' => $usedScore]]); if ($memberUpdatedCount === 1) { $this->_saveLog($member, $exchanges, $params, $user); if (!empty($params['useWebhook'])) { $eventData = ['type' => Webhook::EVENT_PRODUCT_REDEEMED, 'member_id' => $params['memberId'], 'products' => $params['goods'], 'address' => $params['address'], 'postcode' => $params['postcode'], 'used_score' => $params['usedScore'], 'origin' => Member::PORTAL, 'account_id' => (string) $member->accountId, 'created_at' => TimeUtil::msTime2String(time() * TimeUtil::MILLI_OF_SECONDS, \DateTime::ATOM)]; Yii::$app->webhook->triggerEvent($eventData); } } else { $this->_rollBackUsedCount($successExchange); throw new InvalidParameterException(Yii::t('product', 'member_score_not_enough')); } }
/** * This function is provide to format time * @param $time, time stamp millisecond * @param $format, string * @return string */ private function _formatTime($time, $format = 'Y-m-d H:i:s') { return $time ? TimeUtil::msTime2String($time, $format) : ''; }