Goods.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: 芸众商城 www.yunzshop.com
  5. * Date: 2017/2/22
  6. * Time: 19:35
  7. */
  8. namespace app\common\models;
  9. use app\common\events\goods\GoodsStockNotEnoughEvent;
  10. use app\common\facades\SiteSetting as SiteSettingFacades;
  11. use app\common\models\goods\GoodsFiltering;
  12. use app\frontend\models\MemberLevel;
  13. use app\frontend\models\MemberShopInfo;
  14. use app\frontend\modules\orderGoods\price\adapter\GoodsAdapterManager;
  15. use app\frontend\modules\orderGoods\price\adapter\GoodsPriceAdapter;
  16. use Illuminate\Support\Facades\Redis;
  17. use app\common\exceptions\AppException;
  18. use app\common\exceptions\GoodsStockNotEnough;
  19. use app\common\models\goods\Discount;
  20. use app\common\models\goods\GoodsDispatch;
  21. use app\common\models\goods\GoodsLimitBuy;
  22. use app\common\models\goods\GoodsVideo;
  23. use app\common\models\goods\Privilege;
  24. use app\common\modules\goods\GoodsPriceManager;
  25. use app\common\models\goods\Share;
  26. use app\common\services\wordanalysis\Analysis;
  27. use app\framework\Database\Eloquent\Collection;
  28. use app\frontend\modules\goods\stock\GoodsStock;
  29. use Illuminate\Database\Eloquent\SoftDeletes;
  30. use Illuminate\Support\Facades\DB;
  31. use app\common\modules\discount\GoodsMemberLevelDiscount;
  32. use Yunshop\Invoice\models\InvoiceGoods;
  33. use Yunshop\Invoice\models\InvoiceRelation;
  34. /**
  35. * Class Goods
  36. * @package app\common\models
  37. * @property string status
  38. * @property string status_name
  39. * @property string title
  40. * @property int uniacid
  41. * @property int id
  42. * @property int stock
  43. * @property float max_price
  44. * @property float min_price
  45. * @property string thumb
  46. * @property string thumb_url
  47. * @property int buyNum
  48. * @property int has_option
  49. * @property int virtual_sales
  50. * @property int plugin_id
  51. * @property int comment_num
  52. * @property int is_comment
  53. * @property int is_recommand
  54. * @property int is_discount
  55. * @property int is_hot
  56. * @property int is_new
  57. * @property int weight
  58. * @property int real_sales
  59. * @property int show_sales
  60. * @property int reduce_stock_method
  61. * @property int cost_price
  62. * @property int price
  63. * @property int market_price
  64. * @property int product_sn
  65. * @property string goods_sn
  66. * @property string content
  67. * @property string description
  68. * @property string sku
  69. * @property int type
  70. * @property int brand_id
  71. * @property int goods_video
  72. * @property int display_order
  73. * @property float deal_price
  74. * @property float vip_price
  75. * @property float next_level_price
  76. * @property int is_open_micro
  77. * @property float vip_next_price
  78. * @property int price_level
  79. * @property int withhold_stock
  80. * @property string next_level_name
  81. * @property Collection hasManySpecs
  82. * @property Collection hasManyOptions
  83. * @property GoodsDiscount hasManyGoodsDiscount
  84. * @property GoodsDispatch hasOneGoodsDispatch
  85. * @property Privilege hasOnePrivilege
  86. * @property Brand hasOneBrand
  87. * @property GoodsLimitBuy hasOneGoodsLimitBuy
  88. * @property GoodsAdvertising hasOneGoodsAdvertising
  89. * @property GoodsVideo hasOneGoodsVideo
  90. * @property Share hasOneShare
  91. * @property Sale hasOneSale
  92. */
  93. class Goods extends BaseModel
  94. {
  95. use SoftDeletes;
  96. public $table = 'yz_goods';
  97. public $attributes = ['display_order' => 0];
  98. protected $mediaFields = ['thumb', 'thumb_url'];
  99. protected $dates = ['deleted_at'];
  100. protected $appends = ['status_name'];
  101. public $fillable = [];
  102. protected $guarded = ['widgets'];
  103. public $widgets = [];
  104. protected $search_fields = ['title'];
  105. static protected $needLog = true;
  106. private $dealPrice;
  107. protected $vipDiscountAmount;
  108. public $vipDiscountLog;
  109. public $nextLevelName = '';
  110. /**
  111. * 实物
  112. */
  113. const REAL_GOODS = 1;
  114. /**
  115. * 虚拟物品
  116. */
  117. const VIRTUAL_GOODS = 2;
  118. /*
  119. 商品 plugin_id :
  120. 0 => 平台商品
  121. 31 => 门店收银台
  122. 32 => 门店商品
  123. 40 => 租赁商品
  124. 41 => 网约车商品
  125. 42 => 网约车分红
  126. 43 => ps 由于服务站订单使用了
  127. 44 => 京东-供应链
  128. 92 => 供应商商品
  129. */
  130. /**
  131. * 定义字段名
  132. *
  133. * @return array
  134. */
  135. public function atributeNames()
  136. {
  137. return ['title' => '商品名称', 'price' => '价格', 'cost_price' => '成本价', 'sku' => '商品单位', 'thumb' => '图片', 'weight' => '重量', 'stock' => '库存',];
  138. }
  139. /**
  140. * 字段规则
  141. *
  142. * @return array
  143. */
  144. public function rules()
  145. {
  146. return ['title' => 'required', 'price' => 'required|numeric|min:0', 'cost_price' => 'required|numeric|min:0', 'sku' => 'required', 'thumb' => 'required', 'weight' => 'required', 'stock' => 'required|numeric|min:0',];
  147. }
  148. public static function getList()
  149. {
  150. return static::uniacid();
  151. }
  152. public static function getGoodsById($id)
  153. {
  154. return static::find($id);
  155. }
  156. public static function getGoodsByIds($ids)
  157. {
  158. if (!is_array($ids)) {
  159. return [];
  160. }
  161. return self::whereIn('id', $ids)->get();
  162. }
  163. public function hasManyParams()
  164. {
  165. return $this->hasMany('app\common\models\GoodsParam', 'goods_id', 'id');
  166. }
  167. public function belongsToCategorys()
  168. {
  169. return $this->hasMany('app\common\models\GoodsCategory', 'goods_id', 'id');
  170. }
  171. /**
  172. * @return \Illuminate\Database\Eloquent\Relations\HasMany
  173. */
  174. public function hasManyGoodsDiscount()
  175. {
  176. return $this->hasMany('app\common\models\GoodsDiscount', 'goods_id', 'id');
  177. }
  178. public function hasManyOptions()
  179. {
  180. return $this->hasMany('app\common\models\GoodsOption', 'goods_id', 'id');
  181. }
  182. public function hasOneBrand()
  183. {
  184. return $this->hasOne('app\common\models\Brand', 'id', 'brand_id');
  185. }
  186. public function hasOneShare()
  187. {
  188. return $this->hasOne('app\common\models\goods\Share', 'goods_id', 'id');
  189. }
  190. /**
  191. * @return \Illuminate\Database\Eloquent\Relations\HasOne
  192. * @throws \app\common\exceptions\ShopException
  193. */
  194. public function hasOnePrivilege()
  195. {
  196. return $this->hasOne($this->getNearestModel('goods\Privilege'));
  197. }
  198. public function hasOneGoodsDispatch()
  199. {
  200. return $this->hasOne('app\common\models\goods\GoodsDispatch', 'goods_id', 'id');
  201. }
  202. //该条关联可能出错了不是一对一关系 是一对多
  203. public function hasOneDiscount()
  204. {
  205. return $this->hasOne('app\common\models\goods\Discount', 'goods_id', 'id');
  206. }
  207. public function hasManyDiscount()
  208. {
  209. return $this->hasMany(Discount::class, 'goods_id', 'id');
  210. }
  211. public function hasManyGoodsCategory()
  212. {
  213. return $this->hasMany('app\common\models\GoodsCategory', 'goods_id', 'id');
  214. }
  215. public function hasManySpecs()
  216. {
  217. return $this->hasMany('app\common\models\GoodsSpec', 'goods_id', 'id');
  218. }
  219. public function hasManyPostageIncluded()
  220. {
  221. return $this->belongsToMany('app\common\models\goods\PostageIncludedCategory', 'yz_postage_included_category_goods', 'goods_id', 'postage_included_category_id');
  222. }
  223. public function hasOneSale()
  224. {
  225. return $this->hasOne(app('GoodsManager')->make('GoodsSale'), 'goods_id', 'id');
  226. }
  227. public function hasOneGoodsCoupon()
  228. {
  229. return $this->hasOne('app\common\models\goods\GoodsCoupon', 'goods_id', 'id');
  230. }
  231. public function hasOneGoodsLimitBuy()
  232. {
  233. return $this->hasOne('app\common\models\goods\GoodsLimitBuy', 'goods_id', 'id');
  234. }
  235. public function hasOneGoodsAdvertising()
  236. {
  237. return $this->hasOne('app\common\models\goods\GoodsAdvertising', 'goods_id', 'id');
  238. }
  239. public function hasOneInvitePage()
  240. {
  241. return $this->hasOne('app\common\models\goods\InvitePage', 'goods_id', 'id');
  242. }
  243. public function hasOnePointActivity()
  244. {
  245. return $this->hasOne('Yunshop\PointActivity\Backend\Models\GoodsPointActivity', 'goods_id', 'id');
  246. }
  247. public function hasOneGoodsService()
  248. {
  249. return $this->hasOne('app\common\models\goods\GoodsService', 'goods_id', 'id');
  250. }
  251. public function hasOneGoodsVideo()
  252. {
  253. return $this->hasOne('app\common\models\goods\GoodsVideo', 'goods_id', 'id');
  254. }
  255. public function hasOneSmallCodeUrl()
  256. {
  257. return $this->hasOne(GoodsSmallUrl::class, 'goods_id', 'id');
  258. }
  259. public function hasManyGoodsFilter()
  260. {
  261. return $this->hasMany(GoodsFiltering::class,'goods_id', 'id');
  262. }
  263. public function scopeState($query, $state = '')
  264. {
  265. if (!is_numeric($state)) {
  266. return $query;
  267. }
  268. return $query->where('status', $state);
  269. }
  270. public function scopePluginIdShow($query, $pluginId = [0])
  271. {
  272. return $query->whereIn('plugin_id', $pluginId);
  273. }
  274. public function scopeIsPlugin($query)
  275. {
  276. return $query->where('is_plugin', 0);
  277. }
  278. public function scopeWhereInPluginIds($query, $pluginIds = [])
  279. {
  280. if (empty($pluginIds)) {
  281. //标准商城默认都会显示下面这几种类型的商品
  282. $pluginIds = $this->showPluginGoods();
  283. }
  284. return $query->whereIn('plugin_id', $pluginIds);
  285. }
  286. protected function showPluginGoods()
  287. {
  288. $pluginIds = [0, 40, 41, 44, 52, 53, 103];//todo 这些都要写到对应的插件里
  289. $plugin = \app\common\modules\shop\ShopConfig::current()->get('shop-foundation.goods.plugin');
  290. $plugin = array_merge($plugin, $pluginIds);
  291. return $plugin;
  292. }
  293. public function scopeSearch($query, $filters)
  294. {
  295. $query->uniacid();
  296. if (!$filters) {
  297. return;
  298. }
  299. foreach ($filters as $key => $value) {
  300. switch ($key) {
  301. /*case 'category':
  302. $category[] = ['id' => $value * 1];
  303. $query->with("")->where('category_id', $category);
  304. break;*/
  305. //上架商品库存筛选
  306. case 'sell_stock':
  307. if ($value) {
  308. $query->where('yz_goods.status', 1)->where('yz_goods.stock', '>', 0);
  309. } else {
  310. $query->where('yz_goods.status', 1)->where('yz_goods.stock', '=', 0);
  311. }
  312. break;
  313. //新加过滤搜索
  314. case 'filtering':
  315. $scope = explode(',', rtrim($value, ','));
  316. $goodsFiltering = GoodsFiltering::select('goods_id')->whereIn('filtering_id', $scope)->get();
  317. $goods_ids = $goodsFiltering->pluck('goods_id')->unique()->toArray();
  318. if ($goods_ids) {
  319. $query->whereIn('yz_goods.id', $goods_ids);
  320. }
  321. break;
  322. //新加标签名过滤搜索
  323. case 'filtering_name':
  324. $goodsFiltering = GoodsFiltering::select('goods_id')
  325. ->join('yz_search_filtering', function ($join) use ($value) {
  326. $join->on('yz_goods_filtering.filtering_id', 'yz_search_filtering.id')
  327. ->where('name', 'like', '%' . $value . '%');
  328. })
  329. ->get();
  330. $goods_ids = $goodsFiltering->pluck('goods_id')->unique()->toArray();
  331. if ($goods_ids) {
  332. $query->whereIn('yz_goods.id', $goods_ids);
  333. } else {
  334. $query->where('yz_goods.id', 0);//标签下没有商品,条件为id=0令其搜索不到
  335. }
  336. break;
  337. case 'keyword':
  338. $splice_word = Analysis::getKeywords($value, 10);
  339. $ims = DB::getConfig('prefix');//获取前缀
  340. if (empty($splice_word)) {
  341. $splice_search = $ims . 'yz_goods.title like "%' . $value . '%"';
  342. } else {
  343. $splice_search = '';
  344. $splice_array = explode(',', $splice_word);
  345. foreach ($splice_array as $val) {
  346. $splice_search .= $ims . 'yz_goods.title like "%' . $val . '%" and ';
  347. }
  348. $splice_search = '(' . rtrim($splice_search, 'and ') . ')';
  349. }
  350. $query->whereRaw('(' . $splice_search . ' or ' . DB::getTablePrefix() . 'yz_goods.`id` = ?)', [$value]);
  351. break;
  352. case 'goods_id':
  353. $query->where('yz_goods.id', '=', $value);
  354. break;
  355. case 'brand_id':
  356. $query->where('brand_id', $value);
  357. break;
  358. case 'product_attr':
  359. //前端传参是 string 类型,后端传参是 array 类型
  360. if (!is_array($value)) {
  361. $value = explode(',', rtrim($value, ','));
  362. }
  363. //$value = explode(',', rtrim($value, ','));
  364. foreach ($value as $attr) {
  365. if ($attr == 'limit_buy') {
  366. $query->join('yz_goods_limitbuy', function ($join) {
  367. $join->on('yz_goods_limitbuy.goods_id', '=', 'yz_goods.id')->where('yz_goods_limitbuy.status', 1);
  368. });
  369. // $query->whereHas('hasOneGoodsLimitBuy', function (BaseModel $q) {
  370. // $q->where('status', 1);
  371. // });
  372. } else {
  373. $query->where($attr, 1);
  374. }
  375. }
  376. break;
  377. case 'status':
  378. $query->where('yz_goods.status', $value);
  379. break;
  380. case 'min_price':
  381. $query->where('price', '>', $value);
  382. break;
  383. case 'max_price':
  384. $query->where('price', '<', $value);
  385. break;
  386. case 'category':
  387. if (array_key_exists('parentid', $value) || array_key_exists('childid', $value) || array_key_exists('thirdid', $value)) {
  388. // $id = $value['parentid'][0] ? $value['parentid'][0] : '';
  389. // $id = $value['childid'][0] ? $value['childid'][0] : $id;
  390. // $id = $value['thirdid'][0] ? $value['thirdid'][0] : $id;
  391. $id = $value['parentid'] ? $value['parentid'] : '';
  392. $id = $value['childid'] ? $value['childid'] : $id;
  393. $id = $value['thirdid'] ? $value['thirdid'] : $id;
  394. $query->select(['yz_goods.*', 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id', 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids'])->join('yz_goods_category', 'yz_goods_category.goods_id', '=', 'yz_goods.id')->whereRaw('FIND_IN_SET(?,category_ids)', [$id]);
  395. } elseif (strpos($value, ',')) {
  396. $scope = explode(',', $value);
  397. $query->select(['yz_goods.*', 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id', 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids'])->join('yz_goods_category', function ($join) use ($scope) {
  398. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id');
  399. $join->where(function ($join) use ($scope) {
  400. foreach ($scope as $s) {
  401. $join->orWhereRaw('FIND_IN_SET(?,category_ids)', [$s]);
  402. }
  403. });
  404. });
  405. } else {
  406. $query->select(['yz_goods.*', 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id', 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids'])->join('yz_goods_category', function ($join) use ($value) {
  407. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->whereRaw('FIND_IN_SET(?,category_ids)', [$value]);
  408. // ->where('yz_goods_category.category_id', $value);
  409. });
  410. }
  411. break;
  412. case 'couponid': //搜索指定优惠券适用的商品
  413. $res = Coupon::getApplicableScope($value);
  414. switch ($res['type']) {
  415. case Coupon::COUPON_GOODS_USE: //优惠券适用于指定商品
  416. if (is_array($res['scope'])) {
  417. $query->whereIn('id', $res['scope']);
  418. } else {
  419. $query->where('id', $res['scope']);
  420. }
  421. break;
  422. case 8:
  423. if (is_array($res['scope'])) {
  424. $query->whereIn('id', $res['scope']);
  425. } else {
  426. $query->where('id', $res['scope']);
  427. }
  428. break;
  429. case Coupon::COUPON_CATEGORY_USE: //优惠券适用于指定商品分类
  430. if (is_array($res['scope'])) {
  431. $query->join('yz_goods_category', function ($join) use ($res) {
  432. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->whereIn('yz_goods_category.category_id', $res['scope']);
  433. });
  434. } else {
  435. $query->join('yz_goods_category', function ($join) use ($res) {
  436. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->where('yz_goods_category.category_id', $res['scope']);
  437. });
  438. }
  439. break;
  440. default: //优惠券适用于整个商城
  441. break;
  442. }
  443. break;
  444. case 'is_spec':
  445. if ($value !== '') {
  446. if ($value == 1) {
  447. $query->where('has_option', 1)->select('yz_goods.*');
  448. // $query->whereIn('yz_goods.id',function ($query) {
  449. // $query->select('goods_id')->from('yz_goods_spec')->where('uniacid',\Yunshop::app()->uniacid);
  450. // })->where('has_option',1)->select('yz_goods.*');
  451. // $query->join('yz_goods_spec','yz_goods.id','yz_goods_spec.goods_id')->select('yz_goods.*','yz_goods_spec.goods_id');
  452. } else {
  453. $query->where('has_option', 0)->select('yz_goods.*');
  454. }
  455. }
  456. break;
  457. case 'is_hide':
  458. if ($value) {
  459. $query->where('is_hide', $value);
  460. }
  461. break;
  462. case 'source_id':
  463. if ($value) {
  464. $query->join('yz_goods_source_goods', 'yz_goods_source_goods.goods_id', 'yz_goods.id')
  465. ->where('yz_goods_source_goods.source_id', $value);
  466. }
  467. break;
  468. default:
  469. break;
  470. }
  471. }
  472. }
  473. public function scopeSearchList($query, $filters)
  474. {
  475. $query->uniacid();
  476. if (!$filters) {
  477. return;
  478. }
  479. foreach ($filters as $key => $value) {
  480. switch ($key) {
  481. //上架商品库存筛选
  482. case 'sell_stock':
  483. if ($value) {
  484. $query->where('yz_goods.status', 1)->where('yz_goods.stock', '>', 0);
  485. } else {
  486. $query->where('yz_goods.status', 1)->where('yz_goods.stock', '=', 0);
  487. }
  488. break;
  489. //新加过滤搜索
  490. case 'filtering':
  491. $scope = explode(',', rtrim($value, ','));
  492. if ($scope) {
  493. $goodsFiltering = GoodsFiltering::select('goods_id')->whereIn('filtering_id', $scope)->get();
  494. $goods_ids = $goodsFiltering->pluck('goods_id')->unique()->toArray();
  495. if ($goods_ids) {
  496. $query->whereIn('yz_goods.id', $goods_ids);
  497. } else {
  498. $query->where('yz_goods.id', 0);//标签下没有商品,条件为id=0令其搜索不到
  499. }
  500. }
  501. break;
  502. case 'price_range':
  503. //价格区间搜索
  504. $price_range = explode(',', $value);
  505. if (empty($price_range[0]) && !empty($price_range[1])) {
  506. $query->where('yz_goods.price', '<=', $price_range[1]);
  507. } elseif(!empty($price_range[0]) && empty($price_range[1])) {
  508. $query->where('yz_goods.price', '>=', $price_range[0]);
  509. } else {
  510. $query->whereBetween('yz_goods.price', $price_range);
  511. }
  512. break;
  513. case 'keyword':
  514. $splice_word = Analysis::getKeywords($value, 10);
  515. $ims = DB::getConfig('prefix');//获取前缀
  516. if (empty($splice_word)) {
  517. $splice_search = $ims . 'yz_goods.title like "%' . $value . '%"';
  518. } else {
  519. $splice_search = '';
  520. $splice_array = explode(',', $splice_word);
  521. foreach ($splice_array as $val) {
  522. $splice_search .= $ims . 'yz_goods.title like "%' . $val . '%" and ';
  523. }
  524. $splice_search = '(' . rtrim($splice_search, 'and ') . ')';
  525. }
  526. // 商品标签
  527. if (\app\common\facades\Setting::get('goods.goods-tag-set')['is_search_show']) {
  528. if (empty($splice_word)) {
  529. $filter_ids = SearchFiltering::uniacid()->where('name', 'like', "%{$value}%")->get()->pluck('id')->toArray();
  530. // 有可能标签组不显示
  531. $filter_ids = SearchFiltering::getAllEnableFiltering()->whereIn('id',$filter_ids)->pluck('id')->toArray();
  532. } else {
  533. $keywords = explode(',', $splice_word);
  534. $label_search = '';
  535. foreach ($keywords as $val) {
  536. $label_search .= $ims . 'yz_search_filtering.name like "%' . $val . '%" and ';
  537. }
  538. $filter_ids = SearchFiltering::uniacid()->whereRaw('(' . rtrim($label_search, 'and ') . ')')->get()->pluck('id')->toArray();
  539. // 有可能标签组不显示
  540. $filter_ids = SearchFiltering::getAllEnableFiltering()->whereIn('id',$filter_ids)->pluck('id')->toArray();
  541. }
  542. if (!empty($filter_ids)) {
  543. $goods_ids = GoodsFiltering::whereIn('filtering_id', $filter_ids)->get()->pluck('goods_id')->toArray();
  544. if (!empty($goods_ids)) {
  545. $goods_ids = implode(',', $goods_ids);
  546. $splice_search = '(' . $splice_search . ' or (' . DB::getTablePrefix() . 'yz_goods.`id` in (' . $goods_ids . '))' . ')';
  547. }
  548. }
  549. }
  550. $query->whereRaw('(' . $splice_search . ' or ' . DB::getTablePrefix() . 'yz_goods.`id` = ?)', [$value]);
  551. break;
  552. case 'goods_id':
  553. $query->where('yz_goods.id', '=', $value);
  554. break;
  555. case 'brand_id':
  556. $query->where('brand_id', $value);
  557. break;
  558. case 'product_attr':
  559. //前端传参是 string 类型,后端传参是 array 类型
  560. if (!is_array($value)) {
  561. $value = explode(',', rtrim($value, ','));
  562. }
  563. foreach ($value as $attr) {
  564. if ($attr == 'limit_buy') {
  565. $query->join('yz_goods_limitbuy', function ($join) {
  566. $join->on('yz_goods_limitbuy.goods_id', '=', 'yz_goods.id')->where('yz_goods_limitbuy.status', 1);
  567. });
  568. } else {
  569. $query->where($attr, 1);
  570. }
  571. }
  572. break;
  573. case 'status':
  574. $query->where('yz_goods.status', $value);
  575. break;
  576. case 'min_price':
  577. $query->where('price', '>', $value);
  578. break;
  579. case 'max_price':
  580. $query->where('price', '<', $value);
  581. break;
  582. case 'category':
  583. if (array_key_exists('parentid', $value) || array_key_exists('childid', $value) || array_key_exists('thirdid', $value)) {
  584. $id = $value['parentid'] ? $value['parentid'] : '';
  585. $id = $value['childid'] ? $value['childid'] : $id;
  586. $id = $value['thirdid'] ? $value['thirdid'] : $id;
  587. $query->select(['yz_goods.id', 'yz_goods.title', 'yz_goods.thumb', 'yz_goods.real_sales', 'yz_goods.virtual_sales',
  588. 'yz_goods.market_price', 'yz_goods.price', 'yz_goods.cost_price', 'yz_goods.stock',
  589. 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id',
  590. 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids'
  591. ])->join('yz_goods_category', 'yz_goods_category.goods_id', '=', 'yz_goods.id')
  592. ->whereRaw('FIND_IN_SET(?,category_ids)', [$id])
  593. ->groupBy('yz_goods.id');
  594. } elseif (strpos($value, ',')) {
  595. $scope = explode(',', $value);
  596. $query->select(['yz_goods.id', 'yz_goods.title', 'yz_goods.thumb', 'yz_goods.real_sales', 'yz_goods.virtual_sales',
  597. 'yz_goods.market_price', 'yz_goods.price', 'yz_goods.cost_price', 'yz_goods.stock',
  598. 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id',
  599. 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids']
  600. )->join('yz_goods_category', function ($join) use ($scope) {
  601. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id');
  602. $join->where(function ($join) use ($scope) {
  603. foreach ($scope as $s) {
  604. $join->orWhereRaw('FIND_IN_SET(?,category_ids)', [$s]);
  605. }
  606. });
  607. })->groupBy('yz_goods.id');
  608. } else {
  609. $query->select(['yz_goods.id', 'yz_goods.title', 'yz_goods.thumb', 'yz_goods.real_sales', 'yz_goods.virtual_sales',
  610. 'yz_goods.market_price', 'yz_goods.price', 'yz_goods.cost_price', 'yz_goods.stock',
  611. 'yz_goods_category.id as goods_category_id', 'yz_goods_category.goods_id as goods_id',
  612. 'yz_goods_category.category_id as category_id', 'yz_goods_category.category_ids as category_ids'
  613. ])->join('yz_goods_category', function ($join) use ($value) {
  614. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->whereRaw('FIND_IN_SET(?,category_ids)', [$value]);
  615. })->groupBy('yz_goods.id');
  616. }
  617. break;
  618. case 'couponid': //搜索指定优惠券适用的商品
  619. $res = Coupon::getApplicableScope($value);
  620. switch ($res['type']) {
  621. case Coupon::COUPON_GOODS_USE: //优惠券适用于指定商品
  622. if (is_array($res['scope'])) {
  623. $query->whereIn('id', $res['scope']);
  624. } else {
  625. $query->where('id', $res['scope']);
  626. }
  627. break;
  628. case 8:
  629. if (is_array($res['scope'])) {
  630. $query->whereIn('id', $res['scope']);
  631. } else {
  632. $query->where('id', $res['scope']);
  633. }
  634. break;
  635. case Coupon::COUPON_CATEGORY_USE: //优惠券适用于指定商品分类
  636. if (is_array($res['scope'])) {
  637. $query->join('yz_goods_category', function ($join) use ($res) {
  638. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->whereIn('yz_goods_category.category_id', $res['scope']);
  639. });
  640. } else {
  641. $query->join('yz_goods_category', function ($join) use ($res) {
  642. $join->on('yz_goods_category.goods_id', '=', 'yz_goods.id')->where('yz_goods_category.category_id', $res['scope']);
  643. });
  644. }
  645. break;
  646. default: //优惠券适用于整个商城
  647. break;
  648. }
  649. break;
  650. case 'is_spec':
  651. if ($value !== '') {
  652. if ($value == 1) {
  653. $query->where('has_option', 1)->select('yz_goods.*');
  654. } else {
  655. $query->where('has_option', 0)->select('yz_goods.*');
  656. }
  657. }
  658. break;
  659. case 'plugin_id':
  660. if (!is_array($value)) {
  661. if ($value == -1) {
  662. $value = 0;
  663. }
  664. $function = 'where';
  665. } else {
  666. if (($search_key = array_search(-1, $value)) !== false) {
  667. $value[$search_key] = 0;
  668. }
  669. $function = 'whereIn';
  670. }
  671. if ($value || $value === 0 || $value === '0') {
  672. $query->$function('plugin_id', $value);
  673. }
  674. break;
  675. case 'is_hide':
  676. if ($value) {
  677. $query->where('is_hide', $value);
  678. }
  679. break;
  680. default:
  681. break;
  682. }
  683. }
  684. }
  685. /**
  686. * @param $keyword
  687. * @return mixed
  688. */
  689. public static function getGoodsByName($keyword)
  690. {
  691. return static::uniacid()->select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')->where('title', 'like', '%' . $keyword . '%')->where('status', 1)//->where('is_plugin', 0)
  692. ->whereNotIn('plugin_id', [20, 31, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  693. ->get();
  694. }
  695. public static function getGoodsLevelByName($keyword)
  696. {
  697. return static::uniacid()->select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')->where('title', 'like', '%' . $keyword . '%')->where('status', 1)//->where('is_plugin', 0)
  698. // ->whereIn('plugin_id', ['0', '32', '92'])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  699. ->get();
  700. }
  701. public static function getGoodsByNameLevel($keyword)
  702. {
  703. $where = function ($query) use ($keyword) {
  704. if (!empty($keyword) && intval($keyword) == $keyword) {
  705. return $query->where('title', 'like', '%' . $keyword . '%')->orWhere('id', $keyword);
  706. } else {
  707. return $query->where('title', 'like', '%' . $keyword . '%');
  708. }
  709. };
  710. return \app\common\models\Goods::select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')
  711. ->where($where)
  712. // ->where('title', 'like', '%' . $keyword . '%')
  713. ->where('status', 1)
  714. ->whereNotIn('plugin_id', [20, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  715. ->get();
  716. }
  717. /**
  718. * @param $keyword
  719. * @return mixed
  720. */
  721. public static function getGoodsByNames($keyword)
  722. {
  723. return static::uniacid()->select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'virtual_sales', 'sku', 'plugin_id', 'stock')->where('title', 'like', '%' . $keyword . '%')->where('status', 1)//->where('is_plugin', 0)
  724. ->whereNotIn('plugin_id', [20, 31, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  725. ->get();
  726. }
  727. /**
  728. * @param $keyword
  729. * @return mixed
  730. */
  731. public static function getGoodsByNameForLimitBuy($keyword)
  732. {
  733. return static::uniacid()->select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')->where('title', 'like', '%' . $keyword . '%')->where('status', 1)->with(['hasOneGoodsLimitBuy' => function ($query) {
  734. return $query->where('status', 1)->select('goods_id', 'start_time', 'end_time');
  735. }])->whereHas('hasOneGoodsLimitBuy', function ($query) {
  736. return $query->where('status', 1);
  737. })->whereNotIn('plugin_id', [20, 31, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  738. ->get();
  739. }
  740. /**
  741. * @param $goodsId
  742. * @return mixed
  743. */
  744. public static function updatedComment($goodsId)
  745. {
  746. return self::where('id', $goodsId)->update(['comment_num' => DB::raw('`comment_num` + 1')]);
  747. }
  748. /**
  749. * 判断实物
  750. * @return bool
  751. * @author shenyang
  752. */
  753. public function isRealGoods()
  754. {
  755. if (!isset($this->type)) {
  756. return false;
  757. }
  758. return $this->type == self::REAL_GOODS;
  759. }
  760. /**
  761. * 推广商品
  762. * @param $goodsIds
  763. * @return array
  764. */
  765. public static function getPushGoods($goodsIds)
  766. {
  767. return self::select('id', 'title', 'thumb', 'price', 'market_price','has_option')->whereIn('id', $goodsIds)->where('status', 1)->get()->toArray();
  768. }
  769. public static function boot()
  770. {
  771. parent::boot();
  772. static::addGlobalScope(function ($builder) {
  773. $builder->uniacid();
  774. });
  775. static::observe(new \app\common\modules\goods\GoodsObserverBase);
  776. }
  777. public static function getGoodsByIdAll($goodsId)
  778. {
  779. $model = static::where('id', $goodsId);
  780. return $model;
  781. }
  782. public function getStatusNameAttribute()
  783. {
  784. return [0 => '下架', 1 => '上架'][$this->status];
  785. }
  786. /**
  787. * 商品购买验证
  788. * @param Member $member
  789. * @param $total
  790. * @throws AppException
  791. */
  792. public function generalValidate(Member $member, $total)
  793. {
  794. if (empty($this->status)) {
  795. throw new AppException('(ID:' . $this->id . ')商品已下架');
  796. }
  797. // if (!isset($this->hasOneSale)) {
  798. // throw new AppException('(ID:' . $this->id . ')商品优惠信息数据已损坏');
  799. // }
  800. // if (!isset($this->hasOneGoodsDispatch)) {
  801. // throw new AppException('(ID:' . $this->id . ')商品配送信息数据已损坏');
  802. // }
  803. //添加了一个按商品规格校验的,所以不能根据商品判断
  804. // if (isset($this->hasOnePrivilege)) {
  805. // $this->hasOnePrivilege->validate($member, $total);
  806. // }
  807. if (isset($this->hasOneGoodsLimitBuy)) {
  808. $this->hasOneGoodsLimitBuy->check();
  809. }
  810. }
  811. /**
  812. * 是否启用规格
  813. * @param $option_id
  814. * @throws AppException
  815. */
  816. public function verifyOption($option_id)
  817. {
  818. if ($this->has_option && empty($option_id)) {
  819. throw new AppException($this->title . '(ID:' . $this->id . ')商品未选择规格');
  820. }
  821. }
  822. /**
  823. * 获取商品名称
  824. * @return html
  825. */
  826. public static function getSearchOrder($keyword, $pluginId)
  827. {
  828. // $keyword = \YunShop::request()->keyword;
  829. return Goods::select(['id', 'title', 'thumb', 'plugin_id'])->pluginId($pluginId)->where('title', 'like', '%' . $keyword . '%')->get();
  830. }
  831. private $priceManager;
  832. public function getPriceManager()
  833. {
  834. if (!isset($this->priceManager)) {
  835. $this->priceManager = new GoodsPriceManager($this);
  836. }
  837. return $this->priceManager;
  838. }
  839. /**
  840. * 获取交易价(实际参与交易的商品价格)
  841. * @return float|int
  842. * @throws \app\common\exceptions\MemberNotLoginException
  843. */
  844. public function getDealPriceAttribute()
  845. {
  846. if (!isset($this->dealPrice)) {
  847. // $level_discount_set = SiteSettingFacades::get('discount.all_set');
  848. // if (
  849. // isset($level_discount_set['type'])
  850. // && $level_discount_set['type'] == 1
  851. // && $this->memberLevelDiscount()->getAmount($this->market_price)
  852. // ) {
  853. // // 如果开启了原价计算会员折扣,并且存在等级优惠金额
  854. // $this->dealPrice = $this->market_price;
  855. // } else {
  856. // // 默认使用现价
  857. // $this->dealPrice = $this->price;
  858. // }
  859. $this->dealPrice = $this->getPriceManager()->getDealPrice();
  860. }
  861. return $this->dealPrice;
  862. }
  863. /**
  864. * @var GoodsMemberLevelDiscount
  865. */
  866. private $memberLevelDiscount;
  867. /**
  868. * @return GoodsMemberLevelDiscount
  869. * @throws AppException
  870. */
  871. public function memberLevelDiscount()
  872. {
  873. if (!isset($this->memberLevelDiscount)) {
  874. if (\YunShop::app()->getMemberId()) {
  875. $member = \app\frontend\models\Member::current();
  876. } else {
  877. $member = new \app\frontend\models\Member();
  878. }
  879. $this->memberLevelDiscount = new GoodsMemberLevelDiscount($this, $member);
  880. }
  881. return $this->memberLevelDiscount;
  882. }
  883. //todo blank 商品价格适配器
  884. public function getGoodsPriceAdapter()
  885. {
  886. return new GoodsPriceAdapter($this);
  887. }
  888. /**
  889. * 缓存等级折金额
  890. * @param $price
  891. * @return float
  892. * @throws AppException
  893. */
  894. public function getVipDiscountAmount($price)
  895. {
  896. if (isset($this->vipDiscountAmount)) {
  897. return $this->vipDiscountAmount;
  898. }
  899. $this->vipDiscountAmount = $this->memberLevelDiscount()->getAmount($price);
  900. $this->vipDiscountLog = $this->memberLevelDiscount()->getLog($this->vipDiscountAmount);
  901. return $this->vipDiscountAmount;
  902. }
  903. /**
  904. * 获取商品的会员价格
  905. * @return float|mixed
  906. * @throws AppException
  907. */
  908. public function getVipPriceAttribute()
  909. {
  910. //todo 涉及优惠走舍去非四舍五入
  911. return sprintf("%.2f",substr(sprintf("%.3f", $this->deal_price - $this->getVipDiscountAmount($this->getGoodsPriceAdapter())), 0, -1));
  912. // return sprintf('%.2f', $this->deal_price - $this->getVipDiscountAmount($this->getGoodsPriceAdapter()));
  913. }
  914. /**
  915. * 获取下一等级的会员价
  916. * @return int|string
  917. * @throws AppException
  918. */
  919. public function getNextLevelPriceAttribute()
  920. {
  921. if (\YunShop::app()->getMemberId()) {
  922. $member = \app\frontend\models\Member::current();
  923. } else {
  924. $member = new \app\frontend\models\Member();
  925. }
  926. $level_id = $member->yzMember->level_id;
  927. if (empty($level_id)) {
  928. $nextLevel = MemberLevel::getFirstLevel();
  929. $this->nextLevelName = $nextLevel->level_name;
  930. } else {
  931. $level = MemberLevel::getMemberLevel($level_id);
  932. $nextLevel = MemberLevel::getNextMemberLevel($level);
  933. $this->nextLevelName = $nextLevel->level_name;
  934. }
  935. $priceClass = $this->getGoodsPriceAdapter();
  936. /**
  937. * @param \app\common\models\MemberLevel $nextLevel
  938. * @param \app\common\models\GoodsDiscount $goods
  939. */
  940. if ($nextLevel) {
  941. $goods = $this->hasManyGoodsDiscount->where('level_id', $nextLevel->id)->first();
  942. if (!$goods) {
  943. /**
  944. * @param \app\common\models\MemberLevel $nextLevel
  945. */
  946. $price = $nextLevel->getDiscountCalculation($priceClass);
  947. return sprintf('%.2f', $this->deal_price - $price);
  948. // $nextLevel->discount = trim($nextLevel->discount);
  949. // $nextLevel->discount = $nextLevel->discount == false ? 10 : $nextLevel->discount;
  950. // $price = (1 - $nextLevel->discount / 10) * $this->deal_price;
  951. // return sprintf('%.2f', $this->deal_price - $price);
  952. }
  953. return sprintf('%.2f', $this->deal_price - $goods->getNextAmount($priceClass, $nextLevel));
  954. } else {
  955. $goods = $this->hasManyGoodsDiscount->where('level_id', $level->id)->first();
  956. if (!$goods) {
  957. if (is_null($level)) {
  958. return $this->deal_price;
  959. }
  960. $price = $level->getDiscountCalculation($priceClass);
  961. return sprintf('%.2f', $this->deal_price - $price);
  962. // $level->discount = trim($level->discount);
  963. // $level->discount = $level->discount == false ? 10 : $level->discount;
  964. // $price = (1 - $level->discount / 10) * $this->deal_price;
  965. // return sprintf('%.2f', $this->deal_price - $price);
  966. }
  967. return sprintf('%.2f', $this->deal_price - $goods->getAmount($priceClass, $member));
  968. }
  969. }
  970. public function getAllLevelPriceAttribute()
  971. {
  972. if (\YunShop::app()->getMemberId()) {
  973. $member = \app\frontend\models\Member::current();
  974. } else {
  975. $member = new \app\frontend\models\Member();
  976. }
  977. $level_id = $member->yzMember->level_id;
  978. $all_level_price = [];
  979. $priceClass = $this->getGoodsPriceAdapter();
  980. // if (!$level_id) {
  981. // $nextLevel = MemberLevel::getFirstLevel();
  982. // if ($nextLevel) {
  983. // $goods = $this->hasManyGoodsDiscount->where('level_id', $nextLevel->id)->first();
  984. // if (!$goods) {
  985. // /**
  986. // * @param \app\common\models\MemberLevel $nextLevel
  987. // */
  988. // $price = $nextLevel->getDiscountCalculation($priceClass);
  989. // $deal_price = sprintf('%.2f', $this->deal_price - $price);
  990. // } else {
  991. // $deal_price = sprintf('%.2f', $this->deal_price - $goods->getNextAmount($priceClass, $nextLevel));
  992. // }
  993. // } else {
  994. // $deal_price = $this->deal_price;
  995. // }
  996. // $all_level_price[] = [
  997. // 'level_name' => $nextLevel->level_name,
  998. // 'level_id' => $nextLevel->id,
  999. // 'level' => $nextLevel->level,
  1000. // 'price' => $deal_price,
  1001. // ];
  1002. // } else {
  1003. $member_levels = MemberLevel::uniacid()->groupBy('level')->orderBy('level', 'asc')->get();
  1004. if ($member_levels->isEmpty()) {
  1005. $default_level = \Setting::get('shop.member.level_name');
  1006. $level_name = $default_level ?: '普通会员';
  1007. $all_level_price[] = [
  1008. 'level_name' => $level_name,
  1009. 'level_id' => 0,
  1010. 'level' => 0,
  1011. 'price' => $this->deal_price,
  1012. 'is_select' => true,
  1013. ];
  1014. return $all_level_price;
  1015. }
  1016. $is_check_next = true;
  1017. $level_count = $member_levels->count();
  1018. $i = 0;
  1019. $can_upgrade = false;
  1020. foreach ($member_levels as $level) {
  1021. $goods = $this->hasManyGoodsDiscount->where('level_id', $level->id)->first();
  1022. if (!$goods) {
  1023. $price = $level->getDiscountCalculation($priceClass);
  1024. $deal_price = sprintf('%.2f', $this->deal_price - $price);
  1025. } else {
  1026. $deal_price = sprintf('%.2f', $this->deal_price - $goods->getNextAmount($priceClass, $level));
  1027. }
  1028. $level_data = [
  1029. 'level_name' => $level->level_name,
  1030. 'level_id' => $level->id,
  1031. 'level' => $level->level,
  1032. 'price' => $deal_price,
  1033. 'is_select' => false,
  1034. 'is_next' => false,
  1035. 'is_last' => false,
  1036. ];
  1037. if ($level_id == $level->id) {
  1038. $level_data['is_select'] = true;
  1039. }
  1040. if ($level_id < $level->id && $is_check_next) {
  1041. $level_data['is_next'] = true;
  1042. $is_check_next = false;
  1043. $can_upgrade = true;
  1044. }
  1045. $i++;
  1046. if ($level_count == $i && $level->id == $level_id) {
  1047. $level_data['is_last'] = true;
  1048. }
  1049. array_push($all_level_price, $level_data);
  1050. }
  1051. // }
  1052. return [$all_level_price, $can_upgrade];
  1053. }
  1054. public function getVipNextPriceAttribute()
  1055. {
  1056. return 0;
  1057. }
  1058. public function getPriceLevelAttribute()
  1059. {
  1060. if (app('plugins')->isEnabled('member-price')) {
  1061. $set = \Setting::get('plugin.member-price');
  1062. if ($set['is_open_micro']) {
  1063. return $set['price_level'];
  1064. }
  1065. }
  1066. return 1;
  1067. }
  1068. public function getIsOpenMicroAttribute()
  1069. {
  1070. if (app('plugins')->isEnabled('member-price')) {
  1071. $set = \Setting::get('plugin.member-price');
  1072. return $set['is_open_micro'];
  1073. }
  1074. return 2;
  1075. }
  1076. public function getNextLevelNameAttribute()
  1077. {
  1078. if (isset($this->nextLevelName)) {
  1079. return $this->nextLevelName;
  1080. }
  1081. return '';
  1082. }
  1083. public function dispatchTypeSetting()
  1084. {
  1085. if ($this->hasOneGoodsDispatch) {
  1086. return $this->hasOneGoodsDispatch->dispatchTypesSetting();
  1087. }
  1088. return [];
  1089. }
  1090. public function goodsDispatchTypeIds()
  1091. {
  1092. if ($this->hasOneGoodsDispatch) {
  1093. return $this->hasOneGoodsDispatch->getEnableDispatchTypeIds();
  1094. //return $this->hasOneGoodsDispatch->getDispatchTypeIds();
  1095. }
  1096. return [];
  1097. }
  1098. private $goodsStock;
  1099. public function goodsStock()
  1100. {
  1101. if (!isset($this->goodsStock)) {
  1102. $this->goodsStock = new GoodsStock($this);
  1103. }
  1104. return $this->goodsStock;
  1105. }
  1106. public function save($options = [])
  1107. {
  1108. if ($this->attributes['reduce_stock_method'] != $this->original['reduce_stock_method']) {
  1109. if ($this->withhold_stock > 0) {
  1110. throw new AppException('存在预扣库存时,无法修改减库存方式设置。');
  1111. }
  1112. }
  1113. // 提交的库存是扣除预扣的,保存的时候必须将预扣的数量加回来
  1114. if (isset($this->attributes['stock']) && $this->attributes['stock'] != $this->original['stock']) {
  1115. $this->attributes['stock'] = $this->attributes['stock'] + $this->withhold_stock;
  1116. }
  1117. $result = parent::save($options);
  1118. return $result;
  1119. }
  1120. public function getStockAttribute()
  1121. {
  1122. return $this->goodsStock()->usableStock();
  1123. }
  1124. public function getWithholdStockAttribute()
  1125. {
  1126. return $this->goodsStock()->withholdStock();
  1127. }
  1128. /**
  1129. * 库存是否充足
  1130. * @param $num
  1131. * @return bool
  1132. * @author shenyang
  1133. */
  1134. public function stockEnough($num)
  1135. {
  1136. if ($this->reduce_stock_method == 2) {
  1137. return true;
  1138. }
  1139. return $this->goodsStock()->enough($num);
  1140. }
  1141. /**
  1142. * 增加销量
  1143. * @param $num
  1144. * @author shenyang
  1145. */
  1146. public function addSales($num)
  1147. {
  1148. $this->increment('real_sales', $num);
  1149. $this->increment('show_sales', $num);
  1150. }
  1151. public function fireStockNotEnoughtEvent($goods)
  1152. {
  1153. event(new GoodsStockNotEnoughEvent($goods));
  1154. }
  1155. public static function getGoodsByNameLevelNew($keyword)
  1156. {
  1157. $page_size = 15;
  1158. $where = function ($query) use ($keyword) {
  1159. if (!empty($keyword) && intval($keyword) == $keyword) {
  1160. return $query->where('title', 'like', '%' . $keyword . '%')->orWhere('id', $keyword);
  1161. } else {
  1162. return $query->where('title', 'like', '%' . $keyword . '%');
  1163. }
  1164. };
  1165. return \app\common\models\Goods::select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')
  1166. ->where($where)
  1167. ->where('status', 1)
  1168. ->whereNotIn('plugin_id', [20, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  1169. ->paginate($page_size);
  1170. }
  1171. public static function getGoodsByNameNew($keyword)
  1172. {
  1173. $page_size = 15;
  1174. return static::uniacid()->select('id', 'title', 'thumb', 'market_price', 'price', 'real_sales', 'sku', 'plugin_id', 'stock')->where('title', 'like', '%' . $keyword . '%')->where('status', 1)//->where('is_plugin', 0)
  1175. ->whereNotIn('plugin_id', [20, 31, 60])//屏蔽门店、码上点餐、第三方插件接口的虚拟商品
  1176. ->paginate($page_size);
  1177. }
  1178. public function hasOneInvoiceGoods()
  1179. {
  1180. return $this->hasOne(InvoiceRelation::class, 'goods_id', 'id');
  1181. }
  1182. /**
  1183. * 获取商品的最低显示价格
  1184. * @return int|mixed
  1185. */
  1186. public function getMinPriceAttribute()
  1187. {
  1188. if ($this->has_option && $this->hasManyOptions->isNotEmpty()) {
  1189. return $this->hasManyOptions->min('product_price');
  1190. }
  1191. return $this->price;
  1192. }
  1193. /**
  1194. * 获取商品的最高显示价格
  1195. * @return int|mixed
  1196. */
  1197. public function getMaxPriceAttribute()
  1198. {
  1199. if ($this->has_option && $this->hasManyOptions->isNotEmpty()) {
  1200. return $this->hasManyOptions->max('product_price');
  1201. }
  1202. return $this->price;
  1203. }
  1204. public function getVipLevelStatusAttribute()
  1205. {
  1206. $vip_status = [
  1207. 'status' => 0,
  1208. 'word' => '',
  1209. 'tips' => ''
  1210. ];
  1211. if (!app('plugins')->isEnabled('price-authority')) {
  1212. return $vip_status;
  1213. }
  1214. //查询会员等级
  1215. $level = MemberShopInfo::select('level_id')->where('member_id',\YunShop::app()->getMemberId())->first();
  1216. $set = \Setting::get('plugin.price_authority');
  1217. if (!empty($set['is_jurisdiction']) && $set['is_jurisdiction']){
  1218. $goods = \Yunshop\PriceAuthority\model\Goods::find($this->id);
  1219. if (($goods->plugin_id == 0 || $goods->plugin_id == 92)) {
  1220. if ($set['supplier_vip_level'] == '' || empty($set['supplier_vip_level'])){
  1221. $vip_status = [
  1222. 'status' => 0,
  1223. 'word' => '',
  1224. 'tips' => ''
  1225. ];
  1226. }else if (!in_array($level->level_id, $set['supplier_vip_level'])) {
  1227. $level_name = '';
  1228. foreach ($set['supplier_vip_level'] as $item) {
  1229. $level = MemberLevel::find($item);
  1230. if (!$level) {
  1231. $level->level_name = '普通会员';
  1232. }
  1233. $level_name .= '/' . $level->level_name;
  1234. }
  1235. $vip_status['status'] = 1;
  1236. $vip_status['word'] = $set['supplier_jurisdiction_word'] ?: '无权限';
  1237. $vip_status['tips'] = '该商品仅限' . $level_name . '等级购买';
  1238. }
  1239. }
  1240. if (($goods->plugin_id == 31 || $goods->plugin_id == 32)){
  1241. if ($set['store_vip_level'] == ''){
  1242. $vip_status = [
  1243. 'status' => 0,
  1244. 'word' => '',
  1245. 'tips' => ''
  1246. ];
  1247. }else if (!in_array($level->level_id, $set['store_vip_level'])){
  1248. $level_name = '';
  1249. foreach ($set['store_vip_level'] as $item){
  1250. $level = MemberLevel::find($item);
  1251. if (!$level){
  1252. $level->level_name = '普通会员';
  1253. }
  1254. $level_name .= '/'.$level->level_name ;
  1255. }
  1256. $vip_status['status'] = 1;
  1257. $vip_status['word'] = $set['store_jurisdiction_word'] ?: '无权限';
  1258. $vip_status['tips'] = '该商品仅限'.$level_name.'等级购买';
  1259. }
  1260. }
  1261. }
  1262. return ($vip_status);
  1263. }
  1264. }