public function actionIndex($accountId) { if (empty($accountId)) { echo 'accountId is invaild' . PHP_EOL; exit; } $where['accountId'] = new \MongoId($accountId); // delete member info Member::getCollection()->remove($where); //delete MemberLogs MemberLogs::getCollection()->remove($where); //delete scoreHistory ScoreHistory::getCollection()->remove($where); //delete CampaignLog CampaignLog::getCollection()->remove($where); //delete GoodsExchangeLog GoodsExchangeLog::getCollection()->remove($where); //delete MemberStatistics MemberStatistics::getCollection()->remove($where); //delete ReMemberCampaign ReMemberCampaign::getCollection()->remove($where); //delete StatsCampaignProductCodeQuarterly StatsCampaignProductCodeQuarterly::getCollection()->remove($where); //delete StatsMemberCampaignLogDaily StatsMemberCampaignLogDaily::getCollection()->remove($where); //delete StatsMemberDaily StatsMemberDaily::getCollection()->remove($where); //delete StatsMemberGrowthMonthly StatsMemberGrowthMonthly::getCollection()->remove($where); //delete StatsMemberGrowthQuarterly StatsMemberGrowthQuarterly::getCollection()->remove($where); //delete StatsMemberMonthly StatsMemberMonthly::getCollection()->remove($where); //delete StatsMemberPropAvgTradeQuarterly StatsMemberPropAvgTradeQuarterly::getCollection()->remove($where); //delete StatsMemberPropMonthly StatsMemberPropMonthly::getCollection()->remove($where); //delete StatsMemberPropQuaterly StatsMemberPropQuaterly::getCollection()->remove($where); //delete StatsMemberPropTradeCodeAvgQuarterly StatsMemberPropTradeCodeAvgQuarterly::getCollection()->remove($where); //delete StatsMemberPropTradeCodeQuarterly StatsMemberPropTradeCodeQuarterly::getCollection()->remove($where); //delete StatsMemberPropTradeQuarterly StatsMemberPropTradeQuarterly::getCollection()->remove($where); //delete PromotionCodeAnalysis PromotionCodeAnalysis::getCollection()->remove($where); //delete order Order::getCollection()->remove($where); //delete stats member order StatsMemberOrder::getCollection()->remove($where); //delete stats order StatsOrder::getCollection()->remove($where); //delete MembershipDiscount MembershipDiscount::getCollection()->remove($where); //delete couponLog CouponLog::getCollection()->remove($where); echo 'delete data successful.' . PHP_EOL; }
public function actionFixData($startData, $endData) { $accounts = Account::findAll(['enabledMods' => 'product']); foreach ($accounts as $account) { $accountId = $account->_id; $condition = ['accountId' => $accountId, 'createdAt' => ['$gte' => new MongoDate(strtotime($startData)), '$lt' => new Mongodate(strtotime($endData))]]; $pipeline = [['$match' => $condition], ['$group' => ['_id' => ['campaignId' => '$campaignId', 'code' => '$code'], 'count' => ['$sum' => 1]]], ['$match' => ['count' => ['$gt' => 1]]]]; $stats = CampaignLog::getCollection()->aggregate($pipeline); if (!empty($stats)) { foreach ($stats as $stat) { $code = $stat['_id']['code']; $logCondition = array_merge($condition, $stat['_id']); $logs = CampaignLog::find()->where($logCondition)->orderBy(['createdAt' => 1])->all(); $memberId = $logs[0]['member']['id']; $productName = $logs[0]['productName']; $description = $productName . ' ' . $code; $scoreHistoryCondition = ['memberId' => $memberId, 'brief' => ScoreHistory::ASSIGNER_EXCHANGE_PROMOTION_CODE, 'description' => $description]; $scoreHistorys = ScoreHistory::find()->where($scoreHistoryCondition)->orderBy(['createdAt' => 1])->all(); $keepScoreHistory = $scoreHistorys[0]; unset($scoreHistorys[0]); $removeScoreHistoryIds = []; $deduct = 0; foreach ($scoreHistorys as $scoreHistory) { $removeScoreHistoryIds[] = $scoreHistory->_id; $deduct += $scoreHistory->increment; } $member = Member::findByPk($memberId); if ($member->score <= $deduct || $member->totalScore <= $deduct || $member->totalScoreAfterZeroed <= $deduct) { echo 'Failed : Member' . $memberId . ' score not enough ' . 'score: ' . $member->score; echo ' totalScore: ' . $member->totalScore; echo ' totalScoreAfterZeroed: ' . $member->totalScoreAfterZeroed . PHP_EOL; continue; } $deductScore = 0 - $deduct; Member::updateAll(['$inc' => ['score' => $deductScore, 'totalScore' => $deductScore, 'totalScoreAfterZeroed' => $deductScore]], ['_id' => $memberId]); ScoreHistory::deleteAll(['_id' => ['$in' => $removeScoreHistoryIds]]); $logIds = ArrayHelper::getColumn($logs, '_id'); $keepLogId = $logIds[0]; unset($logIds[0]); CampaignLog::deleteAll(['_id' => ['$in' => array_values($logIds)]]); echo 'Success: ' . $productName . ' ' . $code . ' ' . $stat['count']; echo ' Deduct member ' . $memberId . ' score ' . $deduct . PHP_EOL; } } } echo 'Success' . PHP_EOL; }
/** * @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; }
/** * export the promotioncode has been redeemed */ public function actionExport() { $accountId = $this->getAccountId(); $params = $this->getQuery(); $where = CampaignLog::createCondition($params, $accountId); $data = CampaignLog::find()->where($where)->one(); if ($data) { //redis hash key and set a default value $key = Yii::t('product', 'file_name') . '_' . date('YmdHis'); // get the header for the excel $headerValues = explode(",", Yii::t('product', 'promotion_redeemed_export')); $headerKeys = ['id', 'cardNumber', 'memberName', 'tel', 'sku', 'productName', 'code', 'prize', 'redeemTime', 'createdAt', 'redeemptionChannelName', 'campaignName', 'backendUser']; $header = array_combine($headerKeys, $headerValues); $exportArgs = ['collection' => 'campaignLog', 'classFunction' => '\\backend\\modules\\product\\models\\CampaignLog::preProcessRedeemedCodeData', 'sort' => ['createdAt' => -1], 'language' => Yii::$app->language, 'header' => $header, 'key' => $key, 'params' => [], 'fields' => '_id,code,productId,productName,campaignName,sku,operaterEmail,member,redeemTime,usedFrom,createdAt', 'accountId' => (string) $accountId, 'condition' => serialize(CampaignLog::getCollection()->buildCondition($where)), 'description' => 'Direct: export promotionCodes that is been redeemed']; $jobId = Yii::$app->job->create('backend\\modules\\common\\job\\MongoExportFile', $exportArgs); $result = ['result' => 'success', 'message' => 'exporting redeemed code', 'data' => ['jobId' => $jobId, 'key' => $key]]; } else { $result = ['result' => 'error', 'message' => 'no datas', 'data' => []]; } return $result; }
/** * This function is just for fix error promotionCode redeem data * @param MongoId $accountId * @param MongoId $memberId * @param Array $codes * @return boolean, true, if there is no error data */ private function fixData($accountId, $memberId, $codes) { $condition = ['accountId' => $accountId, 'member.id' => $memberId, 'code' => ['$in' => $codes]]; $pipeline = [['$match' => $condition], ['$group' => ['_id' => ['campaignId' => '$campaignId', 'code' => '$code'], 'count' => ['$sum' => 1]]], ['$match' => ['count' => ['$gt' => 1]]]]; $stats = CampaignLog::getCollection()->aggregate($pipeline); if (empty($stats)) { return true; } $logCondition = ['accountId' => $accountId, 'member.id' => $memberId]; $failedMessages = []; $successMessages = []; foreach ($stats as $stat) { $code = $stat['_id']['code']; //get campaign log $logCondition = array_merge($logCondition, $stat['_id']); $logs = CampaignLog::find()->where($logCondition)->orderBy(['createdAt' => SORT_ASC])->all(); $memberId = $logs[0]['member']['id']; $productName = $logs[0]['productName']; //get score history $description = $productName . ' ' . $code; $scoreHistoryCondition = ['memberId' => $memberId, 'brief' => ScoreHistory::ASSIGNER_EXCHANGE_PROMOTION_CODE, 'description' => $description]; $scoreHistorys = ScoreHistory::find()->where($scoreHistoryCondition)->orderBy(['createdAt' => SORT_ASC])->all(); $keepScoreHistory = $scoreHistorys[0]; unset($scoreHistorys[0]); $removeScoreHistoryIds = []; $deduct = 0; foreach ($scoreHistorys as $scoreHistory) { $removeScoreHistoryIds[] = $scoreHistory->_id; $deduct += $scoreHistory->increment; } $member = Member::findByPk($memberId); //if member score not enough, log continue if ($member->score <= $deduct || $member->totalScore <= $deduct || $member->totalScoreAfterZeroed <= $deduct) { $failedMessages[] = ['Failed' => 'Member score not enough', 'member' => $member->toArray(), 'deduct' => $deduct]; continue; } //fix member score $deductScore = 0 - $deduct; Member::updateAll(['$inc' => ['score' => $deductScore, 'totalScore' => $deductScore, 'totalScoreAfterZeroed' => $deductScore]], ['_id' => $memberId]); //remove scorehistory ScoreHistory::deleteAll(['_id' => ['$in' => $removeScoreHistoryIds]]); //remove campaignlog $logIds = ArrayHelper::getColumn($logs, '_id'); $keepLogId = $logIds[0]; unset($logIds[0]); CampaignLog::deleteAll(['_id' => ['$in' => array_values($logIds)]]); $successMessages[] = ['Success' => $productName . ' ' . $code . ' ' . $stat['count'], 'memberId' => $memberId, 'deduct' => $deduct]; } LogUtil::error(['Failed' => $failedMessages, 'Success' => $successMessages], 'fix-campaign-data'); }
private static function _getCampaignLogs($productIds, $createWhere) { $campaignLogs = []; if (!empty($productIds)) { $where = array_merge($createWhere, ['productId' => ['$in' => $productIds]]); $campaignLogs = CampaignLog::getCollection()->aggregate([['$match' => $where], ['$group' => ['_id' => ['productId' => '$productId', 'productName' => '$productName', 'memberId' => '$member.id', 'accountId' => '$accountId']]]]); } return $campaignLogs; }
/** * get the campaign log * @param $total,boolean,true means to get the all campaign logs,false means to get a part of logs * @param $today,timestamp,get log at what time */ public static function getMemberCampaignLog($total = false, $today = '', $group = [], $secondGroup = []) { $createWhere = self::_getCreateTime($total, $today); if (empty($group)) { $group = ['_id' => ['campaignId' => '$campaignId', 'accountId' => '$accountId', 'productId' => '$productId', 'memberId' => '$member.id']]; $secondGroup = ['_id' => ['campaignId' => '$_id.campaignId', 'accountId' => '$_id.accountId', 'productId' => '$_id.productId'], 'total' => ['$sum' => 1]]; } $campaignLogs = CampaignLog::getCollection()->aggregate([['$match' => $createWhere], ['$group' => $group], ['$group' => $secondGroup]]); return $campaignLogs; }
public function perform() { $args = $this->args; if (empty($args['beginTime']) || empty($args['endTime']) || empty($args['type'])) { ResqueUtil::log(['error' => 'missing params', 'args' => $args]); return false; } $beginTime = strtotime($args['beginTime']) + 3600 * 24; $endTime = strtotime($args['endTime']); if ($endTime > time()) { $endTime = strtotime(date('Y-m-d', time())); } $endTime += 3600 * 24; $type = new \MongoInt32($args['type']); switch ($args['type']) { case PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_PARTICIPATE: //delete data and create data for ($t = $beginTime; $t <= $endTime; $t += 3600 * 24) { $where = ['createdAt' => new \MongoDate($t - 3600 * 24), 'type' => $type]; PromotionCodeAnalysis::deleteAll($where); //create data begin $createWhere = PromotionCodeAnalysis::getCreateTime($t); $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', 'accountId' => '$accountId', 'productId' => '$productId', 'memberId' => '$member.id']]]]); } 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' => new \MongoDate($t - 3600 * 24), 'total' => 1, 'type' => $type]; $campaignData[$key] = $result; } } PromotionCodeAnalysis::batchInsert($campaignData); unset($datas, $campaignIds, $campaignData); } } break; case PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL: //delete data and create data for ($t = $beginTime; $t <= $endTime; $t += 3600 * 24) { $where = ['createdAt' => new \MongoDate($t - 3600 * 24), 'type' => $type]; PromotionCodeAnalysis::deleteAll($where); //get campaignlogs in yesterday $campaignLogs = PromotionCodeAnalysis::getMemberCampaignLog(false, $t); //create datas $yesterday = new \MongoDate($t - 2 * 24 * 3600); if (!empty($campaignLogs)) { $campaignData = []; foreach ($campaignLogs as $key => $campaignLog) { //get total the day yesterday $productId = $campaignLog['_id']['productId']; $campaignId = $campaignLog['_id']['campaignId']; $accountId = $campaignLog['_id']['accountId']; $condition = ['productId' => $productId, 'campaignId' => $campaignId, 'accountId' => $accountId, 'createdAt' => $yesterday, 'type' => $type]; $yesterdayData = PromotionCodeAnalysis::findOne($condition); if (empty($yesterdayData)) { $yesterdayData['total'] = 0; } $condition = ['campaignId' => $campaignId, 'accountId' => $accountId, 'productId' => $productId]; $number = PromotionCodeAnalysis::checkMemberUnique($condition, $t); //subtract the member who is recorded before $total = $yesterdayData['total'] + $number; $campaignLogs[$key]['total'] = $total; } $campaignData = PromotionCodeAnalysis::createAnalysisData($campaignLogs, $type, new \MongoDate($t - 24 * 3600)); PromotionCodeAnalysis::batchInsert($campaignData); } //set the default value when the value is not exists PromotionCodeAnalysis::setDefault($t - 2 * 24 * 3600, $type); } break; case PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_EVERYDAY_PRIZE: for ($t = $beginTime; $t <= $endTime; $t += 3600 * 24) { //delete data $where = ['createdAt' => new \MongoDate($t - 3600 * 24), 'type' => $type]; PromotionCodeAnalysis::deleteAll($where); $campaignLogs = PromotionCodeAnalysis::getCampaignLog(false, $t); if (!empty($campaignLogs)) { $campaignData = PromotionCodeAnalysis::createAnalysisData($campaignLogs, $type, new \MongoDate($t - 3600 * 24)); PromotionCodeAnalysis::batchInsert($campaignData); } } break; case PromotionCodeAnalysis::PROMOTION_CODE_ANALYSIS_TOTAL_PARTICIPATE: for ($t = $beginTime; $t <= $endTime; $t += 3600 * 24) { //delete data $where = ['createdAt' => new \MongoDate($t - 3600 * 24), 'type' => $type]; PromotionCodeAnalysis::deleteAll($where); unset($where); $where = PromotionCodeAnalysis::getCreateTime($t); $campaignLogs = PromotionCodeAnalysis::getMemberAllTimes($where); if (!empty($campaignLogs)) { $campaignData = PromotionCodeAnalysis::createAnalysisData($campaignLogs, $type, new \MongoDate($t - 3600 * 24)); PromotionCodeAnalysis::batchInsert($campaignData); } } break; } return true; }
private static function _getCampaignLog($condition) { $campaignLogs = CampaignLog::getCollection()->aggregate(['$match' => $condition], ['$group' => ['_id' => ['productId' => '$productId', 'createdAt' => '$createdAt', 'member' => '$member', 'code' => '$code', 'redeemTime' => '$redeemTime']]]); return $campaignLogs; }
/** * get how many code to exchange and how many scords to redeem * @param $codes */ public static function getCodeRecord($codes) { if (!is_array($codes)) { $codes = explode(',', $codes); } $where = ['code' => ['$in' => $codes], 'member.type' => self::CAMPAIGN_SCORE]; LogUtil::info(['msg' => 'get code and score', 'where' => $where], 'campaignLog'); $results = CampaignLog::getCollection()->aggregate([['$match' => $where], ['$group' => ['_id' => '$code', 'score' => ['$sum' => '$member.scoreAdded']]]]); LogUtil::info(['msg' => 'get struct', 'results' => $results], 'campaignLog'); $codeCount = $scoreCount = 0; if (!empty($results)) { $codeCount = count($results); foreach ($results as $result) { $scoreCount += $result['score']; } } return [$codeCount, $scoreCount]; }
/** * check member whether to fit with the condition of campaign, * if the member fit with the condition,then this function will return the campaign * otherwise it will return a empty array * @param $campaign, array, campaign info * @param $member , array, member info * @param $createReMemberCampaign, boolean, if the value is true, this function will create a record * in the table called ReMemberCampaign.when you check the condition for the campaign and you do not want to * exchange code,this value you can pass false */ public static function selectCampaign($campaign, $member, $params, $createReMemberCampaign = true) { //record fail message $msg = ''; $accountId = $member->accountId; //check the total member to take part in campaign $memberIds = CampaignLog::getCollection()->distinct("member.id", ['campaignId' => $campaign->_id]); if ($createReMemberCampaign) { self::createReMemberCampaign($campaign, $member, $accountId); } else { //check the limiter and participantCount $num = CampaignLog::count(['campaignId' => $campaign->_id, 'member.id' => $member->_id]); //check campaign limit times $result = self::checkCampaignLimitTimes($campaign, $member, $num); if (empty($result['campaign'])) { return $result; } //check the limit time in advance whnen check the limit in offline $result = self::preCheckCampaignLimitTimes($campaign, $member, $num); if (empty($result['campaign'])) { return $result; } //check the campaign participant count $result = self::checkCampaignParticipantCount($campaign, $member, $memberIds); if (empty($result['campaign'])) { return $result; } } // check the tags of member $result = self::checkCampaignMemberTag($campaign, $member); if (empty($result['campaign'])) { return $result; } // check the channels of member $result = self::checkCampaignChannel($campaign, $member, $params); if (empty($result['campaign'])) { return $result; } // check the experice $result = self::checkMemberExperice2Campaign($campaign, $member); if (empty($result['campaign'])) { return $result; } //when user redeem the code.we need operate the participate and limit for per-person if ($createReMemberCampaign) { $result = self::recordCampaignLimit($campaign, $member, $accountId, $memberIds); if (!empty($result['campaign'])) { return $result; } } return ['campaign' => $campaign, 'status' => self::CODE_STATUS_VALID, 'message' => 'code is vaild']; }