public function handle($data) { parent::handle($data); # handle the wechat message LogUtil::info(['channel weconnect event' => $data], 'channel-webhook'); if (empty($data)) { throw new BadRequestHttpException(Yii::t('channel', 'parameter_format_error')); } $data = $data['data']; $requiredParameters = ['outTradeNo', 'tradeNo', 'tradeStatus']; ValidatorUtil::fieldsRequired($data, $requiredParameters); $tradePayment = TradePayment::findOne(['orderNumber' => $data['outTradeNo']]); LogUtil::info(['tradePayment' => $tradePayment->toArray()], 'channel-webhook'); if (empty($tradePayment)) { throw new InvalidParameterException(Yii::t('common', 'data_error')); } $memberId = $tradePayment['user']['memberId']; $couponId = $tradePayment['couponId']; LogUtil::info(['memberId' => $memberId, 'couponId' => $couponId], 'channel-webhook'); if ($data['tradeStatus'] == 'PAY_SUCCESS') { $tradePayment->status = TradePayment::STATUS_PAID; $tradePayment->realAmount = intval($data['totalFee']) / 100; // Make coupon used if (!empty($couponId)) { Yii::$app->service->coupon->makeUsed($memberId, $couponId); } } else { if ($data['tradeStatus'] == 'PAY_ERROR') { $tradePayment->status = TradePayment::STATUS_FAILED; } } $tradePayment->paymentTime = MongodbUtil::msTimetamp2MongoDate($data['paymentTime']); $tradePayment->transactionId = $data['tradeNo']; return $tradePayment->save(true, ['paymentTime', 'status', 'transactionId', 'realAmount']); }
/** * 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'); } }
private function processProductInfoData($header, $filePath, $classFunction, $params = []) { LogUtil::info(['message' => 'Begin to read csv file', 'fileName' => $filePath], 'resque'); $fileInfos = fopen($filePath, "r"); $newFilePath = ExcelUtil::getDownloadFile($filePath); $productNames = $infos = []; while (!feof($fileInfos)) { $fileInfo = Json::decode(fgets($fileInfos), true); if (!empty($fileInfo)) { if (in_array($fileInfo['productName'], $productNames) || empty($productNames)) { $infos[] = $fileInfo; $productNames[] = $fileInfo['productName']; } else { $args = [$infos, $params]; self::writeCsv($classFunction, $args, $header, $newFilePath); unset($infos, $productNames); $productNames[] = $fileInfo['productName']; $infos[] = $fileInfo; } } } if (!empty($infos)) { $args = [$infos, $params]; self::writeCsv($classFunction, $args, $header, $newFilePath); unset($productNames, $infos); } fclose($fileInfos); LogUtil::info(['message' => 'End to read csv file and end to write file', 'fileName' => $filePath], 'resque'); }
/** * @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; } }
/** * @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; }
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; } }
/** * @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'); } }
/** * 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; }
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 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'); } }
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; } }
/** * validate go api signature * @return boolean */ private function validateSignature() { $request = Yii::$app->request; $bodyStr = $request->getRawBody(); $headers = $request->getHeaders(); //for golang $signature = hash_hmac('sha256', $bodyStr, 'Zc6smtltqrAToO44awoutxdS7LNsA81k'); LogUtil::info(['signature' => $signature, 'header' => $headers['X-Event-Signature'], 'body' => $bodyStr], 'event'); if (!empty($headers['X-Event-Signature']) && $signature === $headers['X-Event-Signature']) { return true; } else { return false; } }
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]; } }
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; }
/** * 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; } }
/** * 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); } }
public function perform() { $args = $this->args; if (empty($args['type'])) { $types = [PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_PARTICIPATE, PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL, PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_EVERYDAY_PRIZE, PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL_PARTICIPATE]; foreach ($types as $type) { $yesterdayStamp = TimeUtil::today() - 24 * 3600; self::setData($type, $yesterdayStamp); LogUtil::info(['message' => 'run stats PromotionCodeAnalysis, type :' . $type], 'resque'); } } else { $type = intval($args['type']); $yesterdayStamp = TimeUtil::today() - 24 * 3600; self::setData($type, $yesterdayStamp); } return true; }
/** * 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'); } }
public function actionAuth() { $secret = TUISONGBAO_SECRET; $socketId = $this->getParams('socketId'); $channelName = $this->getParams('channelName'); $authData = $this->getParams('authData'); $parts = explode(':', $authData); $clientId = $parts[1]; $userData = ['userId' => $clientId, 'userInfo' => []]; $userDataJsonStr = json_encode($userData); $strToSign = $socketId . ':' . $channelName . ':' . $userDataJsonStr; LogUtil::info(['strToSign' => $strToSign, 'secret' => $secret], 'signature'); $signature = hash_hmac('sha256', $strToSign, $secret); LogUtil::info(['signature' => $signature, 'channelData' => $userDataJsonStr], 'signature'); $result = ['signature' => $signature, 'channelData' => $userDataJsonStr]; header("Content-Type:application/json"); echo json_encode($result); }
/** * Create a job and put it in global queue * @param string $className * @param array $args * @param timestamp $executeTime UNIX timestamp when job should be executed, default is now * @param int $span seconds * @return string|null job token or empty */ public function create($className, $args = [], $executeTime = null, $interval = null, $isGlobal = true) { LogUtil::info(['message' => 'Begin a job', 'args' => $args], 'resque'); $queue = $isGlobal ? self::GLOBAL_QUEUE : self::BACKEND_QUEUE; $args['language'] = Yii::$app->language; if (!empty($executeTime)) { if (!empty($interval)) { $args['cron_job_time_interval'] = '+ ' . $interval . ' seconds'; while ($executeTime < time()) { $executeTime = strtotime($args['cron_job_time_interval'], $executeTime); } $args['cron_job_execute_time'] = $executeTime; } return Yii::$app->resque->enqueueJobAt($executeTime, $queue, $className, $args); } else { return Yii::$app->resque->createJob($queue, $className, $args); } }
/** * @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]; }
public function perform() { //accountId, properties are required fileds $args = $this->args; if (empty($args['accountId']) || empty($args['properties'])) { ResqueUtil::log('Missing required arguments accountId or properties!'); return false; } $date = empty($args['date']) ? '' : $args['date']; $datetime = TimeUtil::getDatetime($date); $dateStr = date('Y-m-d', $datetime); $start = new MongoDate($datetime); $end = new MongoDate(strtotime('+1 day', $datetime)); $accountId = new MongoId($args['accountId']); $condition = ['accountId' => $accountId, 'createdAt' => ['$gte' => $start, '$lt' => $end]]; $campaignLogs = self::getCampaignLog($condition); if (empty($campaignLogs)) { LogUtil::info(['date' => date('Y-m-d H:i:s'), 'message' => $dateStr . ': campaignLogs is empty,no need to store data'], 'resque'); return true; } //get all member info $memberInfos = self::getMemberInfo($condition); //Get all the property mongo id for comparison $condition = ['propertyId' => ['$in' => $args['properties']], 'accountId' => $accountId]; $propertyIdStrs = self::getPropertyIds($condition); //Generate the meta data for inserting $statsRows = []; foreach ($campaignLogs as $campaignLog) { $campaignLog = $campaignLog['_id']; $redeemTime = self::getRedeemTime($campaignLog); //check the redeem time whether exists $condition = ['code' => $campaignLog['code'], 'productId' => $campaignLog['productId'], 'month' => date('Y-m', $redeemTime)]; $memberCampaignLogDaily = ModelStatsMemberCampaignLogDaily::findOne($condition); if (empty($memberCampaignLogDaily)) { $memProperty = self::getProperty((string) $campaignLog['member']['id'], $memberInfos, $propertyIdStrs); $statsRows[] = ['memberId' => $campaignLog['member']['id'], 'memProperty' => $memProperty, 'productId' => $campaignLog['productId'], 'code' => $campaignLog['code'], 'year' => date('Y', $redeemTime), 'month' => date('Y-m', $redeemTime), 'quarter' => TimeUtil::getQuarter($redeemTime), 'accountId' => $accountId, 'createdAt' => new MongoDate(strtotime('+1 day', $datetime) - 1)]; } } ModelStatsMemberCampaignLogDaily::batchInsert($statsRows); unset($statsRows, $memberCampaignLogDaily, $condition, $memProperty, $memberInfos); return true; }
/** * @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; }