public function actionStatistics()
 {
     $startTime = $this->getQuery('startTime');
     $endTime = $this->getQuery('endTime');
     $accountId = $this->getAccountId();
     $condition = ['accountId' => $accountId, 'isDeleted' => BaseModel::NOT_DELETED];
     if (!empty($startTime) && !empty($endTime)) {
         $condition['createdAt'] = ['$gt' => new \MongoDate(TimeUtil::ms2sTime($startTime)), '$lt' => new \MongoDate(TimeUtil::ms2sTime($endTime))];
     }
     //get the original statistics from db.(raw data)
     $clientCount = ChatConversation::getClientCount($condition);
     $conversationCount = ChatConversation::count($condition);
     $clientMessageCount = ChatMessage::countClientMessage($condition);
     $conversationDailyStatistics = ChatConversation::getDailyData($condition);
     $messageDailyStatistics = ChatMessage::getDailyData($condition);
     //format the statistics for chart
     $categories = [];
     $messageCountSeries = [];
     $clientCountSeries = [];
     $conversationCountSeries = [];
     foreach ($conversationDailyStatistics as $conversationDay) {
         foreach ($messageDailyStatistics as $messageDay) {
             if ($conversationDay['date'] == $messageDay['date']) {
                 $conversationDay['messageCount'] = $messageDay['messageCount'];
             }
         }
         if (empty($conversationDay['messageCount'])) {
             $conversationDay['messageCount'] = 0;
         }
         $categories[] = $conversationDay['date'];
         $messageCountSeries[] = $conversationDay['messageCount'];
         $clientCountSeries[] = $conversationDay['clientCount'];
         $conversationCountSeries[] = $conversationDay['conversationCount'];
     }
     $statistics = ['categories' => $categories, 'series' => [['name' => 'helpdesk_users_count', 'data' => $clientCountSeries], ['name' => 'helpdesk_sessions_count', 'data' => $conversationCountSeries], ['name' => 'helpdesk_sent_message_count', 'data' => $messageCountSeries]]];
     return ['clientCount' => $clientCount, 'conversationCount' => $conversationCount, 'clientMessageCount' => $clientMessageCount, 'statistics' => $statistics];
 }
 public function actionUpdate($id)
 {
     $campaign = Campaign::findByPk($id);
     if (empty($campaign)) {
         throw new BadRequestHttpException(Yii::t('product', 'campaign_not_found'));
     }
     if (MongodbUtil::isExpired($campaign->endTime)) {
         throw new BadRequestHttpException(Yii::t('product', 'can_not_update'));
     }
     $params = $this->getParams();
     $params['startTime'] = empty($params['startTime']) ? $campaign->startTime : new \MongoDate(TimeUtil::ms2sTime($params['startTime']));
     $params['endTime'] = empty($params['endTime']) ? $campaign->endTime : new \MongoDate(TimeUtil::ms2sTime($params['endTime']));
     $attributeNames = null;
     foreach ($params as $key => $value) {
         if (in_array($key, ['productIds', 'gift', 'products', 'tags', 'channels'])) {
             $attributeNames[] = 'promotion';
             $promotion = $campaign->promotion;
             $promotion['type'] = Campaign::TYPE_PROMOTION_CODE;
             $key == 'productIds' ? $promotion['data'] = $params['productIds'] : '';
             $key == 'gift' ? $promotion['gift'] = $params['gift'] : '';
             $key == 'products' ? $promotion['products'] = $params['products'] : '';
             $key == 'tags' ? $promotion['tags'] = $params['tags'] : '';
             $key == 'channels' ? $promotion['channels'] = $params['channels'] : '';
             $campaign->promotion = $promotion;
         } else {
             if (in_array($key, ['participantCount', 'limitTimes'])) {
                 $attributeNames[] = $key;
                 $campaign->{$key} = is_null($value) ? null : intval($value);
             } else {
                 $attributeNames[] = $key;
                 $campaign->{$key} = $value;
             }
         }
     }
     $campaign->save(true, $attributeNames);
     return $campaign;
 }
Esempio n. 3
0
 /**
  * set the goods status and sale time,offshelf time
  * @return obejct, goods object
  * @param $params, array
  * @param $goods, object
  */
 public static function setGoodsStatusAndTime($params, $goods)
 {
     if (!empty($params['status']) && $params['status'] == Goods::STATUS_ON) {
         $goods->status = Goods::STATUS_ON;
         $goods->onSaleTime = new MongoDate();
     } else {
         if (!empty($params['status']) && $params['status'] == Goods::STATUS_OFF && isset($params['onSaleTime']) && $params['onSaleTime'] !== '') {
             if (time() > TimeUtil::ms2sTime($params['onSaleTime'])) {
                 throw new InvalidParameterException(Yii::t('product', 'not_less_than_current'));
             } else {
                 $goods->status = Goods::STATUS_OFF;
                 $goods->onSaleTime = new MongoDate(TimeUtil::ms2sTime($params['onSaleTime']));
             }
         } else {
             if (!empty($params['status']) && $params['status'] == Goods::STATUS_OFF && (!isset($params['onSaleTime']) || $params['onSaleTime'] === '')) {
                 $goods->status = Goods::STATUS_OFF;
                 $goods->onSaleTime = null;
                 $goods->offShelfTime = new MongoDate();
             }
         }
     }
     return $goods;
 }
