ProductMongodb.php 14.9 KB
Newer Older
R
root 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php
/**
 * FecShop file.
 *
 * @link http://www.fecshop.com/
 * @copyright Copyright (c) 2016 FecShop Software LLC
 * @license http://www.fecshop.com/license/
 */
namespace fecshop\services\product;
use Yii;
use yii\base\InvalidValueException;
use yii\base\InvalidConfigException;
use fecshop\models\mongodb\Product;
/**
 * @author Terry Zhao <2358269014@qq.com>
 * @since 1.0
 */
class ProductMongodb implements ProductInterface
{
	public $numPerPage = 20;
	
	public function getPrimaryKey(){
		return '_id';
	}
	
	public function getByPrimaryKey($primaryKey){
		if($primaryKey){
			return Product::findOne($primaryKey);
		}else{
			return new Product;
		}
	}
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
	/**
	 * @property $sku|Array 
	 * @property $returnArr|boolean 返回的数据是否是数组格式,如果设置为
	 *		false,则返回的是对象数据
	 * @return  Array or Object
	 * 通过sku 获取产品,一个产品
	 */
	public function getBySku($sku,$returnArr=true){
		if($sku){
			if($returnArr){
				return Product::find()->asArray()
					->where(['sku' => $sku])
					->one()
					;
			}else{
				return Product::findOne(['sku' => $sku]);
			} 
		}
	}
	
	/**
	 * @property $spu|Array 
	 * @property $returnArr|boolean 返回的数据是否是数组格式,如果设置为
	 *		false,则返回的是对象数据
	 * @return  Array or Object
	 *  通过spu 获取产品数组
	 */
	public function getBySpu($spu,$returnArr=true){
		if($spu){
			if($returnArr){
				return Product::find()->asArray()
					->where(['spu' => $spu])
					->all();
			}else{
				return Product::find()
					->where(['spu' => $spu])
					->all();
			} 
		}
	}
	
R
root 已提交
74 75 76 77 78 79 80
	/*
	 * example filter:
	 * [
	 * 		'numPerPage' 	=> 20,  	
	 * 		'pageNum'		=> 1,
	 * 		'orderBy'	=> ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
	 * 		'where'			=> [
R
root 已提交
81 82 83
				['>','price',1],
				['<=','price',10]
	 * 			['sku' => 'uk10001'],
R
root 已提交
84 85 86 87 88 89 90 91 92 93 94 95
	 * 		],
	 * 	'asArray' => true,
	 * ]
	 */
	public function coll($filter=''){
		$query = Product::find();
		$query = Yii::$service->helper->ar->getCollByFilter($query,$filter);
		return [
			'coll' => $query->all(),
			'count'=> $query->count(),
		];
	}
96 97 98 99 100 101 102 103
	/**
	 *  得到总数
	 */
	public function collCount($filter=''){
		$query = Product::find();
		$query = Yii::$service->helper->ar->getCollByFilter($query,$filter);
		return $query->count();
	}
R
root 已提交
104
	
R
root 已提交
105 106 107 108 109 110 111
	/**
	 * @property  $product_id_arr | Array
	 * @property  $category_id | String
	 * 在给予的产品id数组$product_id_arr中,找出来那些产品属于分类 $category_id
	 * 该功能是后台分类编辑中,对应的分类产品列表功能
	 * 也就是在当前的分类下,查看所有的产品,属于当前分类的产品,默认被勾选。
	 */
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	public function getCategoryProductIds($product_id_arr,$category_id){
		$id_arr = [];
		if(is_array($product_id_arr) && !empty($product_id_arr)){
			$query = Product::find()->asArray();
			$mongoIds = [];
			foreach($product_id_arr as $id){
				$mongoIds[] = new \MongoId($id);
			}
			//var_dump($mongoIds);
			$query->where(['in',$this->getPrimaryKey(),$mongoIds]);
			$query->andWhere(['category'=>$category_id]);
			$data = $query->all();
			if(is_array($data) && !empty($data) ){
				foreach($data as $one){
					$id_arr[] = $one[$this->getPrimaryKey()];
				}
			}
		}
		//echo '####';
		//var_dump($id_arr);
		//echo '####';
		return $id_arr;
	}
	
R
root 已提交
136
	/**
R
root 已提交
137
	 * @property $one|Array , 产品数据数组
138
	 * @property $originUrlKey|String , 产品的原来的url key ,也就是在前端,分类的自定义url。
R
root 已提交
139 140
	 * 保存产品(插入和更新),以及保存产品的自定义url  
     * 如果提交的数据中定义了自定义url,则按照自定义url保存到urlkey中,如果没有自定义urlkey,则会使用name进行生成。	 
R
root 已提交
141
	 */
142 143
	public function save($one,$originUrlKey='catalog/product/index'){
		
144 145 146
		if(!$this->initSave($one)){
			return;
		}
R
root 已提交
147 148 149 150 151 152 153 154
		$currentDateTime = \fec\helpers\CDate::getCurrentDateTime();
		$primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : '';
		if($primaryVal){
			$model = Product::findOne($primaryVal);
			if(!$model){
				Yii::$service->helper->errors->add('Product '.$this->getPrimaryKey().' is not exist');
				return;
			}	
155 156 157 158 159 160 161 162 163 164
			#验证sku 是否重复
			$product_one = Product::find()->asArray()->where([
				'<>',$this->getPrimaryKey(),(new \MongoId($primaryVal))
			])->andWhere([
				'sku' => $one['sku'],
			])->one();
			if($product_one['sku']){
				Yii::$service->helper->errors->add('Product Sku 已经存在,请使用其他的sku');
				return;
			}
R
root 已提交
165 166 167 168 169 170
		}else{
			$model = new Product;
			$model->created_at = time();
			$model->created_user_id = \fec\helpers\CUser::getCurrentUserId();
			$primaryVal = new \MongoId;
			$model->{$this->getPrimaryKey()} = $primaryVal;
171 172 173 174 175 176 177 178
			#验证sku 是否重复
			$product_one = Product::find()->asArray()->where([
				'sku' => $one['sku'],
			])->one();
			if($product_one['sku']){
				Yii::$service->helper->errors->add('Product Sku 已经存在,请使用其他的sku');
				return;
			}
R
root 已提交
179 180
		}
		$model->updated_at = time();
181 182 183 184 185
		/**
		 * 计算出来产品的最终价格。
		 */
		$one['final_price']= Yii::$service->product->price->getFinalPrice($one['price'],$one['special_price'],$one['special_from'],$one['special_to']);
		$one['score'] = (int)$one['score'];
R
root 已提交
186
		unset($one['_id']);
187 188 189
		/**
		 * 保存产品
		 */
R
root 已提交
190
		$saveStatus = Yii::$service->helper->ar->save($model,$one);
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		/**
		 * 自定义url部分
		 */
		if($originUrlKey){
			$originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal;
			$originUrlKey = isset($one['url_key']) ? $one['url_key'] : '';
			$defaultLangTitle = Yii::$service->fecshoplang->getDefaultLangAttrVal($one['name'],'name');
			$urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle,$originUrl,$originUrlKey);
			$model->url_key = $urlKey;
			$model->save();
		}
		/**
		 * 更新产品信息到搜索表。
		 */
		$product_ids = [$model->{$this->getPrimaryKey()} ];
		Yii::$service->search->syncProductInfo($product_ids);
R
root 已提交
207 208
		return true;
	}
