GoodsLogic.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop100%开源免费商用商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | gitee下载:https://gitee.com/likeshop_gitee
  10. // | github下载:https://github.com/likeshop-github
  11. // | 访问官网:https://www.likeshop.cn
  12. // | 访问社区:https://home.likeshop.cn
  13. // | 访问手册:http://doc.likeshop.cn
  14. // | 微信公众号:likeshop技术社区
  15. // | likeshop团队 版权所有 拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshopTeam
  18. // +----------------------------------------------------------------------
  19. namespace app\shopapi\logic;
  20. use app\shopapi\logic\Order\FreightLogic;
  21. use app\common\{cache\HandleConcurrencyCache,
  22. enum\FootprintEnum,
  23. enum\OrderEnum,
  24. enum\PayEnum,
  25. logic\CommonPresellLogic,
  26. logic\GoodsActivityLogic,
  27. model\Cart,
  28. model\Distribution,
  29. model\DistributionConfig,
  30. model\DistributionGoods,
  31. model\DistributionLevel,
  32. model\FreeShipping,
  33. model\Goods,
  34. logic\BaseLogic,
  35. logic\DiscountLogic,
  36. model\GoodsCategoryIndex,
  37. model\GoodsItem,
  38. model\GoodsServiceGuarantee,
  39. model\GoodsVisit,
  40. model\GoodsCollect,
  41. model\OrderGoods,
  42. model\PresellGoods,
  43. model\SearchRecord,
  44. model\GoodsComment,
  45. enum\GoodsCommentEnum,
  46. model\User,
  47. model\UserAddress,
  48. service\FileService,
  49. model\GoodsCategory};
  50. use app\common\service\ConfigService;
  51. /**
  52. * 商品接口逻辑层
  53. * Class GoodsLogic
  54. * @package app\shopapi\logic
  55. */
  56. class GoodsLogic extends BaseLogic
  57. {
  58. /**
  59. * @notes 商品详情
  60. * @param $id
  61. * @return array|false
  62. * @throws \think\db\exception\DataNotFoundException
  63. * @throws \think\db\exception\DbException
  64. * @throws \think\db\exception\ModelNotFoundException
  65. * @author cjhao
  66. * @date 2021/8/2 19:54
  67. */
  68. public function detail($params)
  69. {
  70. $id = $params['id'];
  71. $userId = $params['user_id'];
  72. outFileLog($params,'goods_detail','params');
  73. $goods = Goods::with(['spec_value.spec_list','spec_value_list'])
  74. ->field('id,name,type,code,image,video,video_cover,total_stock,click_num,virtual_sales_num+sales_num as sales_num,unit_id,spec_type,content,poster,virtual_click_num,express_type,express_money,express_template_id,limit_type,limit_value,status,service_guarantee_ids')
  75. ->append(['goods_image'])
  76. ->find($id);
  77. if(empty($goods)){
  78. self::$error = '商品已下架!';
  79. return false;
  80. }
  81. // 服务保障
  82. $goods->service_guarantee = GoodsServiceGuarantee::getApiList($goods->service_guarantee_ids);
  83. // 判断是否需要统计浏览量
  84. if (isset($params['visit'])) {
  85. //记录点击量
  86. $goods->click_num = $goods->click_num + 1;
  87. $goods->save();
  88. // 浏览量
  89. $this->visit($id, $userId);
  90. }
  91. $stockShow = ConfigService::get('goods_set', 'is_show', 1);
  92. $showPrice = ConfigService::get('goods_set', 'show_price', 1);
  93. $goods->stock_show = true;
  94. if(0 == $stockShow){
  95. $goods->stock_show = false;
  96. }
  97. $goods->buy_num = 0;//已购买数量
  98. $goods->cart_goods_num = 0;
  99. if($userId) {
  100. // 地址
  101. $address_id = input('address_id/d', 0);
  102. $address = $address_id ? UserAddress::getAddressById($userId, $address_id) : UserAddress::getDefaultAddress($userId);
  103. if ($address) {
  104. $goods->address = $address;
  105. }
  106. // 汽泡足迹
  107. event('Footprint', ['type' => FootprintEnum::BROWSE_PRODUCT, 'user_id' => $userId, 'foreign_id'=>$id]);
  108. //是否收藏过
  109. $IsCollect = GoodsCollect::where(['goods_id' => $id, 'user_id' => $userId])->value('id');
  110. $goods->is_collect = $IsCollect ? 1 : 0;
  111. //会员价
  112. $userLevel = User::where(['id' => $userId])
  113. ->field('id,level')
  114. ->with('user_level')
  115. ->findOrEmpty()->toArray();
  116. $goodsDiscountPrice = DiscountLogic::getGoodsDiscount($userId, [$goods->id])[$goods->id] ?? [];
  117. foreach ($goods->spec_value_list as $key => $specValue) {
  118. $specValue['member_price'] = $goodsDiscountPrice[$specValue['id']]['discount_price'] ?? '';
  119. $specValue['member_level'] = [
  120. 'name' => $userLevel['name'] ?? '',
  121. ];
  122. }
  123. $goods->member_price = $goods->spec_value_list[0]->member_price;
  124. $goods->member_level = [
  125. 'name' => $userLevel['name'] ?? '',
  126. ];
  127. //用户下单数量
  128. $goods->buy_num = OrderGoods::alias('og')
  129. ->join('order o', 'o.id = og.order_id')
  130. ->where(['og.goods_id'=>$id,'o.order_status'=>[OrderEnum::STATUS_WAIT_PAY,OrderEnum::STATUS_WAIT_DELIVERY,OrderEnum::STATUS_WAIT_RECEIVE,OrderEnum::STATUS_FINISH],'o.user_id'=>$params['user_id'],'o.order_type'=>[OrderEnum::NORMAL_ORDER,OrderEnum::VIRTUAL_ORDER]])
  131. ->sum('og.goods_num');
  132. //购物车商品数量
  133. $goods->cart_goods_num = Cart::where(['goods_id'=>$id,'user_id'=>$params['user_id']])->sum('goods_num');
  134. }
  135. if(0 == $showPrice){
  136. foreach ($goods->spec_value_list as $key =>$specValue){
  137. $specValue['lineation_price'] = 0;
  138. }
  139. }
  140. $goods->sell_price = $goods->spec_value_list[0]->sell_price;
  141. $goods->lineation_price = $goods->spec_value_list[0]->lineation_price;
  142. $goods->goods_comment = $this->getComment($goods->id);
  143. $goods->goods_comment_count = count($this->getComment($goods->id));
  144. $goods->click_num += $goods->virtual_click_num;
  145. $goods->unit_name = '';
  146. if($goods->unit_id){
  147. $goods->unit_name = $goods->unit->name;
  148. }
  149. $goods->hidden(['unit_id','unit']);
  150. // 预估佣金
  151. $goods->distribution = self::getDistribution($id, $userId);
  152. // 包邮信息
  153. $goods->free_shipping_tips = self::getFreeShippingTips($userId, $goods);
  154. // 预售信息
  155. $goods = CommonPresellLogic::goodsDetailInfo($goods);
  156. return $goods->toArray();
  157. }
  158. public function getshopGoods(){
  159. $goods_cate = GoodsCategory::where(['is_show'=>1,'level'=>1])->field('id,name')->order('sort asc')->select()->toArray();
  160. $shop_goods =[];
  161. foreach($goods_cate as &$v){
  162. $cate_arr = [];
  163. array_push($cate_arr,$v['id']);
  164. $second = GoodsCategory::where(['is_show'=>1,'pid'=>$v['id']])->field('id,name')->order('sort asc')->select()->toArray();
  165. $second_arr = array_column($second,'id');
  166. $cate_arr = array_merge($cate_arr,$second_arr);
  167. foreach($second as $sv){
  168. $three = GoodsCategory::where(['is_show'=>1,'pid'=>$sv['id']])->field('id,name')->order('sort asc')->select()->toArray();
  169. $three_arr= array_column($three,'id');
  170. $cate_arr = array_merge($cate_arr,$three_arr);
  171. }
  172. $good_id_list = GoodsCategoryIndex::where(['category_id'=>$cate_arr])->select()->toArray();
  173. $goods_list=[];
  174. if($good_id_list){
  175. $goods_id_arr = array_column($good_id_list,'goods_id');
  176. $goods_list = Goods::where(['id'=>$goods_id_arr,'status'=>1])->field('id,name,min_price,min_lineation_price,image')->limit(4)->select()->toArray();
  177. $v['goods_list'] = $goods_list;
  178. $shop_goods[] = $v;
  179. }
  180. $v['goods_list'] = $goods_list;
  181. }
  182. return ['goods_cate'=>$shop_goods];
  183. }
  184. /**
  185. * @notes 商品搜索记录
  186. * @param $userId
  187. * @param $limit
  188. * @return array
  189. * @author cjhao
  190. * @date 2021/8/11 17:12
  191. */
  192. public function searchRecord($userId,$limit){
  193. //读取缓存
  194. $HandleConcurrencyCache = new HandleConcurrencyCache();
  195. $recordList = $HandleConcurrencyCache->getCache($HandleConcurrencyCache->getGoodsSearchRecordKey($userId));
  196. if ($recordList !== false) {
  197. return $recordList;
  198. }
  199. $recordList = SearchRecord::where(['user_id'=>$userId])
  200. ->limit($limit)
  201. ->order('id desc')
  202. ->column('keyword');
  203. //设置缓存
  204. $HandleConcurrencyCache->setCache($HandleConcurrencyCache->getGoodsSearchRecordKey($userId),$recordList,3600);
  205. return $recordList;
  206. }
  207. /**
  208. * @notes 商品营销接口
  209. * @param int $goodsId
  210. * @param int $userId
  211. * @return array
  212. * @author cjhao
  213. * @date 2021/8/27 17:27
  214. */
  215. public function goodsMarketing(int $goodsId,int $userId):array
  216. {
  217. $coupon = CouponLogic::goodsCoupon($goodsId,$userId);
  218. $activityList = GoodsActivityLogic::activityInfo($goodsId)[$goodsId] ?? [];
  219. $marketing = [
  220. 'coupon' => $coupon,
  221. 'activity' => array_values($activityList),
  222. ];
  223. return $marketing;
  224. }
  225. /**
  226. * @notes 清空搜索记录
  227. * @param int $userId
  228. * @author cjhao
  229. * @date 2021/9/15 11:35
  230. */
  231. public function clearRecord(int $userId)
  232. {
  233. SearchRecord::where(['user_id'=>$userId])->delete();
  234. }
  235. /**
  236. * @notes 商品浏览记录
  237. * @param $goodsId
  238. * @param $userId
  239. * @return bool
  240. * @author Tab
  241. * @date 2021/9/15 14:04
  242. */
  243. public function visit($goodsId, $userId)
  244. {
  245. if (empty($userId)) {
  246. $userId = 0;
  247. }
  248. $ip = request()->ip();
  249. // 一个ip一个商品一个用户一天只生成一条记录
  250. $record = GoodsVisit::where([
  251. 'ip' => $ip,
  252. 'goods_id' => $goodsId,
  253. 'user_id' => $userId,
  254. ])->whereDay('create_time')->findOrEmpty();
  255. if (!$record->isEmpty()) {
  256. // 增加浏览量
  257. $record->visit += 1;
  258. $record->save();
  259. return true;
  260. }
  261. // 生成商品浏览记录
  262. GoodsVisit::create([
  263. 'ip' => $ip,
  264. 'goods_id' => $goodsId,
  265. 'user_id' => $userId,
  266. 'visit' => 1
  267. ]);
  268. }
  269. /**
  270. * @notes 获取最近的商品评价
  271. * @param $id
  272. * @param int $limit
  273. * @author cjhao
  274. * @date 2021/11/17 17:44
  275. */
  276. public static function getComment($id,$limit = 1){
  277. //商品评论
  278. $goodsComment = GoodsComment::with(['goods_comment_image','user'])
  279. ->where(['goods_id'=>$id,'status'=>GoodsCommentEnum::APPROVED])
  280. ->field('id,user_id,spec_value_str,comment,virtual')
  281. ->order('id desc')
  282. ->limit($limit)
  283. ->findOrEmpty();
  284. if(!$goodsComment->isEmpty()){
  285. $commentCount = GoodsComment::where(['goods_id'=>$id,'status'=>GoodsCommentEnum::APPROVED])->count();
  286. $goodsCommentCount = GoodsComment::where([['goods_id','=',$id],['goods_comment','>',3],['status', '=', GoodsCommentEnum::APPROVED]])->count();
  287. $goodsRate = $commentCount > 0 ? round(($goodsCommentCount/$commentCount)*100).'%' : '100%';
  288. $goodsComment->goods_rate = $goodsRate;
  289. $goodsComment->comment_image = array_column($goodsComment->goods_comment_image->toArray(),'uri');
  290. $goodsComment->hidden(['user_id','goods_comment_image']);
  291. if (!is_null($goodsComment->virtual)) {
  292. // 虚拟评价
  293. $vitual = json_decode($goodsComment->virtual, true);
  294. $goodsComment->nickname = $vitual['nickname'];
  295. $goodsComment->avatar = FileService::getFileUrl($vitual['avatar']);
  296. }
  297. //隐藏用户昵称
  298. $goodsComment->nickname = hide_substr($goodsComment->nickname);
  299. if(empty($goodsComment->comment)){
  300. $goodsComment->comment = '此用户没有填写评论';
  301. }
  302. }
  303. return $goodsComment->toArray();
  304. }
  305. /**
  306. * 计算最高可得预估佣金
  307. */
  308. public static function getDistribution($goodsId, $userId)
  309. {
  310. $earnings = 0;
  311. $ratio = 0;
  312. $rule = 0;
  313. $goods = Goods::findOrEmpty($goodsId)->toArray();
  314. // 用户分销等级
  315. $distribution_level_id = Distribution::where('user_id', $userId)->where('is_distribution', 1)->value('level_id', 0);
  316. $distribution_level = DistributionLevel::where('id', $distribution_level_id)->findOrEmpty()->toArray();
  317. // 分销等级
  318. $default_level = DistributionLevel::where('is_default', 1)->findOrEmpty()->toArray();
  319. $level = $distribution_level ? : $default_level;
  320. // 分销商品
  321. $distributionGoods = DistributionGoods::where('goods_id', $goodsId)->where('is_distribution', 1)->select()->toArray();
  322. $rule = $distributionGoods[0]['rule'] ?? $rule;
  323. // 按分销等级比例分佣
  324. if ($rule == 1) {
  325. $ratio = $level['first_ratio'] ?? 0;
  326. $earnings = bcdiv(($goods['max_price'] ?? 0) * $ratio , 100, 2);
  327. }
  328. // 单独设置分佣比例
  329. if ($rule == 2) {
  330. foreach ($distributionGoods as $distributionGood) {
  331. if ($distributionGood['level_id'] == $level['id']) {
  332. $ratio = $distributionGood['first_ratio'] ?? 0;
  333. $earnings = bcdiv(($goods['max_price'] ?? 0) * $ratio , 100, 2);
  334. break;
  335. }
  336. }
  337. }
  338. $dbConfig = DistributionConfig::column('value', 'key');
  339. // 分销总开关
  340. $switch = empty($dbConfig['switch']) ? 0 : 1;
  341. // 商品详情页是否显示佣金 0-不显示 1-显示
  342. if (!isset($dbConfig['is_show_earnings'])) {
  343. $isShowEarnings = 1;
  344. } else if(empty((int)$dbConfig['is_show_earnings'])) {
  345. $isShowEarnings = 0;
  346. } else {
  347. $isShowEarnings = 1;
  348. }
  349. // 详情页佣金可见用户 0-全部用户 1-分销商
  350. if (!isset($dbConfig['show_earnings_scope'])) {
  351. $showEarningsScope = 0;
  352. } else if(empty((int)$dbConfig['show_earnings_scope'])) {
  353. $showEarningsScope = 0;
  354. } else {
  355. $showEarningsScope = 1;
  356. }
  357. if (!$switch || empty($distributionGoods)) {
  358. $isShowEarnings = 0;
  359. }
  360. if ($isShowEarnings) {
  361. $user = Distribution::where(['user_id' => $userId])->findOrEmpty()->toArray();
  362. if ($showEarningsScope && empty($user['is_distribution'])) {
  363. $isShowEarnings = 0;
  364. }
  365. }
  366. return [
  367. 'is_show' => $isShowEarnings,
  368. 'earnings' => $earnings,
  369. 'ratio' => $ratio,
  370. 'rule' => $rule,
  371. ];
  372. }
  373. /**
  374. * @notes 自定义海报获取商品信息
  375. */
  376. public static function getGoodsByTypeId($type, $activityId, $goodsId, $userId) {
  377. // type 1普通通商品 2秒杀 3拼团 4砍价 5预售
  378. switch($type) {
  379. case 1:
  380. return Goods::field('name, image, min_lineation_price, min_price')->where('id', $goodsId)->findOrEmpty()->toArray();
  381. case 2:
  382. $data = SeckillLogic::detail([
  383. 'id' => $activityId,
  384. 'user_id' => $userId,
  385. ]);
  386. if (!is_array($data)) {
  387. return [];
  388. }
  389. return [
  390. 'name' => $data['name'],
  391. 'image' => $data['image'],
  392. 'min_lineation_price' => $data['min_price'],
  393. 'min_price' => $data['activity']['min_seckill_price'],
  394. ];
  395. case 3:
  396. $data = TeamLogic::detail($activityId, $userId);
  397. if (!is_array($data)) {
  398. return [];
  399. }
  400. return [
  401. 'name' => $data['name'],
  402. 'image' => $data['image'],
  403. 'min_lineation_price' => $data['min_price'],
  404. 'min_price' => $data['activity']['min_team_price'],
  405. ];
  406. case 4:
  407. $data = BargainLogic::detail([
  408. 'activity_id' => $activityId,
  409. 'goods_id' => $goodsId,
  410. ]);
  411. if (!is_array($data)) {
  412. return [];
  413. }
  414. return [
  415. 'name' => $data['goods_name'],
  416. 'image' => $data['image'],
  417. 'min_lineation_price' => $data['goods_max_price'],
  418. 'min_price' => $data['min_price'],
  419. ];
  420. case 5:
  421. $data = PresellGoods::where(['id'=>$goodsId])->findOrEmpty()->toArray();
  422. if (empty($data)) {
  423. return [];
  424. }
  425. $goods = Goods::where(['id'=>$data['goods_id']])->field('name,image')->findOrEmpty()->toArray();
  426. return [
  427. 'name' => $goods['name'],
  428. 'image' => $goods['image'],
  429. 'min_lineation_price' => '',
  430. 'min_price' => $data['min_price'],
  431. ];
  432. default:
  433. return [];
  434. }
  435. }
  436. public static function getFreeShippingTips($userId, $goods)
  437. {
  438. $expressTips = '';
  439. $activityTips = '';
  440. $address = $goods['address'] ?? [];
  441. // 用户未登录
  442. if (empty($userId) || empty($address['id'])) {
  443. return '免运费';
  444. }
  445. // 包邮活动
  446. $activity = FreeShipping::where([
  447. ['start_time', '<=', time()],
  448. ['end_time', '>', time()],
  449. ['status', '=', 1]
  450. ])->findOrEmpty()->toArray();
  451. if ($activity) {
  452. foreach($activity['region'] as $item) {
  453. if ($item->region_id == "100000") {
  454. // 全国区域
  455. if ($activity['condition_type'] == 1) {
  456. $activityTips = '订单满' . $item->threshold . '元包邮';
  457. } else {
  458. $activityTips = '订单满' . $item->threshold . '件包邮';
  459. }
  460. continue;
  461. }
  462. // 未设置地址
  463. if(empty($address)) {
  464. continue;
  465. }
  466. if (
  467. str_contains($item->region_id, $address['district_id'])
  468. ||
  469. str_contains($item->region_id, $address['city_id'])
  470. ||
  471. str_contains($item->region_id, $address['province_id'])
  472. ) {
  473. if ($activity['condition_type'] == 1) {
  474. $activityTips = '订单满' . $item->threshold . '元包邮';
  475. } else {
  476. $activityTips = '订单满' . (int)$item->threshold . '件包邮';
  477. }
  478. break;
  479. }
  480. }
  481. }
  482. switch ($goods['express_type']) {
  483. // 包邮
  484. case 1:
  485. $expressTips = '免运费';
  486. $activityTips = '';
  487. break;
  488. // 统一运费
  489. case 2:
  490. if ($goods['express_money'] > 0) {
  491. $expressTips = "¥{$goods['express_money']}";
  492. } else {
  493. $expressTips = '免运费';
  494. $activityTips = '';
  495. }
  496. break;
  497. // 运费模板
  498. case 3:
  499. $express = FreightLogic::calculateFreight([
  500. [
  501. 'weight' => $goods['spec_value_list'][0]['weight'] ?? 0,
  502. 'volume' => $goods['spec_value_list'][0]['volume'] ?? 0,
  503. 'goods_num' => 1,
  504. 'id' => $goods['id'],
  505. 'express_type' => $goods['express_type'],
  506. 'express_money' => $goods['express_money'],
  507. 'express_template_id' => $goods['express_template_id'],
  508. ]
  509. ], $address);
  510. $express_money = $express['express_price'] ?? 0;
  511. if ($express_money > 0) {
  512. $expressTips = "¥{$express_money}";
  513. } else {
  514. $expressTips = '免运费';
  515. $activityTips = '';
  516. }
  517. break;
  518. default:
  519. $expressTips = '免邮';
  520. $activityTips = '';
  521. break;
  522. }
  523. return "{$expressTips} {$activityTips}";
  524. }
  525. static function checkCanBuy($item_id, $num) : bool|string
  526. {
  527. $item = GoodsItem::findOrEmpty($item_id);
  528. $goods = Goods::findOrEmpty($item['goods_id'] ?? 0);
  529. if (empty($goods['id'])) {
  530. return '找不到商品';
  531. }
  532. if ($goods['status'] == 0) {
  533. return '商品不能购买';
  534. }
  535. if ($item['stock'] < $num) {
  536. return '商品库存不足';
  537. }
  538. return true;
  539. }
  540. }