Esempio n. 4
0
 /**
  * conver the coupon time
  */
 public static function converCouponTime($params)
 {
     if (!empty($params['time']['type']) && isset($params['time']['beginTime']) && isset($params['time']['endTime'])) {
         if (!in_array($params['time']['type'], [self::COUPON_ABSOLUTE_TIME, self::COUPON_RELATIVE_TIME])) {
             throw new InvalidParameterException(Yii::t('product', 'coupon_time_missing'));
         }
         if (Coupon::COUPON_ABSOLUTE_TIME == $params['time']['type']) {
             $params['time']['beginTime'] = new MongoDate(TimeUtil::ms2sTime($params['time']['beginTime']));
             $params['time']['endTime'] = new MongoDate(TimeUtil::ms2sTime($params['time']['endTime']));
         } else {
             $params['time']['beginTime'] = intval($params['time']['beginTime']);
             $params['time']['endTime'] = intval($params['time']['endTime']);
         }
     } else {
         throw new BadRequestHttpException(Yii::t('product', 'coupon_time_missing'));
     }
     return $params;
 }
 /**
  * check the promocode in the offline to get the score
  */
 public function actionCheck()
 {
     $params = $this->getQuery();
     if (empty($params['code']) || empty($params['memberId'])) {
         throw new BadRequestHttpException('missing params');
     }
     if (empty($params['exchangeTime'])) {
         $params['exchangeTime'] = time();
     } else {
         $params['exchangeTime'] = TimeUtil::ms2sTime($params['exchangeTime']);
     }
     $exchangeTime = new MongoDate($params['exchangeTime']);
     $member = Member::findByPk($params['memberId']);
     if (empty($member)) {
         throw new InvalidParameterException(Yii::t('member', 'no_member_find'));
     }
     if ($member->isDisabled) {
         throw new InvalidParameterException(Yii::t('member', 'member_invalid_not_exchange'));
     }
     $codes = explode(',', $params['code']);
     $codes = array_unique($codes);
     foreach ($codes as $key => $code) {
         $codes[$key] = (string) strtoupper(trim($code));
     }
     $accountId = $this->getAccountId();
     $datas = PromotionCode::checkCodeStatus($codes, $accountId, $member, $exchangeTime, $params);
     //sort the code
     $newCode = [];
     $totalScore = 0;
     foreach ($codes as $code) {
         foreach ($datas as $key => $data) {
             if ($data['code'] == $code) {
                 $newCode[] = $data;
             }
         }
     }
     return ['data' => $newCode];
 }
Esempio n. 6
0
 /**
  * @param begin=2015-10-01
  * @param end=2015-10-02
  */
 public function actionExportKlpMember()
 {
     $params = $this->getQuery();
     $accountId = $this->getAccountId();
     unset($params['accesstoken']);
     $condition = ['accountId' => $accountId];
     $key = '';
     if (!empty($params['begin'])) {
         $begin = TimeUtil::ms2sTime($params['begin']);
         $key = date('Y-m-d', $begin);
         $condition['updatedAt']['$gte'] = new \MongoDate($begin);
     }
     if (!empty($params['end'])) {
         $end = TimeUtil::ms2sTime($params['end']) + 24 * 3600;
         $key = !empty($key) ? $key . '_' . date('Y-m-d', $end) : date('Y-m-d', $end);
         $condition['updatedAt']['$lt'] = new \MongoDate($end);
     }
     if (empty($condition['updatedAt'])) {
         $key = date('Y-m-d');
         $condition['updatedAt']['$lt'] = new \MongoDate();
     }
     //only export enable member
     $condition['isDisabled'] = ['$ne' => true];
     $result = Member::findOne($condition);
     if (!empty($result)) {
         $condition = serialize($condition);
         $header = ['gender' => 'Title/ Salutation', 'firstName' => 'First name', 'lastName' => 'Surname', '工作職稱' => 'Job title', 'email' => 'Email address', 'tel' => 'Username (prefilled)', '密碼' => 'Password', 'tel_1' => 'Mobile phone number', '餐廳電話' => 'phone number', '經營型態' => 'Type of business', '每日供餐量' => 'Number of covers per day', '訂閱' => 'Opt-in / emailable (y/n)', '餐廳名稱' => 'Business name', '餐廳地址' => 'Business address', 'letter_unknow' => 'Street number / Letter', '地址' => 'Street name', '縣市' => 'City', 'county' => 'County', '郵遞區號' => 'Postcode', 'country' => 'Country', 'locations_unkonw' => 'Number of locations', '首選經銷商' => 'Wholesaler/ Supplier', '廚房廚師人數' => 'Number of kitchen staff', 'cuisine_unknow' => 'Type of cuisine', '感興趣產品' => 'UFS brands'];
         $fields = 'cardId,location,tags,properties,cardNumber,score,remarks,birth,socials';
         $exportArgs = ['collection' => 'member', 'fields' => $fields, 'key' => $key, 'header' => $header, 'accountId' => (string) $accountId, 'condition' => $condition, 'description' => 'Direct: export KLP member'];
         $jobId = Yii::$app->job->create('backend\\modules\\member\\job\\ExportKlpMember', $exportArgs);
         return ['result' => 'success', 'message' => 'exporting file', 'data' => ['jobId' => $jobId, 'key' => $key]];
     } else {
         return ['result' => 'error', 'message' => 'no datas', 'data' => []];
     }
 }