R
root 已提交
209 210 211 212 213
	/**
	 * @property $one|Array
	 * 对保存的数据进行数据验证
	 * sku  spu   默认语言name , 默认语言description不能为空。
	 */
214 215 216
	protected function initSave($one){
		if(!isset($one['sku']) || empty($one['sku'])){
			Yii::$service->helper->errors->add(' sku 必须存在 ');
R
root 已提交
217 218
			return false;
		}
219 220 221 222 223 224 225 226 227 228 229 230
		if(!isset($one['spu']) || empty($one['spu'])){
			Yii::$service->helper->errors->add(' spu 必须存在 ');
			return false;
		}
		$defaultLangName = \Yii::$service->fecshoplang->getDefaultLangAttrName('name'); 
		if(!isset($one['name'][$defaultLangName]) || empty($one['name'][$defaultLangName])){
			Yii::$service->helper->errors->add(' name '.$defaultLangName.' 不能为空 ');
			return false;
		}
		$defaultLangDes = \Yii::$service->fecshoplang->getDefaultLangAttrName('description');
		if(!isset($one['description'][$defaultLangDes]) || empty($one['description'][$defaultLangDes])){
			Yii::$service->helper->errors->add(' description '.$defaultLangDes.'不能为空 ');
R
root 已提交
231 232 233 234 235
			return false;
		}
		return true;
	}
	
