/** * get sign package * @return array */ public function getSignPackage($channelId = null) { /* $channelId = '54d9c155e4b0abe717853ee1'; if (!empty($channelId)) { $sign = Yii::$app->wechatSdk->getSignPackage($channelId); return $sign; } */ // 注意 URL 一定要动态获取,不能 hardcode. $url = $this->refererUrl; if (empty($url)) { $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; $url = "{$protocol}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; $this->refererUrl = $url; } $jsapiTicket = $this->_getJsApiTicket(); LogUtil::error(['message' => 'get jsapiTicket with old method', 'jsapiTicket' => $jsapiTicket], 'weixin'); $timestamp = time(); $nonceStr = StringUtil::rndString(16, StringUtil::ALL_DIGITS_LETTERS); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}"; $signature = sha1($string); $signPackage = array("appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "signature" => $signature, "url" => $url); LogUtil::error(['message' => 'get signPackage with old method', 'signPackage' => json_encode($signPackage)], 'weixin'); return $signPackage; }
/** * @param $data array eg: [['mobile'=>'0912345678', 'smsContent'=>'恭喜中奖了'], ...] * @param $smsName string eg: 'cny_winners' * @param $smsRecord MongoId */ public static function sendSms($data, $smsName, $smsRecordId, $accountId) { BulkSmsRecord::updateProcessById($smsRecordId, 1); // 正在發送 try { if (!empty($data)) { foreach ($data as $sms) { $mobile = self::processSmsMobile($accountId, $sms['mobile']); $response = MessageUtil::sendMobileMessage($mobile, $sms['smsContent'], $accountId); BulkSmsLog::createSmsLog($sms['mobile'], $sms['smsContent'], $response, $smsRecordId, $accountId); if (!$response) { LogUtil::error(['message' => '群發簡訊失敗', 'mobile' => $mobile, 'SMSContent' => $sms['smsContent']], 'bulkSms'); BulkSmsFailed::createSmsFailed($sms['mobile'], $sms['smsContent'], $smsRecordId, $accountId); } unset($response, $mobile); } BulkSmsRecord::updateProcessById($smsRecordId, 2); // 發送完成 } } catch (\Exception $e) { LogUtil::error(['message' => 'EarlyBirdSms發送失敗', 'error' => $e], 'earlybird'); BulkSmsRecord::updateProcessById($smsRecordId, 3); // 發送故障 throw $e; } }
public static function createStatsCouponLog($dateStr, $stats) { //check data whether exists today $result = ModelStatsCouponLogDaily::findOne(['date' => $dateStr]); if ($result) { LogUtil::info(['message' => $dateStr . ' coupon log data is exists'], 'resque'); return true; } $stats = CouponLog::formatStruct($stats); $data = $couponIds = []; foreach ($stats as $stat) { $receivedKey = $stat['couponId'] . '_' . CouponLog::RECIEVED; $redeemedKey = $stat['couponId'] . '_' . CouponLog::REDEEMED; if (!in_array($stat['couponId'], $couponIds)) { $couponIds[] = $stat['couponId']; $receivedNum = isset($stats[$receivedKey]['count']) ? $stats[$receivedKey]['count'] : 0; $redeemedNum = isset($stats[$redeemedKey]['count']) ? $stats[$redeemedKey]['count'] : 0; $data[] = ['couponId' => $stat['couponId'], 'accountId' => $stat['accountId'], 'recievedNum' => $receivedNum + $redeemedNum, 'redeemedNum' => $redeemedNum, 'date' => $dateStr]; } } unset($stat, $stats, $couponIds); if (false === ModelStatsCouponLogDaily::batchInsert($data)) { LogUtil::error(['message' => 'Faild to create statis daily couponlog', 'date' => $dateStr, 'data' => json_encode($data)], 'resque'); } }
/** * This method is used to valide the user's authority with token in help desk chat system. * This method is invoked right before an action is executed. * * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method * will determine whether the action should continue to run. * * If you override this method, your code should look like the following: * * ```php * public function beforeAction($action) * { * if (parent::beforeAction($action)) { * // your custom code here * return true; // or false if needed * } else { * return false; * } * } * ``` * @param Action $action the action to be executed. * @return boolean whether the action should continue to run. * @author Harry Sun */ public function beforeAction($action) { $route = $this->id . '/' . $action->id; //init i18n configuration from user agent Yii::$app->language = LanguageUtil::getBrowserLanguage(); // the action ids without auth $noAuth = ['site/login', 'site/logout', 'conversation/state', 'conversation/message', 'setting/index', 'setting/self-helpdesk', 'site/send-reset-password-email', 'site/reset-password', 'help-desk/check-auth', 'conversation/user-state', 'issue/create-from-js-sdk', 'issue/remove-attachment']; if (in_array($route, $noAuth)) { return true; } else { $accessToken = $this->getQuery('accesstoken'); $info = Token::getToken($accessToken); if (!empty($info) && isset($info->expireTime) && !MongodbUtil::isExpired($info->expireTime)) { Yii::$app->language = empty($info->language) ? LanguageUtil::DEFAULT_LANGUAGE : $info->language; $expireTime = new \MongoDate(time() + Token::EXPIRE_TIME); if ($info->expireTime < $expireTime) { $info->expireTime = $expireTime; } $updateResult = $info->update(); return true; } LogUtil::error(['accessToken' => $accessToken, 'message' => 'You have not logined']); throw new \yii\web\UnauthorizedHttpException('You have not logined'); } }
/** * @args {"description": "Delay: Stats of questionnaire"} */ public function perform() { $args = $this->args; //Get date from args or today $date = empty($args['date']) ? '' : $args['date']; $datetime = TimeUtil::getDatetime($date); $dateStr = date('Y-m-d', $datetime); $stats = QuestionnaireLog::getStats($dateStr); $statsRows = []; foreach ($stats as $stat) { $questionnaireId = $stat['_id']['questionnaireId']; $accountId = $stat['_id']['accountId']; //if $dailyStats exists, update it; else , create $dailyStats = ModelStatsQuestionnaireDaily::getByQuestionnaireAndDate($accountId, $questionnaireId, $dateStr); if (empty($dailyStats)) { $statsRows[] = ['accountId' => $accountId, 'questionnaireId' => $questionnaireId, 'date' => $dateStr, 'count' => $stat['count']]; } else { $dailyStats->count = $stat['count']; //catch exception to avoid block batch insert try { $dailyStats->save(true, ['count']); } catch (Exception $e) { LogUtil::error(['Update StatsQuestionnaireDaily error' => $e->getMessage(), 'StatsQuestionnaireDaily' => $dailyStats]); continue; } } } ModelStatsQuestionnaireDaily::batchInsert($statsRows); return true; }
/** * @args {"description": "Delay: stats of account orders"} * @author Rex Chen */ public function perform() { $stats = StatsMemberOrder::getStatsByAccount(); if (!ModelStatsOrder::batchInsert($stats)) { LogUtil::error(['message' => 'Stats account order', 'date' => date('Y-m-d'), 'statsOrder' => $stats], 'resque'); } }
public function perform() { $args = $this->args; if (empty($args['status']) || empty($args['header']) || empty($args['key']) || empty($args['accountId']) || empty($args['sku'])) { LogUtil::error(['message' => 'Faild to export code, missing params', 'args' => $args], 'resque'); return false; } $fileName = $args['key']; $filePath = ExcelUtil::getFile($fileName, 'csv'); $condition = ExcelUtil::processCondition(unserialize($args['condition'])); $baseData = ['sku' => $args['sku'], 'status' => $args['status']]; ExcelUtil::exportWithMongo('promotionCode', $args['fields'], $filePath, $condition); $classFunction = '\\backend\\modules\\product\\models\\PromotionCode::preProcessCodeData'; if (!file_exists($filePath)) { return false; } ExcelUtil::processRowsData($args['header'], $filePath, $classFunction, $baseData); $newFilePath = ExcelUtil::getDownloadFile($filePath); $hashKey = ExcelUtil::setQiniuKey($newFilePath, $fileName); @unlink($filePath); @unlink($newFilePath); 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; } }
public function perform() { $args = $this->args; if (empty($args['header']) || empty($args['condition']) || empty($args['key']) || empty($args['accountId']) || empty($args['collection']) || empty($args['sort']) || empty($args['fields']) || empty($args['classFunction']) || !isset($args['params'])) { LogUtil::error(['message' => 'missing params when create job for export file', 'args' => $args]); return false; } $fileName = $args['key']; $filePath = ExcelUtil::getFile($fileName, 'csv'); $condition = ExcelUtil::processCondition(unserialize($args['condition'])); ExcelUtil::exportWithMongo($args['collection'], $args['fields'], $filePath, $condition, $args['sort']); if (!file_exists($filePath)) { LogUtil::error(['message' => 'Can not find this file', 'fileName' => $filePath, 'condition' => $condition, 'args' => $args], 'resque'); return false; } self::processProductInfoData($args['header'], $filePath, $args['classFunction'], $args['params']); $newFilePath = ExcelUtil::getDownloadFile($filePath); $hashKey = ExcelUtil::setQiniuKey($newFilePath, $fileName); @unlink($filePath); @unlink($newFilePath); 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; } }
public function actionCreate() { $params = $this->getParams(); if (isset($params['total'])) { $params['total'] = intval($params['total']); } if (isset($params['limit'])) { $params['limit'] = intval($params['limit']); } $params['accountId'] = $this->getAccountId(); //check the coupon time $params = Coupon::converCouponTime($params); //check the coupon storeType Coupon::checkCouponStore($params); //check coupon field Coupon::checkCouponField($params); $coupon = new Coupon(); $coupon->load($params, ''); if (false === $coupon->save()) { LogUtil::error(['message' => 'Faild to save coupon', 'params' => $params, 'error' => $coupon->getErrors()], 'product'); throw new ServerErrorHttpException(Yii::t('common', 'save_fail')); } else { //create shortUrl $longUrl = Yii::$app->request->hostInfo . '/mobile/product/coupon?couponId=' . $coupon->_id; $shortObj = Yii::$app->urlService->shortenUrl($longUrl); $coupon->url = $shortObj['Short']; $coupon->save(); return $coupon; } }
public function actionFrontend() { $params = $this->getQuery(); if (self::ERROR_TYPE === $params[self::PARAM_TYPE]) { LogUtil::error($params, self::FRONTEND); } else { LogUtil::info($params, self::FRONTEND); } header(self::IMAGE_CONTENT_TYPE); }
private function _upload($filePath, $fileName) { $result = Yii::$app->qiniu->upload($filePath, $fileName); @unlink($filePath); if (empty($result->Err)) { return true; } else { LogUtil::error(['message' => 'fail to upload file to qiniu', 'result' => json_encode($result)], 'qiniu'); return false; } }
public function perform() { $args = $this->args; if (empty($args['data']) || empty($args['accountId']) || empty($args['modelContent']) || empty($args['smsBatch'])) { ResqueUtil::log(['status' => 'fail to send sms', 'message' => 'missing params', 'args' => $args]); LogUtil::error(['message' => 'missing params in job', 'args' => $args], 'Sms'); } $data = $args['data']; $accountId = $args['accountId']; $modelContent = $args['modelContent']; $smsBatch = $args['smsBatch']; $failureCount = 0; $successCount = 0; $totalCount = 0; try { if (!empty($data)) { foreach ($data as $sms) { if ($sms['mobile'] != '') { $response = MessageUtil::sendMobileMessage($sms['mobile'], $sms['content'], $accountId); // $response = MessageUtil::sendMobileMessage($sms['mobile'], $sms['content']); BulkSmsLog::createSmsLog($sms['mobile'], $sms['content'], $response, $smsBatch, $accountId); if (!$response) { $failureCount++; LogUtil::error(['message' => '群發簡訊失敗', 'mobile' => $sms['mobile'], 'SMSContent' => $sms['content']], 'bulkSms'); BulkSmsFailed::createSmsFailed($sms['mobile'], $sms['content'], $smsBatch, $accountId); } else { $successCount++; LogUtil::error(['message' => '群發簡訊成功', 'mobile' => $sms['mobile'], 'SMSContent' => $sms['content']], 'bulkSms'); BulkSmsSuccess::createSmsSuccess($sms['mobile'], $sms['content'], $smsBatch, $accountId); } unset($response); } else { LogUtil::error(date('Y-m-d h:i:s') . '号码为空.'); $failureCount++; } } $totalCount = $successCount + $failureCount; //record result $SmsResultModel = new SmsResultModel(); $SmsResultModel->successRecord = $successCount; $SmsResultModel->failureRecord = $failureCount; $SmsResultModel->totalRecord = $totalCount; $SmsResultModel->smsBatch = $smsBatch; $SmsResultModel->accountId = $accountId; $SmsResultModel->modelContent = $modelContent; $SmsResultModel->save(); } } catch (\Exception $e) { LogUtil::error(['message' => 'Sms發送失敗', 'error' => $e], 'sms'); throw $e; } }
public function actionAnswer() { $params = $this->getParams(); if (empty($params['questionnaireId']) || empty($params['answers'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $user = []; if (!empty($params['user']['channelId']) && !empty($params['user']['openId'])) { $channelId = $params['user']['channelId']; $openId = $params['user']['openId']; $user = $params['user']; try { $follower = Yii::$app->weConnect->getFollowerByOriginId($openId, $channelId); $user['name'] = empty($follower['nickname']) ? '' : $follower['nickname']; } catch (ApiDataException $e) { LogUtil::error(['message' => 'Answer questionnaire failed to get follower info', 'param' => ['openId' => $openId, 'channelId' => $channelId]]); } } $questionnaireId = new MongoId($params['questionnaireId']); $questionnaire = Questionnaire::findByPk($questionnaireId); //error questionnaire id or un published questionnaire if (empty($questionnaire) || !$questionnaire->isPublished) { throw new InvalidParameterException(Yii::t('content', 'invalid_questionnaire')); } //questionnaire has not begun $now = time(); if (MongodbUtil::MongoDate2TimeStamp($questionnaire->startTime) > $now) { throw new InvalidParameterException(Yii::t('content', 'questionnaire_not_began')); } //questionnaire expired if (MongodbUtil::MongoDate2TimeStamp($questionnaire->endTime) < $now) { throw new InvalidParameterException(Yii::t('content', 'questionnaire_expired')); } if (!empty($user)) { $questionnaireLog = QuestionnaireLog::getByQuestionnaireAndUser($questionnaireId, $user); if (!empty($questionnaireLog)) { throw new InvalidParameterException(Yii::t('content', 'user_has_answered_questionnaire')); } } $quertionnaireLog = new QuestionnaireLog(); $quertionnaireLog->questionnaireId = $questionnaireId; $quertionnaireLog->user = $user; $quertionnaireLog->answers = $params['answers']; $quertionnaireLog->accountId = $questionnaire->accountId; if ($quertionnaireLog->save()) { return ['message' => 'OK', 'data' => '']; } else { throw new ServerErrorHttpException(Yii::t('common', 'save_fail')); } }
public function perform() { $args = $this->args; if (empty($args['condition'])) { ResqueUtil::log(['status' => 'fail to send early bird sms', 'message' => 'missing params', 'args' => $args]); LogUtil::error(['message' => 'EarlyBirdSms發送失敗', 'message' => 'missing params in job', 'args' => $args], 'earlybird'); } $condition = unserialize($args['condition']); $smsRecord = new \MongoId($args['smsRecord']); if ($args['smsTag'] == 'sms_four') { EarlybirdSmsUtil::sendSmsByExchangeGoodsScore($condition, $args['smsTag'], $smsRecord); } else { EarlybirdSmsUtil::sendSmsBycondition($condition, $args['smsTag'], $smsRecord); } }
public function actionSendTestSms() { $params = $this->getQuery(); if (empty($params) || empty($params['testSms'])) { throw new BadRequestHttpException('Failed! Mobile number or content is null.'); } $response = MessageUtil::sendMobileMessage($params['testMobile'], $params['testSms'], $this->getAccountId()); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; if ($response) { return ['code' => 200]; } else { LogUtil::error(['message' => 'EarlyBird測試簡訊發送失敗', 'mobile' => $params['testMobile'], 'content' => $params['testSms']], 'earlybird'); return ['code' => 1000]; } }
/** * Send mobile message. * @param string $mobile The phone number * @param string $text, The message content. * @return Array */ public static function sendMobileMessage($mobile, $text) { $url = YUNPIAN_DOMAIN; $params = ['apikey' => YUNPIAN_API_KEY, 'mobile' => $mobile, 'text' => $text]; Yii::$app->curl->setHeaders(['Content-Type: application/x-www-form-urlencoded']); $resultJson = Yii::$app->curl->post($url, http_build_query($params)); LogUtil::info(['url' => $url, 'params' => $params, 'response' => $resultJson], 'mobile-message'); $result = Json::decode($resultJson, true); if ($result && isset($result['code']) && 0 == $result['code'] && isset($result['result']) && isset($result['result']['count']) && $result['result']['count'] > 0) { self::recoreMessageCount('omni_record_message_total'); return true; } else { LogUtil::error(['url' => $url, 'params' => $params, 'response' => $resultJson], 'mobile-message'); return false; } }
public function perform() { $args = $this->job->payload['args']; $args = json_decode($args, true); if (empty($args['qrcodeType']) || empty($args['accountId']) || empty($args['associatedId']) || empty($args['membershipDiscountId'])) { LogUtil::error(['message' => 'Missing params', 'params' => $args], 'upload_resque'); return false; } $qrcode = Yii::$app->qrcode->create(rtrim(DOMAIN, '/'), $args['qrcodeType'], $args['associatedId'], new MongoId($args['accountId'])); //update membership discount qrcode info $qrcodeItem = ['_id' => $qrcode->_id, 'qiniuKey' => $qrcode->qiniuKey]; if (false == MembershipDiscount::updateAll(['$set' => ['qrcode' => $qrcodeItem]], ['_id' => new MongoId($args['membershipDiscountId'])])) { LogUtil::error(['message' => 'Fail to update MembershipDiscount qrcode info', 'qrcodeItem' => var_export($qrcodeItem, true), 'membershipDiscountId' => $args['membershipDiscountId']], 'upload_resque'); } return true; }
/** * Request the service with basic auth * @param string $url requested url * @param string $method requested method * @param string $params requested parameters */ private function _requestService($url, $method, $params = NULL) { //format header and params for post and put if (in_array($method, [self::METHOD_POST, self::METHOD_PUT])) { $method = $method . 'Json'; $params = Json::encode($params); } $resultJson = Yii::$app->curl->{$method}($url, $params); $logUrl = strtoupper($method) . ' ' . $url; $logTarget = 'webhook'; LogUtil::info(['url' => $logUrl, 'response' => $resultJson, 'params' => $params], $logTarget); if (StringUtil::isJson($resultJson)) { return Json::decode($resultJson, true); } else { LogUtil::error(['url' => $logUrl, 'response' => $resultJson, 'params' => $params], $logTarget); } }
/** * Unified Order, the order must contain `orderNumber`, * `shallCount`, `payMode`, `user`, `timeExpire` * @param ObjectId $accountId * @param array $order the detail of trade order. * @return bool */ public function create($order) { $requiredFields = ['userIp', 'subject', 'orderNumber', 'expectedAmount', 'realAmount', 'payMode', 'timeExpire', 'openId', 'user' => ['memberId']]; ValidatorUtil::fieldsRequired($order, $requiredFields); ModelPayment::avoidDuplicate($order['orderNumber']); if (!ModelPayment::isAlreadyPrepay($order['orderNumber'])) { if (!ModelPayment::create($this->accountId, $order)) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } } $totalFee = round(floatval($order['realAmount']) * 100); try { $reponse = Yii::$app->tradeService->unifiedOrder($order['subject'], $order['orderNumber'], $totalFee, MongodbUtil::MongoDate2msTimeStamp($order['timeExpire']), $order['userIp'], $this->accountId, $order['openId']); return $reponse; } catch (yii\base\Exception $e) { LogUtil::error(['message' => 'Create wechat order occurs a error', 'error' => $e->getMessage()], 'trade'); } }
/** * @args {"description": "Direct: Analysis daily promotion code "} */ public function perform() { $yesterday = ModelPromotionCodeAnalysis::getTime(-1); $type = new MongoInt32(ModelPromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL); $where = ['createdAt' => $yesterday, 'type' => $type]; $status = ModelPromotionCodeAnalysis::checkExistData($where); if ($status) { $yesterdayStamp = TimeUtil::today() - 24 * 3600; $yesterday = new MongoDate($yesterdayStamp); //get campaignlogs in yesterday $campaignLogs = ModelPromotionCodeAnalysis::getMemberCampaignLog(); //create datas if (!empty($campaignLogs)) { $campaignData = []; foreach ($campaignLogs as $key => $campaignLog) { //get total the day before yesterday $beforeYesterday = new MongoDate(TimeUtil::today() - 2 * 24 * 3600); $productId = $campaignLog['_id']['productId']; $campaignId = $campaignLog['_id']['campaignId']; $accountId = $campaignLog['_id']['accountId']; $condition = ['productId' => $productId, 'campaignId' => $campaignId, 'accountId' => $accountId, 'createdAt' => $beforeYesterday, 'type' => $type]; $beforeYesterdayData = ModelPromotionCodeAnalysis::findOne($condition); if (empty($beforeYesterdayData)) { $beforeYesterdayData['total'] = 0; } $condition = ['campaignId' => $campaignId, 'accountId' => $accountId, 'productId' => $productId]; $number = ModelPromotionCodeAnalysis::checkMemberUnique($condition, TimeUtil::today()); //subtract the member who is recorded before $total = $beforeYesterdayData['total'] + $number; $campaignLogs[$key]['total'] = $total; } $campaignData = ModelPromotionCodeAnalysis::createAnalysisData($campaignLogs, $type, $yesterday); if (false === ModelPromotionCodeAnalysis::batchInsert($campaignData)) { LogUtil::error(['message' => 'Faild to create daily data', 'date' => date('Y-m-d H:i:s'), 'data' => json_encode($campaignData)], 'resque'); } } //set the default value when the value is not exists $yesterdayStamp -= 3600 * 24; ModelPromotionCodeAnalysis::setDefault($yesterdayStamp, $type); } else { LogUtil::info(['message' => 'Total analysis data is exists', 'date' => date('Y-m-d H:i:s')], 'resque'); } return true; }
public function perform() { $args = $this->args; if (empty($args['condition']) || empty($args['smsName'])) { ResqueUtil::log(['status' => 'fail to send early bird sms', 'message' => 'missing params', 'args' => $args]); LogUtil::error(['message' => 'missing params in job', 'args' => $args], 'bulkSms'); } $condition = unserialize($args['condition']); $smsRecordId = new \MongoId($args['smsRecord']); $smsData = null; switch ($args['smsName']) { case 'cny_winners': $smsData = LuckyDrawWinner::preProcessCnyWinnerSmsData($condition); break; default: break; } BulkSmsUtil::sendSms($smsData, $args['smsName'], $smsRecordId, $condition['accountId']); }
/** * @args {"description": "Delay: Statistics of location info and scores issued by rule every day"} */ public function perform() { $args = $this->args; $accounts = Account::findAll(['enabledMods' => 'member']); foreach ($accounts as $account) { $accountId = $account->_id; //score rule statistics $scoreRules = ScoreRule::getByAccount($accountId); foreach ($scoreRules as $scoreRule) { $this->updateScoreRuleStatistics($scoreRule->name, $accountId); } //location statistics $result = $this->updateLocationStatistics($accountId); if (!$result) { LogUtil::error(['message' => 'statistics location error', 'date' => date('Y-m-d H:i:s'), 'args' => $args], 'resque'); } } return true; }
/** * when crate a staff successful,and send sms fail,we need to delete the staff */ public function actionCreate() { $params = $this->getParams(); if (empty($params['phone']) || empty($params['channel']['channelId']) || empty($params['badge']) || empty($params['storeId'])) { throw new BadRequestHttpException('params missing'); } $accountId = $this->getAccountId(); $params['accountId'] = $accountId; $existsEmpID = Staff::checkUnique($params['badge'], $accountId); if ($existsEmpID) { throw new InvalidParameterException(['badge' => Yii::t("store", "badge_exists")]); } $storeId = $params['storeId']; $params['storeId'] = new \MongoId($storeId); if (false === Staff::checkPhone($params['storeId'], $params['phone'])) { throw new InvalidParameterException(['phone' => Yii::t("store", 'phone_exists')]); } $data = Staff::setQrcodeParam($params['channel']['channelId']); $params = array_merge($params, $data); $params['salt'] = StringUtil::rndString(6, 1); $staff = new Staff(); $staff->load($params, ''); $result = 'success'; if ($staff->save()) { if (!empty($params['useWebhook'])) { $eventData = ['type' => Webhook::EVENT_STAFF_CREATED, 'store_id' => $storeId, 'staff_id' => (string) $staff->_id, 'phone' => $params['phone'], 'badge' => $params['badge'], 'channel' => ['id' => $params['channel']['channelId'], 'name' => $params['channel']['channelName'], 'type' => $params['channel']['channelType']], 'origin' => Member::PORTAL, 'account_id' => (string) $accountId, 'created_at' => MongodbUtil::MongoDate2String($staff->createdAt, \DateTime::ATOM)]; Yii::$app->webhook->triggerEvent($eventData); } else { //send mobile message $template = Staff::getMobileTemplate($accountId); $status = MessageUtil::sendMobileMessage($params['phone'], $template); if (false === $status) { $result = 'fail'; //delete the staff Staff::getCollection()->remove(['_id' => $staff->_id]); LogUtil::error(['message' => 'Faild to send message', 'template' => $template, 'params' => $params], 'staff'); } } } else { throw new ServerErrorHttpException(Yii::t('store', 'fail_to_create')); } return ['result' => $result]; }
/** * @args {"description": "Direct: Analysis participate promotion code "} */ public function perform() { $yesterday = ModelPromotionCodeAnalysis::getTime(-1); $type = new MongoInt32(ModelPromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_PARTICIPATE); $where = ['createdAt' => $yesterday, 'type' => $type]; $status = ModelPromotionCodeAnalysis::checkExistData($where); if ($status) { $yesterdayStamp = TimeUtil::today() - 24 * 3600; $yesterday = new MongoDate($yesterdayStamp); $createWhere = ModelPromotionCodeAnalysis::getCreateTime(); $campaignIds = CampaignLog::distinct('campaignId', $createWhere); $campaignLogs = []; if (!empty($campaignIds)) { $where = array_merge($createWhere, ['campaignId' => ['$in' => $campaignIds]]); $campaignLogs = CampaignLog::getCollection()->aggregate([['$match' => $where], ['$group' => ['_id' => ['campaignId' => '$campaignId', 'memberId' => '$member.id', 'accountId' => '$accountId', 'productId' => '$productId']]]]); } if (!empty($campaignLogs)) { //get total for take part in a campaign $campaignData = []; foreach ($campaignLogs as $data) { $campaignId = $data['_id']['campaignId']; $key = (string) $campaignId . (string) $data['_id']['productId']; if (isset($campaignData[$key])) { //to sum the total in every product in same campaign $campaignData[$key]['total'] += 1; } else { $product = Product::findByPk($data['_id']['productId']); $productName = empty($product['name']) ? '' : $product['name']; $result = ['productId' => $data['_id']['productId'], 'productName' => $productName, 'campaignId' => $campaignId, 'accountId' => $data['_id']['accountId'], 'createdAt' => $yesterday, 'total' => 1, 'type' => $type]; $campaignData[$key] = $result; } } if (false === ModelPromotionCodeAnalysis::batchInsert($campaignData)) { LogUtil::error(['message' => 'Faild to create daily data', 'date' => date('Y-m-d H:i:s'), 'data' => json_encode($campaignData)], 'resque'); } unset($datas, $campaignIds, $campaignData); } } else { LogUtil::info(['message' => 'Participate analysis data is exists', 'date' => date('Y-m-d H:i:s')], 'resque'); } return true; }
public static function updateBar($params) { $params['_id'] = new \MongoId($params['_id']); $bar = ActivityBar::findOne($params['_id']); $params['startDate'] = MongodbUtil::msTimetamp2MongoDate($params['startDate']); $params['endDate'] = MongodbUtil::msTimetamp2MongoDate($params['endDate']); $bar['name'] = $params['name']; $bar['mainImgUrl'] = $params['mainImgUrl']; $bar['probability'] = (int) $params['probability']; $bar['rule'] = $params['rule']; $bar['startDate'] = $params['startDate']; $bar['endDate'] = $params['endDate']; $bar['status'] = $params['status']; $bar['operator'] = $params['operator']; if (!$bar->save()) { LogUtil::error(['message' => 'save activity-bar failed', 'error' => $bar->errors], 'activityBar'); throw new ServerErrorHttpException('save activityBar failed'); } return $bar['_id']; }
public static function createDrawRecord($params) { try { $order = self::getDrawCount() + 1; $record = new EarlyBirdDrawRecord(); $params['activityStartDate'] = MongodbUtil::msTimetamp2MongoDate($params['startDate']); $params['activityEndDate'] = MongodbUtil::msTimetamp2MongoDate($params['endDate']); unset($params['startDate'], $params['endDate']); $record->attributes = $params; $record->order = $order; $record->accountId = Token::getAccountId(); if (!$record->save()) { throw new ServerErrorHttpException('save lucky draw record failed'); } return $record->_id; } catch (\Exception $ex) { LogUtil::error(['message' => 'save lucky draw record failed', 'error' => $ex->getMessage()], 'earlybird'); throw new ServerErrorHttpException('save lucky draw record failed'); } }
/** * @args {"description": "Direct: Analysis total participate"} */ public function perform() { $yesterday = ModelPromotionCodeAnalysis::getTime(-1); $type = new MongoInt32(ModelPromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL_PARTICIPATE); $where = ['createdAt' => $yesterday, 'type' => $type]; $status = ModelPromotionCodeAnalysis::checkExistData($where); if ($status) { $yesterdayStamp = TimeUtil::today() - 24 * 3600; $yesterday = new MongoDate($yesterdayStamp); $where = ModelPromotionCodeAnalysis::getCreateTime(); $campaignData = ModelPromotionCodeAnalysis::getMemberAllTimes($where); $campaignData = ModelPromotionCodeAnalysis::createAnalysisData($campaignData, $type, $yesterday); if (false === ModelPromotionCodeAnalysis::batchInsert($campaignData)) { LogUtil::error(['message' => 'Faild to create daily data', 'date' => date('Y-m-d H:i:s'), 'data' => json_encode($campaignData)], 'resque'); } } else { LogUtil::info(['message' => 'Total participate analysis data is exists', 'date' => date('Y-m-d H:i:s')], 'resque'); } return true; }
public function operationCoupon($membershipDiscount) { //record log when get coupon $memberItem = Member::getMemberInfo($membershipDiscount->member['id'], ['tel']); $memberInfo = ['id' => $membershipDiscount->member['id'], 'name' => $membershipDiscount->member['name'], 'phone' => empty($memberItem['tel']) ? '' : $memberItem['tel'], 'receiveType' => $membershipDiscount->coupon['receiveType']]; $couponLog = new CouponLog(); $couponLog->couponId = $membershipDiscount->coupon['id']; $couponLog->membershipDiscountId = $membershipDiscount->_id; $couponLog->type = $membershipDiscount->coupon['type']; $couponLog->title = $membershipDiscount->coupon['title']; $couponLog->status = CouponLog::RECIEVED; $couponLog->member = $memberInfo; $couponLog->total = 1; $couponLog->operationTime = $couponLog->createdAt = new MongoDate(); $couponLog->accountId = $membershipDiscount->accountId; if (false === $couponLog->save()) { //to avoid the error show to user LogUtil::error(['message' => 'Failed to save couponLog error:' . $couponLog->getErrors()], 'product'); } }
public static function createUser($params) { try { $result = true; $accountId = Token::getAccountId(); if (empty($accountId)) { throw new ServerErrorHttpException("Fail to get account's id"); } $params['accountId'] = $accountId; $user = new ActivityUser(); $user->attributes = $params; if (!$user->save()) { LogUtil::error(['message' => 'save activity-user failed', 'error' => $user->errors], 'activityUser'); $result = false; } return $result; } catch (\Exception $ex) { LogUtil::error(['message' => 'save activity-user failed', 'error' => $ex->getMessage()], 'activityUser'); return false; } }
/** * Give points to member * * <b>Request Type: </b>POST<br/> * <b>Request Endpoint: </b>http://{server-domain}/api/member/score/give<br/> * <b>Content-type: </b>application/json<br/> * <b>Summary: </b>This api is for give scores to specific members or conditions to filter member.<br/> * * <b>Request Parameters: </b> * scores: int, the value of the scores to give, required<br/> * filterType: string, the type of the filter, "name" or "number" or "tag", required<br/> * names: array<string>, the array of the names for filter, required only if the filterType is "name"<br/> * numbers: array<string>, the array of the numbers to filter members, required only if the filterType is "number"<br/> * tags: array<string>, the array of the tags fo filter members, required only if the filterType is "tag"<br/> * description: string, the description. optional. <br/> * * <b>Request Example</b><br/> * <pre> * {"score":100, "filterType":"name", "names":["Zhang San", "Li Si"]} * </pre> * */ public function actionGive() { $filterType = $this->getParams('filterType'); $score = $this->getParams('score'); $description = $this->getParams('description'); if (empty($filterType) || empty($score)) { throw new BadRequestHttpException('Missing required parameters'); } $userId = $this->getUserId(); $user = User::findByPk($userId); $user = ['id' => $userId, 'name' => $user->name]; $filterKey = $filterType . 's'; $filterValue = $this->getParams($filterKey); if (empty($filterValue)) { throw new BadRequestHttpException("Missing required parameters"); } $function = "giveScoreBy" . $filterKey; $memberList = Member::$function($score, $filterValue); if (empty($memberList)) { throw new InvalidParameterException(['member-' . $filterType => \Yii::t('member', 'no_member_find')]); } if ($memberList) { foreach ($memberList as $member) { $scoreHistory = new ScoreHistory(); $scoreHistory->assigner = ScoreHistory::ASSIGNER_ADMIN; $scoreHistory->increment = $score; $scoreHistory->memberId = $member; $scoreHistory->brief = $score >= 0 ? ScoreHistory::ASSIGNER_ADMIN_ISSUE_SCORE : ScoreHistory::ASSIGNER_ADMIN_DEDUCT_SCORE; $scoreHistory->description = $description; $scoreHistory->channel = ['origin' => ScoreHistory::PORTAL]; $scoreHistory->user = $user; $scoreHistory->accountId = $this->getAccountId(); if (!$scoreHistory->save()) { LogUtil::error(['message' => 'save scoreHistory failed', 'data' => $scoreHistory->toArray()], 'member'); } } return ['status' => 'ok']; } }