Esempio n. 7
0
 public function conver2MongoDate($attribute)
 {
     if ($attribute == 'startTime' || $attribute == 'endTime') {
         $time = $this->{$attribute};
         if (!empty($time) && is_numeric($time)) {
             $this->{$attribute} = new MongoDate(TimeUtil::ms2sTime($time));
         }
     } else {
         return true;
     }
 }
Esempio n. 8
0
 public static function refund($accountId, $refundInfo)
 {
     $refund = new self();
     $refundNumber = StringUtil::getUniqueCode('refund', 'T');
     $refund->transactionId = empty($refundInfo['transactionId']) ? '' : $refundInfo['transactionId'];
     $refund->refundNumber = $refundNumber;
     $refund->accountId = $accountId;
     $refund->orderNumber = $refundInfo['orderNumber'];
     $refund->expectedAmount = $refundInfo['expectedAmount'];
     $refund->realAmount = $refundInfo['realAmount'];
     $refund->admin = $refundInfo['admin'];
     $refund->user = $refundInfo['user'];
     $refund->refundMode = $refundInfo['refundMode'];
     $refund->refundAt = empty($refundInfo['refundAt']) ? new MongoDate() : new MongoDate(TimeUtil::ms2sTime($refundInfo['refundAt']));
     $comments = empty($refundInfo['comments']) ? '' : $refundInfo['comments'];
     $refund->comments = $comments;
     $refund->subject = $refundInfo['subject'];
     return $refund->Save();
 }