236
	/**
R
root 已提交
237 238 239
	 * @property $ids | Array or String
	 * 删除产品,如果ids是数组,则删除多个产品,如果是字符串,则删除一个产品
	 * 在产品产品的同时,会在url rewrite表中删除对应的自定义url数据。
240 241 242 243 244 245 246 247 248 249 250
	 */ 
	public function remove($ids){
		if(empty($ids)){
			Yii::$service->helper->errors->add('remove id is empty');
			return false;
		}
		if(is_array($ids)){
			foreach($ids as $id){
				$model = Product::findOne($id);
				if(isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()]) ){
					$url_key =  $model['url_key'];
251
					# 删除在重写url里面的数据。
252
					Yii::$service->url->removeRewriteUrlKey($url_key);
253 254
					# 删除在搜索表(各个语言)里面的数据
					Yii::$service->search->removeByProductId($model[$this->getPrimaryKey()]);
255 256 257 258 259
					$model->delete();
					//$this->removeChildCate($id);
				}else{
					Yii::$service->helper->errors->add("Product Remove Errors:ID:$id is not exist.");
					return false;
R
root 已提交
260 261 262
				}
			}
		}else{
263 264 265 266
			$id = $ids;
			$model = Product::findOne($id);
			if(isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()]) ){
				$url_key =  $model['url_key'];
267
				# 删除在重写url里面的数据。
268
				Yii::$service->url->removeRewriteUrlKey($url_key);
269 270
				# 删除在搜索里面的数据
				Yii::$service->search->removeByProductId($model[$this->getPrimaryKey()]);
271 272 273 274 275
				$model->delete();
				//$this->removeChildCate($id);
			}else{
				Yii::$service->helper->errors->add("Product Remove Errors:ID:$id is not exist.");
				return false;
R
root 已提交
276 277
			}
		}
278
		return true;
R
root 已提交
279 280
	}
	
R
root 已提交
281 282 283 284 285 286
	/**
	 * @property $category_id | String  分类的id的值
	 * @property $addCateProductIdArr | Array 分类中需要添加的产品id数组,也就是给这个分类增加这几个产品。
	 * @property $deleteCateProductIdArr | Array 分类中需要删除的产品id数组,也就是在这个分类下面去除这几个产品的对应关系。
	 * 这个函数是后台分类编辑功能中使用到的函数,在分类中可以一次性添加多个产品,也可以删除多个产品,产品和分类是多对多的关系。
	 */
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	public function addAndDeleteProductCategory($category_id,$addCateProductIdArr,$deleteCateProductIdArr){
		# 在 addCategoryIdArr 查看哪些产品,分类id在product中已经存在,
		$idKey = $this->getPrimaryKey();
		//var_dump($addCateProductIdArr);
		if(is_array($addCateProductIdArr) && !empty($addCateProductIdArr) && $category_id){
			$addCateProductIdArr = array_unique($addCateProductIdArr);
			foreach($addCateProductIdArr as $product_id){
				if(!$product_id){
					continue;
				}
				$product = Product::findOne($product_id);
				if(!$product[$idKey]){
					continue;
				}
				$category = $product->category;
				$category = ($category && is_array($category)) ? $category : [];
				//echo $category_id;
				if(!in_array($category_id,$category)){
					//echo $category_id;
					$category[] = $category_id;
					$product->category = $category;
					$product->save();
				}
			}
		}
		
		if(is_array($deleteCateProductIdArr) && !empty($deleteCateProductIdArr) && $category_id){
			$deleteCateProductIdArr = array_unique($deleteCateProductIdArr);
			foreach($deleteCateProductIdArr as $product_id){
				if(!$product_id){
					continue;
				}
				$product = Product::findOne($product_id);
				if(!$product[$idKey]){
					continue;
				}
				$category = $product->category;
				if(in_array($category_id,$category)){
					$arr = [];
					foreach($category as $c){
						if($category_id != $c){
							$arr[] = $c;
						}
					}
					$product->category = $arr;
					$product->save();
				}
			}
		}
	}
337
	
R
root 已提交
338 339 340
	/**
	 * 通过where条件 和 查找的select 字段信息,得到产品的列表信息,
	 * 这里一般是用于前台的区块性的不分页的产品查找。
R
root 已提交
341 342
	 * 结果数据没有进行进一步处理,需要前端获取数据后在处理。
	 */
R
root 已提交
343 344 345 346 347 348 349 350 351 352 353 354
	public function getProducts($filter){
		$where 			= $filter['where'];
		if(empty($where))
			return [];
		$select			= $filter['select'];
		$query = Product::find()->asArray();
		$query->where($where);
		if(is_array($select) && !empty($select)){
			$query->select($select);
		}
		return $query->all();
	}
