/** * Finds the Product model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Product the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Product::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Product::find(); $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'product_img', $this->product_img])->andFilterWhere(['like', 'product_type', $this->product_type])->andFilterWhere(['like', 'product_name', $this->product_name])->andFilterWhere(['like', 'product_summary', $this->product_summary])->andFilterWhere(['like', 'product_description', $this->product_description])->andFilterWhere(['like', 'meta_title', $this->meta_title])->andFilterWhere(['like', 'meta_description', $this->meta_description])->andFilterWhere(['like', 'alias', $this->alias]); return $dataProvider; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Product::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'manufacture_id' => $this->manufacture_id, 'state' => $this->state, 'created_at' => $this->created_at, 'created_by' => $this->created_by, 'updated_at' => $this->updated_at, 'updated_by' => $this->updated_by]); $query->andFilterWhere(['like', 'guid', $this->guid])->andFilterWhere(['like', 'title', $this->title])->andFilterWhere(['like', 'slug', $this->slug])->andFilterWhere(['like', 'short_description', $this->short_description])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'extension', $this->extension]); return $dataProvider; }
public static function generateData($memberProperty, $property, $year, $quarter, $accountId) { $propertyKey = 'memProperty.' . $memberProperty->_id; $keys = ['productId' => true, $propertyKey => true]; $condition = ['year' => $year, 'quarter' => $quarter, 'accountId' => $accountId]; $initial = ['avg' => 0, 'codes' => ['count' => 0], 'members' => ['count' => 0]]; $reduce = 'function(doc, prev) { if (!prev.members[doc.memberId]) { prev.members[doc.memberId] = true; prev.members["count"]++; } if (!prev.codes[doc.code]) { prev.codes[doc.code] = true; prev.codes["count"]++; } }'; $finalize = 'function(prev) { prev.avg = prev.codes["count"] / prev.members["count"]; delete prev.codes; delete prev.members; }'; $statsItems = ModelStatsMemberCampaignLogDaily::getCollection()->group($keys, $initial, $reduce, ['condition' => $condition, 'finalize' => $finalize]); foreach ($statsItems as $statsItem) { $condition['propId'] = $property; $condition['propValue'] = $statsItem[$propertyKey]; $productId = $statsItem['productId']; $condition['productId'] = $productId; $stats = ModelStatsMemberPropTradeCodeAvgQuarterly::findOne($condition); if (empty($stats)) { $stats = new ModelStatsMemberPropTradeCodeAvgQuarterly(); $product = Product::findByPk($productId); $productName = ''; if (!empty($product)) { $productName = $product->name; } $stats->propId = $property; $stats->propValue = $statsItem[$propertyKey]; $stats->productId = $productId; $stats->productName = $productName; $stats->year = $year; $stats->quarter = $quarter; $stats->accountId = $accountId; } $stats->avg = $statsItem['avg']; $stats->save(); } }
/** * @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 function actionCreate() { $goods = $this->getParams('goods'); $storeId = $this->getParams('storeId'); $accountId = $this->getAccountId(); if (empty($goods) || empty($storeId)) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $storeId = new \MongoId($storeId); $store = Store::findByPk($storeId); if (empty($store)) { throw new InvalidParameterException(Yii::t('common', 'data_error')); } $productIds = []; foreach ($goods as $item) { if (!StoreGoods::validatePrice($item['price'])) { throw new InvalidParameterException(Yii::t('store', 'price_error')); } $productIds[] = new \MongoId($item['productId']); } $storeGoodsCount = StoreGoods::countByProductId($productIds, $storeId); if ($storeGoodsCount > 0) { throw new InvalidParameterException(Yii::t('store', 'goods_exists')); } $storeGoods = []; foreach ($goods as $item) { $product = Product::findByPk($item['productId']); if (empty($product)) { throw new InvalidParameterException(Yii::t('common', 'data_error')); } $category = $product->category; $pictures = ArrayHelper::getColumn($product->pictures, 'url', false); $pictures = array_slice($pictures, 0, 5); $storeGoods[] = ['storeId' => $storeId, 'categoryId' => $category['id'], 'productName' => $product->name, 'sku' => $product->sku, 'productId' => $product->_id, 'pictures' => $pictures, 'status' => StoreGoods::STATUS_OFF, 'offShelfTime' => new \Mongodate(), 'price' => !empty($item['price']) ? floatval($item['price']) : 0.0, 'accountId' => $accountId]; } if (StoreGoods::batchInsert($storeGoods)) { return ['message' => 'OK', 'data' => null]; } else { throw new ServerErrorHttpException(Yii::t('common', 'save_fail')); } }
public function actionUpdate($id) { $params = $this->getParams(); $accountId = $this->getAccountId(); if (empty($params['name'])) { throw new BadRequestHttpException("category required"); } $productCategoryInfo = ProductCategory::findByPk($id); if (ProductCategory::RESERVATION_CATEGORY_NAME == $productCategoryInfo->name) { throw new InvalidParameterException(Yii::t('product', 'can_not_update')); } if (ProductCategory::RESERVATION_CATEGORY_NAME == $params['name']) { throw new InvalidParameterException(Yii::t('product', 'categoryName_isUsed')); } $result = CategoryProperty::checkUniqueName('category', $params['name'], $id, $accountId, ''); if (false === $result) { throw new InvalidParameterException([$id => Yii::t("product", "categoryName_isUsed")]); } $where = ['_id' => new \MongoId($id), 'accountId' => $accountId, 'isDeleted' => false]; ProductCategory::updateAll(['name' => $params['name']], $where); Product::updateAll(['category.name' => $params['name']], ['category.id' => new \MongoId($id)]); return ProductCategory::findByPk($id); }
<?php use yii\helpers\Html; //use yii\widgets\ListView; use yii\grid\GridView; use backend\modules\product\models\Product; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = $type; $this->params['breadcrumbs'][] = ['label' => 'Продукция', 'url' => '/#products']; $this->params['breadcrumbs'][] = $this->title; $this->params['right_menu_page'] = [['label' => 'Производство', 'url' => ['/page/view', 'alias' => 'proizvodstvo']], ['label' => 'О нас', 'url' => ['/page/view', 'alias' => 'about']]]; foreach (Product::find()->groupBy('product_type')->all() as $data) { $this->params['right_menu'][] = ['label' => Product::getProductTypeName2($data->product_type), 'url' => ['/product/index', 'type' => $data->product_type]]; } $this->registerJsFile('/js/filtrproducts.js'); ?> <!--Фильтр товаров--> <div class="container"> <div class="row"> <div class="col-md-8"> <form> <div class="form-process"></div> <div class="col-md-8 form-group"> <input type="search" class="light-table-filter" data-table="table" placeholder="Поиск"> </div> </form> </div> </div> </div>
/** * check the goods info * @param $goods array */ public static function checkGoodsInfo($goods) { //get the productId $productIdList = []; foreach ($goods as $key => $info) { if (empty($info['productId'])) { throw new ServerErrorHttpException(Yii::t('product', 'invalide_params')); } if (!isset($info['score'])) { throw new ServerErrorHttpException(Yii::t('product', 'score_not_empty')); } if (!isset($info['total'])) { throw new ServerErrorHttpException(Yii::t('product', 'total_not_empty')); } $productIdList[] = new MongoId($info['productId']); } //check all product whether can be found in the product table $products = Product::findAll(['_id' => ['$in' => $productIdList]]); if (count($products) != count($productIdList) || count($products) <= 0) { throw new ServerErrorHttpException(Yii::t('product', 'invalide_params')); } //check the goods if (Goods::findOne(['productId' => ['$in' => $productIdList]])) { throw new ServerErrorHttpException(Yii::t('product', 'not_add_again')); } $data = []; foreach ($products as $product) { $key = $product['_id'] . ''; $data[$key]['productName'] = $product['name']; $data[$key]['sku'] = $product['sku']; } unset($key, $productIdList); foreach ($goods as $key => $value) { $productId = $value['productId'] . ''; $goods[$key]['productName'] = $data[$productId]['productName']; $goods[$key]['sku'] = $data[$productId]['sku']; } unset($productId, $data, $products); return $goods; }
/** * update the property * @param $id,int,proprty id * @param $params,array * @param $accountId,MongoId */ public static function updateProperty($id, $params, $accountId) { //update category property $where = ['accountId' => $accountId, '_id' => new \MongoId($id), 'properties.id' => $params['propertyId']]; $categoryPropertyInfo = ProductCategory::findOne($where); if ($categoryPropertyInfo) { //only update the name and isrequired $addproperties = []; if (!empty($categoryPropertyInfo->properties)) { $where = ['properties.id' => $params['propertyId']]; ProductCategory::updateAll(['$set' => ['properties.$.name' => $params['name'], 'properties.$.isRequired' => $params['isRequired']]], $where); } //check whether have properties $productInfo = Product::findOne(['category.id' => new \MongoId($id)]); if ($productInfo) { $where = ['category.properties.id' => $params['propertyId']]; $updateData = ['category.properties.$.name' => $params['name'], 'category.properties.$.value' => $params['defaultValue']]; Product::updateAll(['$set' => $updateData], $where); unset($productInfo); } unset($where); return $categoryPropertyInfo; } else { throw new BadRequestHttpException("categoryId or propertyId invalid"); } }
public function getById($id) { return ModelProduct::findOne(['_id' => $id]); }
/** * export excel for the promotioncode to upload to qiniu,and return key to frontend */ public function actionExport() { $params = $this->getQuery(); if (empty($params['createdAt']) || empty($params['productId'])) { throw new BadRequestHttpException('missing param createdAt or productId'); } $productId = new MongoId($params['productId']); $product = Product::findByPk($productId); if (empty($product)) { throw new BadRequestHttpException('invalid productId'); } $startTime = new MongoDate($params['createdAt']); $endTime = new MongoDate($params['createdAt'] + 1); $condition = ['productId' => $productId, 'createdAt' => ['$gte' => $startTime, '$lt' => $endTime]]; $data = PromotionCode::findOne($condition); if ($data) { $accountId = $this->getAccountId(); list($sku, $code, $isUsed) = explode(',', Yii::t('product', 'export_promotioncode_title')); $header = ['code' => $code, 'isUsed' => $isUsed]; $key = $product['name'] . '_' . date('Ymd') . '_' . $product['sku']; $status = ['vaild' => 'Y', 'unvaild' => 'N']; $fields = 'code,isUsed'; $exportArgs = ['status' => $status, 'header' => $header, 'key' => $key, 'sku' => $product->sku, 'accountId' => (string) $accountId, 'condition' => serialize($condition), 'fields' => $fields, 'description' => 'Direct: export promotionCodes']; $jobId = Yii::$app->job->create('backend\\modules\\product\\job\\ExportPromotionCode', $exportArgs); $result = ['result' => 'success', 'message' => 'exporting file', 'data' => ['jobId' => $jobId, 'key' => $key]]; } else { $result = ['result' => 'error', 'message' => 'no datas', 'data' => []]; } return $result; }
public static function _generateCodePrefix($productId) { $year = date('y'); $year = $year - 10; //start from 2015 $yearPrefix = self::_getPrefix(1, $year); $product = Product::findByPk($productId); $productIndex = Product::find()->where(['createdAt' => ['$lte' => $product->createdAt], 'accountId' => $product->accountId])->orderBy(['createdAt' => SORT_ASC])->count(); $productPrefix = self::_getPrefix(2, $productIndex); $batchPrefix = self::_getPrefix(1, $product->batchCode); return $yearPrefix . $productPrefix . $batchPrefix; }
<div class="col-md-8"> <?php echo $form->field($model, 'product_img')->fileInput(); ?> <?php if (!$model->isNewRecord) { ?> <img src="<?php echo Yii::$app->params['domainName'] . '/images/' . $model->product_img; ?> " /> <?php } ?> <?php echo $form->field($model, 'product_type')->dropDownlist(Product::getTypeArray()); ?> <?php echo $form->field($model, 'product_name')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'product_summary')->textarea(['rows' => 6]); ?> <?php echo $form->field($model, 'product_description')->widget(Widget::className(), ['settings' => ['lang' => 'ru', 'replaceDivs' => false, 'minHeight' => 400, 'imageUpload' => Url::to(['/product/default/image-upload']), 'fileUpload' => Url::to(['/product/default/file-upload'])]]); ?> </div> <div class="col-md-4"> <?php echo $form->field($model, 'meta_title')->textInput(); ?>
/** * create the structure for promorioncodeanalysis * @param $datas,array,source data * @param $type,mongoInt,the type for ananlysis * @param $yesterday,mongodate, create time */ public static function createAnalysisData($datas, $type, $yesterday) { $campaignData = []; foreach ($datas as $data) { if (!empty($data['_id']['productId'])) { $productId = $data['_id']['productId']; $product = Product::findByPk($data['_id']['productId']); $productName = empty($product['name']) ? 'unknow' : $product['name']; } else { $productId = $productName = ''; } $campaignData[] = ['createdAt' => $yesterday, 'total' => $data['total'], 'type' => $type, 'productId' => $productId, 'productName' => $productName, 'campaignId' => $data['_id']['campaignId'], 'accountId' => $data['_id']['accountId']]; } return $campaignData; }
<?php use yii\helpers\Html; use yii\grid\GridView; use backend\modules\product\models\Product; /* @var $this yii\web\View */ /* @var $searchModel backend\modules\product\models\ProductSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Продукция'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="box box-primary"> <div class="box-body"> <p> <?php echo Html::a('Добавить продукцию', ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], ['attribute' => 'product_img', 'format' => 'raw', 'value' => function ($model, $key, $index, $column) { return Html::img(Yii::$app->params['domainName'] . '/images/' . $model->product_img, ['width' => '130px']); }, 'contentOptions' => ['style' => 'width:130px;']], ['attribute' => 'product_type', 'filter' => Product::getTypeArray(), 'value' => 'ProductTypeName', 'contentOptions' => ['style' => 'width:250px;']], 'product_name', ['class' => 'yii\\grid\\ActionColumn', 'template' => '{update} {delete}', 'contentOptions' => ['class' => 'actionColumn'], 'buttonOptions' => ['class' => 'btn btn-sm btn-default', 'style' => 'padding:1px 10px;']]]]); ?> </div> </div>
public function actionGetProductSku() { return Product::createSku(); }
/** * support multiple id to delete the product category * @param $id,string * @param $accountId,MongoId */ public static function deleteProductCategory($id, $accountId) { $idList = self::getCategoryList($id, ','); $where = array_merge(['in', 'category.id', $idList], ['accountId' => $accountId, 'isDeleted' => false]); Product::updateAll(['category' => []], $where); }
/** * @return \yii\db\ActiveQuery */ public function getProduct() { return $this->hasOne(Product::className(), ['id' => 'product_id']); }
public static function generateStatsCampaignProductCodeQuarterlyData($condition) { $campaignLogDailys = StatsMemberCampaignLogDaily::getCollection()->aggregate([['$match' => $condition], ['$group' => ['_id' => ['productId' => '$productId'], 'total' => ['$sum' => 1]]]]); if (!empty($campaignLogDailys)) { $productIds = StatsMemberCampaignLogDaily::distinct('productId', $condition); $products = Product::findAll(['_id' => ['$in' => $productIds]]); $productNames = []; foreach ($products as $product) { $productNames[(string) $product->_id] = $product->name; } foreach ($campaignLogDailys as $campaignLogDaily) { $productId = $campaignLogDaily['_id']['productId']; $rows[] = ['productId' => $productId, 'productName' => isset($productNames[(string) $productId]) ? $productNames[(string) $productId] : '', 'total' => $campaignLogDaily['total'], 'year' => $condition['year'], 'quarter' => $condition['quarter'], 'accountId' => $condition['accountId']]; } StatsCampaignProductCodeQuarterly::batchInsert($rows); } }
/** * @return \yii\db\ActiveQuery */ public function getProducts() { return $this->hasMany(Product::className(), ['id' => 'product_id'])->viaTable('device_product', ['device_id' => 'id']); // return $this->hasOne(Product::className(), ['id' => 'device_product_id']); }
/** *create a number of product */ public static function createSku() { $charlist = '0123456789'; $rand = StringUtil::rndString(6, 0, $charlist); $currentChar = time() . $rand; $result = Product::getSku($currentChar); if (empty($result)) { return ['number' => $currentChar]; } else { self::createNum(); } }
public function changeProductStatus($productId) { $product = Product::findByPk($productId); if (false == $product['isBindCode']) { Product::updateAll(['isBindCode' => true], ['_id' => $productId]); } }
/** * search the product id from the campaign * @param $accountId,MongoId * @param $pageSize,int,the number record for one page * @param $page,int, which page to show */ public static function searchProductInfo($accountId, $pageSize, $page) { $where = ['accountId' => $accountId, 'isDeleted' => self::NOT_DELETED]; $campaigns = Campaign::find()->select(['promotion.data'])->where($where)->all(); $showData = []; //get productId if (!empty($campaigns)) { $productIds = []; foreach ($campaigns as $campaign) { if (!empty($campaign['promotion']['data'])) { $ids = $campaign['promotion']['data']; foreach ($ids as $id) { $productIds[] = $id; } } } //get product info from product with productId if (!empty($productIds)) { $productIds = array_values(array_unique($productIds)); $len = count($productIds); $offset = 0; $where = ['_id' => ['$in' => $productIds]]; $query = Product::find()->select(['_id', 'name'])->where($where); if ($len > $pageSize && $pageSize > 0) { $offset = ($page - 1) * $pageSize; $showData = $query->offset($offset)->limit($pageSize); } $showData = $query->all(); } } $data = ['data' => $showData, 'num' => empty($len) ? 0 : $len]; return $data; }
/** * @return \yii\db\ActiveQuery */ public function getProducts() { return $this->hasMany(Product::className(), ['id' => 'product_id'])->viaTable('brand_product', ['brand_id' => 'id']); }
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; }
/** * @param $accountId,string * @param $createdTime, int(timestamp) */ public static function generateByYearAndQuarter($accountId, $createdTime) { $accountId = new MongoId($accountId); $today = new MongoDate($createdTime); $tomorrow = new MongoDate(strtotime('+1 day', $createdTime)); $condition = ['accountId' => $accountId, 'createdAt' => ['$gte' => $today, '$lt' => $tomorrow]]; $campaignLogDailys = StatsMemberCampaignLogDaily::getCollection()->aggregate([['$match' => $condition], ['$group' => ['_id' => ['productId' => '$productId', 'year' => '$year', 'quarter' => '$quarter'], 'total' => ['$sum' => 1]]]]); $rows = []; if (!empty($campaignLogDailys)) { foreach ($campaignLogDailys as $item) { $where = ['productId' => $item['_id']['productId'], 'year' => $item['_id']['year'], 'quarter' => $item['_id']['quarter']]; $productCodeLog = self::findOne($where); if (!empty($productCodeLog)) { //summary this product $total = self::getTotalWithProductId($where); if ($total > 0) { $productCodeLog->total = $total; $productCodeLog->save(true, ['total']); } } else { $productName = ''; $product = Product::findByPK($item['_id']['productId']); if (!empty($product)) { $productName = $product->name; } $rows[] = ['productId' => $item['_id']['productId'], 'productName' => $productName, 'total' => $item['total'], 'year' => $item['_id']['year'], 'quarter' => $item['_id']['quarter'], 'accountId' => $accountId]; } } unset($item, $campaignLogDailys); } return self::batchInsert($rows); }