Esempio n. 9
0
 /**
  * Validator to transfer timestamp to mongoDate
  * @param unknown $attribute
  */
 public function toMongodate($attribute)
 {
     if (empty($this->{$attribute})) {
         return;
     }
     $this->{$attribute} = new \MongoDate(TimeUtil::ms2sTime($this->{$attribute}));
     return;
 }
 public function formateResponseData($data, $keyMap, $startDate, $endDate)
 {
     $destResult = ['statDate' => []];
     if (!empty($keyMap)) {
         foreach ($keyMap as $resultKey => $sourceKey) {
             $destResult[$resultKey] = [];
         }
     }
     if (!empty($data)) {
         $startTimestamp = intval(TimeUtil::ms2sTime($startDate));
         $endTimestamp = intval(TimeUtil::ms2sTime($endDate));
         for ($recur = $startTimestamp; $recur <= $endTimestamp; $recur += 60 * 60 * 24) {
             if (!empty($targetItem = $this->_getMatchDateItem($data, $recur))) {
                 // timezone to add 8 hours
                 $dateString = date("Y-m-d", $recur + 60 * 60 * 8);
                 $destResult['statDate'][] = $dateString;
                 foreach ($keyMap as $resultKey => $sourceKey) {
                     $destResult[$resultKey][] = $targetItem[$sourceKey];
                 }
             }
         }
     }
     return $destResult;
 }
 /**
  * Update Questionnaire.
  *
  * <b>Request Type</b>: PUT<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/content/questionnaire/{questionnaireId}<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for updating questionnaire.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     name: string<br/>
  *     startTime: string, startTime = "1429000112193"<br/>
  *     endTime: string, endTime = "1429000112193"<br/>
  *     description: string<br/>
  *     question:Array, question = [{"id": "55d6cb8be9c2fb022c8b4577","title": "math","type": "radio",
  *              "order": 0,"options": [{"icon": "support","content": "A option"},{"icon": "support",
  *              "content": "B option"}]},{"id": "55d6cb8be9c2fb022c8b4577","type": "input","title":
  *              "This is a problem","order": 1}]<br/>
  *     isPublished: boolean<br/>
  *
  * <b>Response Params:</b><br/>
  *     {
  *           "name": "name",
  *           "startTime": "1429000112193",
  *           "endTime": "1429000116193",
  *           "description": "good",
  *           "question": [
  *               {
  *                   "id": "55d6cb8be9c2fb022c8b4577",
  *                   "title": "math",
  *                   "type": "radio",
  *                   "order": 0,
  *                   "options": [
  *                       {
  *                           "icon": "support",
  *                           "content": "A option"
  *                       },
  *                       {
  *                           "icon": "support",
  *                           "content": "B option"
  *                       }
  *                   ]
  *               },
  *               {
  *                   "id": "55d6cb8be9c2fb022c8b4577",
  *                   "type": "input",
  *                   "title": "This is a problem",
  *                   "order": 1
  *               }
  *           ],
  *           "isPublished": false
  *     }
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * {
  *     "message": "OK",
  *     "data": ""
  * }
  * <pre>
  * </pre>
  */
 public function actionUpdate($id)
 {
     $id = new MongoId($id);
     $params = $this->getParams();
     $questionnaire = Questionnaire::getById($id);
     $question = [];
     $questionTitles = [];
     $questionExistIds = [];
     if (empty($questionnaire)) {
         throw new BadRequestHttpException(Yii::t('content', 'questionnaire_missing'));
     }
     if (!empty($params['startTime'])) {
         $params['startTime'] = new \MongoDate(TimeUtil::ms2sTime($params['startTime']));
     }
     if (!empty($params['endTime'])) {
         $params['endTime'] = new \MongoDate(TimeUtil::ms2sTime($params['endTime']));
     }
     $questionsItems = Question::getByIds($questionnaire->questions);
     if (!empty($params['question']) && count($params['question']) > 0) {
         foreach ($params['question'] as $questionInfo) {
             Question::checkTitle($questionInfo['title']);
             $question = ['_id' => empty($questionInfo['_id']) ? new MongoId() : new MongoId($questionInfo['_id']), 'title' => $questionInfo['title'], 'type' => $questionInfo['type'], 'order' => $questionInfo['order']];
             if (strcasecmp($questionInfo['type'], Question::TYPE_INPUT) != 0) {
                 if (is_array($questionInfo['options'])) {
                     if (Question::isQuestionOptionRepeat($questionInfo['options']) != null) {
                         $question['options'] = $questionInfo['options'];
                     }
                 }
             }
             if (in_array($question['title'], $questionTitles)) {
                 throw new InvalidParameterException(Yii::t('content', 'question_incorrect'));
             }
             $questionTitles[] = $question['title'];
             if (empty($questionInfo['id'])) {
                 $questionOption = new Question();
                 $questionOption->_id = new MongoId();
             } else {
                 $questionOption = Question::findByPk(new MongoId($questionInfo['id']));
             }
             $questionOption->title = $questionInfo['title'];
             $questionOption->type = $questionInfo['type'];
             $questionOption->order = $questionInfo['order'];
             $questionOption->options = empty($questionInfo['options']) ? [] : $questionInfo['options'];
             $questionOption->createdAt = new \MongoDate();
             if (!$questionOption->save()) {
                 throw new ServerErrorHttpException(Yii::t('content', 'update_fail'));
             }
             $questionExistIds[] = $questionOption->_id;
         }
         if (!empty($questionExistIds) && count($questionnaire->questions) >= count($questionExistIds)) {
             $isDeleteQuestion = array_diff($questionnaire->questions, $questionExistIds);
             if (count($isDeleteQuestion) > 0) {
                 $isDeQuestion = Question::deleteAll(['_id' => ['$in' => $isDeleteQuestion]]);
                 if (!$isDeQuestion) {
                     throw new ServerErrorHttpException(Yii::t('content', 'update_fail'));
                 }
             }
         }
     }
     if (!empty($params['name']) && !empty($params['startTime']) && !empty($params['endTime'])) {
         $questionnaire->name = $params['name'];
         $questionnaire->startTime = $params['startTime'];
         $questionnaire->endTime = $params['endTime'];
         $questionnaire->description = !isset($params['description']) ? '' : $params['description'];
     }
     $questionnaire->isPublished = $params['isPublished'];
     $questionnaire->createdAt = new \MongoDate();
     if (!empty($params['question']) && count($params['question']) > 0) {
         $questionnaire->questions = $questionExistIds;
     }
     unset($questionnaire->createdAt);
     if (!$questionnaire->save()) {
         throw new ServerErrorHttpException(Yii::t('common', 'update_fail'));
     } else {
         return ["message" => "OK", "data" => ""];
     }
 }