R
root 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	/**
	 *[
	 *	'category_id' 	=> 1,
	 *	'pageNum'		=> 2,
	 *	'numPerPage'	=> 50,
	 *	'orderBy'		=> 'name',
	 *	'where'			=> [
	 *		['>','price',11],
	 *		['<','price',22],
	 *	],
	 *	'select'		=> ['xx','yy'],
	 *	'group'			=> '$spu',
	 * ]
	 * 得到分类下的产品,在这里需要注意的是:
	 * 1.同一个spu的产品,有很多sku,但是只显示score最高的产品,这个score可以通过脚本取订单的销量(最近一个月,或者
	 *   最近三个月等等),或者自定义都可以。
	 * 2.结果按照filter里面的orderBy排序
	 * 3.由于使用的是mongodb的aggregate(管道)函数,因此,此函数有一定的限制,就是该函数
	 *   处理后的结果不能大约32MB,因此,如果一个分类下面的产品几十万的时候可能就会出现问题,
	 *   这种情况可以用专业的搜索引擎做聚合工具。
	 *   不过,对于一般的用户来说,这个不会成为瓶颈问题,一般一个分类下的产品不会出现几十万的情况。
	 * 4.最后就得到spu唯一的产品列表(多个spu相同,sku不同的产品,只要score最高的那个)
	 */	
	 
379 380 381 382
	public function getFrontCategoryProducts($filter){
		$where 			= $filter['where'];
		if(empty($where))
			return [];
R
root 已提交
383
		$orderBy 		= $filter['orderBy'];
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		$pageNum 		= $filter['pageNum'];
		$numPerPage 	= $filter['numPerPage'];
		$select			= $filter['select'];
		$group['_id'] 	= $filter['group'];
		$project 		= [];
		foreach($select as $column){
			$project[$column] 	= 1;
			$group[$column] 	= ['$first' => '$'.$column];
		}
		$pipelines = [
			[
				'$match' 	=> $where,
			],
			[
				'$sort' => [
					'score' => -1
				]
			],
			[
				'$project' 	=> $project
			],
			[
				'$group'	=> $group,
			],
			[
				'$sort' 	=> $orderBy,
			],
		];
R
root 已提交
412
		//var_dump($orderBy);
413 414 415 416 417 418 419 420 421
		$product_data = Product::getCollection()->aggregate($pipelines);
		$product_total_count = count($product_data);
		$pageOffset = ($pageNum - 1) * $numPerPage;
		$products = array_slice($product_data, $pageOffset, $numPerPage);
		return [
			'coll' => $products,
			'count' => $product_total_count,
		];
	}
R
root 已提交
422 423 424 425 426 427
	/**
	 * @property $filter_attr | String 需要进行统计的字段名称
	 * @propertuy $where | Array  搜索条件。这个需要些mongodb的搜索条件。
	 * 得到的是个属性,以及对应的个数。
	 * 这个功能是用于前端分类侧栏进行属性过滤。
	 */
R
root 已提交
428 429 430 431
	public function getFrontCategoryFilter($filter_attr,$where){
		if(empty($where))
			return [];
		$group['_id'] 	= '$'.$filter_attr;
R
root 已提交
432
		$group['count'] = ['$sum'=> 1];
R
root 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
		$project 		= [$filter_attr => 1];
		$pipelines = [
			[
				'$match' 	=> $where,
			],
			[
				'$project' 	=> $project
			],
			[
				'$group'	=> $group,
			],
		];
		$filter_data = Product::getCollection()->aggregate($pipelines);
		return $filter_data;
	}
448
	
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
	
	/*
	$project 		= [];
	$group['_id'] 	= $filter['group'];
	foreach($select as $column){
		$project[$column] 	= 1;
		if($column != '_id'){
			$group[$column] 	= ['$first' => '$'.$column];
		}else{
			$group['mongo_id'] 	= ['$first' => '$'.$column];
		
		}
	
	}
	
	$pipelines = [
		[
			'$match' 	=> $where,
		],
		
		[
			'$project' 	=> $project
		],
		[
			'$group'	=> $group,
		],
		
	];
	//var_dump($pipelines);
	//exit;
	$data = Product::getCollection()->aggregate($pipelines);
	
	*/
	//var_dump($where);exit;
	//var_dump($productIds );
	//$data = Product::getCollection()
	//	->fullTextSearch($searchText,[],['_id'],['limit'=>$product_search_max_count])
	//	;
	//exit;
		
	
R
root 已提交
490 491 492
}