Esempio n. 12
0
 public static function createCondition($params, $accountId)
 {
     $comma = ',';
     $condition = ['accountId' => $accountId];
     if (!empty($params['code'])) {
         $condition = array_merge($condition, ['code' => $params['code']]);
     }
     if (!empty($params['memberId'])) {
         $condition = array_merge($condition, ['member.id' => new \MongoId($params['memberId'])]);
     }
     if (!empty($params['filter'])) {
         $condition = array_merge($condition, ['member.type' => ['$in' => $params['filter']]]);
     }
     if (array_key_exists('key', $params) && !empty($params['key'])) {
         $key = $params['key'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new \MongoRegex("/{$key}/i");
         $search = ['$or' => [['code' => $keyReg], ['member.name' => $keyReg], ['member.phone' => $keyReg], ['productName' => $keyReg], ['sku' => $keyReg]]];
         $condition = array_merge($condition, $search);
     }
     if (!empty($params['startTime'])) {
         $condition['redeemTime']['$gte'] = new MongoDate(TimeUtil::ms2sTime($params['startTime']));
     }
     if (!empty($params['endTime'])) {
         $condition['redeemTime']['$lte'] = new MongoDate(TimeUtil::ms2sTime($params['endTime']));
     }
     if (!empty($params['accounts'])) {
         $accounts = explode($comma, $params['accounts']);
         $channelIds = [];
         foreach ($accounts as $account) {
             $channelIds[] = $account;
         }
         $channelCondition = ['$or' => [['usedFrom.id' => ['$in' => $channelIds]], ['usedFrom.type' => ['$in' => $channelIds]]]];
         $condition = ['and', $condition, $channelCondition];
     }
     return $condition;
 }
Esempio n. 13
0
 /**
  * support to get condtion to search log used in api for index function and export function
  */
 public static function createCondition($params, $accountId)
 {
     $condition = ['accountId' => $accountId];
     if (array_key_exists('key', $params) && '' != $params['key']) {
         $condition = self::createKeyWordCondition($params['key'], $condition);
     }
     $usedTime = [];
     if (isset($params['startTime'])) {
         $usedTime['createdAt']['$gte'] = new \MongoDate(TimeUtil::ms2sTime($params['startTime']));
     }
     if (isset($params['endTime'])) {
         $usedTime['createdAt']['$lte'] = new \MongoDate(TimeUtil::ms2sTime($params['endTime']));
     }
     $condition = array_merge($condition, $usedTime);
     $usedScore = [];
     if (isset($params['usedScoreMin'])) {
         $usedScore['usedScore']['$gte'] = $params['usedScoreMin'] + 0;
     }
     if (isset($params['usedScoreMax'])) {
         $usedScore['usedScore']['$lte'] = $params['usedScoreMax'] + 0;
     }
     $condition = array_merge($condition, $usedScore);
     if (!empty($params['memberId'])) {
         $condition['memberId'] = new \MongoId($params['memberId']);
     }
     if (!empty($params['channelId'])) {
         $condition['usedFrom.id'] = $params['channelId'];
     }
     if (isset($params['isRemoved'])) {
         $condition['isRemoved'] = $params['isRemoved'];
     }
     if (!empty($params['usedFrom'])) {
         $condition = array_merge($condition, $params['usedFrom']);
     }
     if (isset($params['isDelivered'])) {
         $condition = self::createIsDeliveredCondition($params['isDelivered'], $condition);
     }
     if (isset($params['receiveMode'])) {
         $condition = self::createReceiveModeCondition($params['receiveMode'], $condition);
     }
     // this condition must in the end,because this condition return is ['and', $condition, $channelCondition], you can see andWhere()
     if (!empty($params['accounts'])) {
         $condition = self::createChannelCondition($condition, $params['accounts']);
     }
     return $condition;
 }
Esempio n. 14
0
 public static function getCondition($params, $accountId)
 {
     $comma = ',';
     $condition = ['accountId' => $accountId, 'isDeleted' => self::NOT_DELETED];
     if (!empty($params['accounts'])) {
         $accounts = explode($comma, $params['accounts']);
         $ids = [];
         $origins = [];
         foreach ($accounts as $account) {
             if (self::MONGO_ID_LENGTH == strlen($account)) {
                 $ids[] = $account;
             } else {
                 $origins[] = $account;
             }
         }
         $channelCondition = ['socialAccountId' => ['$in' => $ids], 'origin' => ['$in' => [self::WECHAT, self::WEIBO, self::ALIPAY]]];
         if (count($origins) > 0) {
             $newCondition = ['$or' => [$channelCondition, ['origin' => ['$in' => $origins]]]];
             $channelCondition = $newCondition;
         }
         $condition = array_merge($condition, $channelCondition);
     }
     $cardStatusCondition = [];
     if (!empty($params['cardExpiredAt'])) {
         $cardStatusCondition = $params['cardExpiredAt'];
     }
     if (!empty($params['cards'])) {
         $cards = explode($comma, $params['cards']);
         $cardIds = [];
         foreach ($cards as $card) {
             $cardIds[] = new \MongoId($card);
         }
         $cards = ['$in' => $cardIds];
         $condition = array_merge($condition, ['cardId' => $cards]);
     }
     if (!empty($params['tags'])) {
         $tags = explode($comma, $params['tags']);
         $tags = ['$all' => $tags];
         $condition = array_merge($condition, ['tags' => $tags]);
     }
     $searchCondition = [];
     if (isset($params['searchKey']) && $params['searchKey'] != '') {
         $key = $params['searchKey'];
         //get the type of condition from search key
         $searchCondition = self::createCondition($key, $accountId);
     }
     // After run new MongoDate, The time can lost accuracy, so it will plus 1 or subtract 1.
     if (!empty($params['startTime'])) {
         $startTime = TimeUtil::ms2sTime($params['startTime']) - 1;
         $condition['createdAt']['$gt'] = new \MongoDate($startTime);
     }
     if (!empty($params['endTime'])) {
         $endTime = TimeUtil::ms2sTime($params['endTime']) + 1;
         $condition['createdAt']['$lt'] = new \MongoDate($endTime);
     }
     if (!empty($params['gender'])) {
         $gender = ['properties' => ['$elemMatch' => ['name' => self::DEFAULT_PROPERTIES_GENDER, 'value' => strtolower($params['gender'])]]];
         $condition = array_merge($condition, $gender);
     }
     foreach ($params as $key => $value) {
         if (!empty($value)) {
             if ($key == 'country' || $key == 'province' || $key == 'city') {
                 $key = 'location.' . $key;
                 $condition = array_merge($condition, [$key => $value]);
             }
         }
     }
     //memberId
     if (!empty($params['memberId'])) {
         $memberIds = explode(',', $params['memberId']);
         $memberIds = MongodbUtil::toMongoIdList($memberIds);
         $condition = array_merge($condition, ['_id' => ['$in' => $memberIds]]);
     }
     return ['condition' => $condition, 'cardStatusCondition' => $cardStatusCondition, 'searchCondition' => $searchCondition];
 }
Esempio n. 15
0
 /**
  * Record offline payment message.
  * @param  array $paymentInfo
  */
 public static function offlinePayment($paymentInfo, $accountId)
 {
     $payment = new self();
     $payment->accountId = $accountId;
     $payment->orderNumber = $paymentInfo['orderNumber'];
     $payment->user = $paymentInfo['user'];
     $payment->status = self::STATUS_PAID;
     $payment->payMode = $paymentInfo['payMode'];
     $payment->expectedAmount = $paymentInfo['expectedAmount'];
     $payment->realAmount = empty($paymentInfo['realAmount']) ? '' : $paymentInfo['realAmount'];
     $payment->payAccount = $paymentInfo['payAccount'];
     $payment->paymentTime = new MongoDate(TimeUtil::ms2sTime($paymentInfo['paymentTime']));
     $payment->subject = $paymentInfo['subject'];
     return $payment->save();
 }
Esempio n. 16
0
 /**
  * Search product by conditions
  * @param Array $params
  * @param string $accountId
  * @return product info
  */
 public static function search($params, $accountId)
 {
     $query = self::find();
     $comma = ',';
     $condition = ['accountId' => $accountId, 'isDeleted' => StoreGoods::NOT_DELETED];
     if (!empty($params['categoryIds'])) {
         $categorys = explode($comma, $params['categoryIds']);
         $categoryIds = [];
         foreach ($categorys as $category) {
             $categoryIds[] = new \MongoId($category);
         }
         $categorys = ['$in' => $categoryIds];
         $condition['categoryId'] = $categorys;
     }
     if (array_key_exists('searchKey', $params) && '' != $params['searchKey']) {
         $key = $params['searchKey'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new \MongoRegex("/{$key}/i");
         $search = ['$or' => [['productName' => $keyReg], ['sku' => $keyReg]]];
         $condition = array_merge($condition, $search);
     }
     if (!empty($params['status'])) {
         $condition['status'] = $params['status'];
     }
     if (!empty($params['storeId'])) {
         $condition['storeId'] = $params['storeId'];
     }
     if (isset($params['saleTimeFrom']) && $params['saleTimeFrom'] !== '') {
         $condition['onSaleTime']['$gte'] = new \MongoDate(TimeUtil::ms2sTime($params['saleTimeFrom']));
     }
     if (isset($params['saleTimeTo']) && $params['saleTimeTo'] !== '') {
         $condition['onSaleTime']['$lte'] = new \MongoDate(TimeUtil::ms2sTime($params['saleTimeTo']));
     }
     if (isset($params['priceFrom']) && $params['priceFrom'] !== '') {
         $condition['price']['$gte'] = floatval($params['priceFrom']);
     }
     if (isset($params['priceTo']) && $params['priceTo'] !== '') {
         $condition['price']['$lte'] = floatval($params['priceTo']);
     }
     $query->orderBy(self::normalizeOrderBy($params));
     $query->where($condition);
     $searchQuery = ['query' => $query];
     return new ActiveDataProvider($searchQuery);
 }
Esempio n. 17
0
 /**
  * Get qrcode statistics information
  *
  * <b>Request Type</b>: GET<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/channel/qrcode/statistics<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used to view qrcode detail.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     channelId: string<br/>
  *     qrcode: string<br/>
  *     startDate: integer<br/>
  *     endDate: integer<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     array, json array to get qrcode statistics information<br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *  "scan": [50, 60, 200, 13, 34, 100, 90, 50, 150, 300],
  *  "subscribe": [351, 316, 29, 963, 292, 72, 52, 501, 772, 472],
  *  "statDate": ["2015-01-10","2015-01-11","2015-01-12","2015-01-13","2015-01-14","2015-01-15","2015-01-16","2015-01-17","2015-01-18","2015-01-19"],
  *  "ydayStat": {
  *      "scan":0,
  *      "subscribe":0,
  *      "totalScan":0,
  *      "totalSubscribe":0
  *  }
  * </pre>
  */
 public function actionStatistics()
 {
     $channelId = $this->getChannelId();
     $qrcodeId = $this->getQuery("qrcodeId");
     $startDate = $this->getQuery("startDate");
     $endDate = $this->getQuery("endDate");
     $result = Yii::$app->weConnect->getQrcodeStatistics($channelId, $qrcodeId, $startDate, $endDate);
     $ydayDate = date('Y-m-d', strtotime('-1 day'));
     $destResult = ['ydayStat' => ['scan' => 0, 'subscribe' => 0, 'totalScan' => 0, 'totalSubscribe' => 0]];
     if (isset($result[$ydayDate])) {
         $ydayData = $result[$ydayDate];
         $destResult['ydayStat']['scan'] = $ydayData['scan'];
         $destResult['ydayStat']['subscribe'] = $ydayData['subscribe'];
         $destResult['ydayStat']['totalScan'] = $ydayData['totalScan'];
         $destResult['ydayStat']['totalSubscribe'] = $ydayData['totalSubscribe'];
     }
     // timezone to add 8 hours
     $startTimestamp = intval(TimeUtil::ms2sTime($startDate)) + 60 * 60 * 8;
     $endTimestamp = intval(TimeUtil::ms2sTime($endDate)) + 60 * 60 * 8;
     for ($recur = $startTimestamp; $recur <= $endTimestamp; $recur += 60 * 60 * 24) {
         $dateItem = date("Y-m-d", $recur);
         if (isset($result[$dateItem])) {
             $destResult['statDate'][] = $dateItem;
             $destResult['scan'][] = $result[$dateItem]['scan'];
             $destResult['subscribe'][] = $result[$dateItem]['subscribe'];
         }
     }
     return $destResult;
 }
Esempio n. 18
0
 public function validateTime($attribute)
 {
     $time = $this->{$attribute};
     $time = TimeUtil::ms2sTime($time);
     $this->{$attribute} = new \MongoDate($time);
     if ($attribute == 'startTime') {
         $now = time();
         if ($time < $now) {
             throw new InvalidParameterException(['beginDatePicker' => \Yii::t('product', 'invalid_start_time')]);
         }
     } else {
         if ($attribute == 'endTime') {
             if ($time <= MongodbUtil::MongoDate2TimeStamp($this->startTime)) {
                 throw new InvalidParameterException(['endDatePicker' => \Yii::t('product', 'invalid_end_time')]);
             }
         }
     }
 }
Esempio n. 19
0
 /**
  * create condition for search
  */
 public static function createCondition($params, $accountId)
 {
     $condition = ['accountId' => $accountId, 'isDeleted' => self::NOT_DELETED];
     //order number
     if (!empty($params['orderNumber'])) {
         $orderNumber = StringUtil::regStrFormat(trim($params['orderNumber']));
         $condition['orderNumber'] = new MongoRegex("/{$orderNumber}/i");
     }
     if (!empty($params['memberId'])) {
         $condition['consumer.id'] = $params['memberId'];
     }
     //order status
     if (!empty($params['status'])) {
         $status = explode(',', $params['status']);
         $condition['status'] = ['$in' => $status];
     }
     //store id
     if (!empty($params['storeId'])) {
         $condition['storeId'] = new \MongoId($params['storeId']);
     }
     //createdAt
     // After run new MongoDate, The time can lost accuracy, so it will plus 1 or subtract 1.
     if (!empty($params['beginCreatedAt'])) {
         $beginCreatedAt = TimeUtil::ms2sTime($params['beginCreatedAt']) - 1;
         $condition['createdAt']['$gt'] = new MongoDate($beginCreatedAt);
     }
     if (!empty($params['endCreatedAt'])) {
         $endCreatedAt = TimeUtil::ms2sTime($params['endCreatedAt']) + 1;
         $condition['createdAt']['$lt'] = new MongoDate($endCreatedAt);
     }
     //price
     if (!empty($params['minAmount'])) {
         $condition['totalPrice']['$gte'] = floatval($params['minAmount']);
     }
     if (!empty($params['maxAmount'])) {
         $condition['totalPrice']['$lte'] = floatval($params['maxAmount']);
     }
     //staff info
     if (!empty($params['staff'])) {
         $staffName = StringUtil::regStrFormat(trim($params['staff']));
         $staffName = new MongoRegex("/{$staffName}/i");
         $condition['staff.name'] = $staffName;
     }
     //member info
     if (!empty($params['member'])) {
         $member = StringUtil::regStrFormat(trim($params['member']));
         $condition['consumer.name'] = new MongoRegex("/{$member}/i");
     }
     return $condition;
 }
Esempio n. 20
0
 public function actionUpdate($id)
 {
     $params = $this->getParams();
     if (empty($params['status']) || !isset($params['price'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $storeGoods = StoreGoods::findByPk(new \MongoId($id));
     if (empty($storeGoods)) {
         throw new InvalidParameterException(Yii::t('store', 'invalid_goods_id'));
     }
     $storeGoods->pictures = empty($params['pictures']) ? $storeGoods->pictures : $params['pictures'];
     $price = floatval($params['price']);
     if ($price <= 0) {
         throw new InvalidParameterException(Yii::t('store', 'price_error'));
     }
     $storeGoods->price = $price;
     if ($params['status'] == StoreGoods::STATUS_ON) {
         $storeGoods->status = StoreGoods::STATUS_ON;
         $storeGoods->onSaleTime = new \MongoDate();
     } else {
         if ($params['status'] == StoreGoods::STATUS_OFF && isset($params['onSaleTime']) && $params['onSaleTime'] !== '') {
             if (time() > TimeUtil::ms2sTime($params['onSaleTime'])) {
                 throw new InvalidParameterException(['onSaleTime' => \Yii::t('product', 'not_less_than_current')]);
             } else {
                 $storeGoods->status = StoreGoods::STATUS_OFF;
                 $storeGoods->onSaleTime = new \MongoDate(TimeUtil::ms2sTime($params['onSaleTime']));
             }
         } else {
             if ($params['status'] == StoreGoods::STATUS_OFF && (!isset($params['onSaleTime']) || $params['onSaleTime'] === '')) {
                 $storeGoods->status = StoreGoods::STATUS_OFF;
                 $storeGoods->onSaleTime = null;
                 $storeGoods->offShelfTime = new \MongoDate();
             } else {
                 throw new BadRequestHttpException(Yii::t('common', 'data_error'));
             }
         }
     }
     if ($storeGoods->save(true)) {
         $storeGoods->_id = (string) $storeGoods->_id;
         return $storeGoods;
     } else {
         throw new ServerErrorHttpException(Yii::t('common', 'save_fail'));
     }
 }
 public function actionExportCampaignAnalysis()
 {
     $params = $this->getQuery();
     if (empty($params['type']) || empty($params['startDate']) || empty($params['endDate'])) {
         throw new InvalidParameterException('missing params');
     }
     //add a param called all for export all campaigns
     $types = self::$types;
     if (!in_array($params['type'], $types)) {
         throw new InvalidParameterException('invaild type');
     }
     $startDate = TimeUtil::ms2sTime($params['startDate']);
     $endDate = TimeUtil::ms2sTime($params['endDate']) + 3600 * 24;
     $header = self::getExportFileHeader($startDate, $endDate);
     $params['type'] = intval($params['type']);
     $sort = ['productName' => 1, 'createdAt' => 1];
     $accountId = $this->getAccountId();
     $condition = ['type' => $params['type'], 'createdAt' => ['$gte' => new MongoDate($startDate), '$lt' => new MongoDate($endDate)], 'accountId' => $accountId];
     $key = Yii::t('product', 'active_name') . '_' . date('Y-m-d', $startDate) . '_' . date('Y-m-d', $endDate);
     $fields = 'createdAt,productName,total,type';
     $args = ['accountId' => (string) $accountId, 'key' => $key, 'header' => $header, 'fields' => $fields, 'sort' => $sort, 'params' => ['header' => $header], 'collection' => 'statsPromotionCodeAnalysis', 'condition' => serialize($condition), 'classFunction' => '\\backend\\modules\\product\\models\\StatsPromotionCodeAnalysis::preProcessData', 'description' => 'Direct: Export stats PromotionCodeAnalysis data'];
     $jobId = Yii::$app->job->create('backend\\modules\\product\\job\\ExportPromotionCodeAnalysis', $args);
     unset($params, $args);
     return ['result' => 'success', 'message' => 'exporting file', 'data' => ['jobId' => $jobId, 'key' => $key]];
 }