GoodsLogic.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. foreach($goods_cate as &$v){
  161. $cate_arr = [];
  162. array_push($cate_arr,$v['id']);
  163. $second = GoodsCategory::where(['is_show'=>1,'pid'=>$v['id']])->field('id,name')->order('sort asc')->select()->toArray();
  164. $second_arr = array_column($second,'id');
  165. $cate_arr = array_merge($cate_arr,$second_arr);
  166. foreach($second as $sv){
  167. $three = GoodsCategory::where(['is_show'=>1,'pid'=>$sv['id']])->field('id,name')->order('sort asc')->select()->toArray();
  168. $three_arr= array_column($three,'id');
  169. $cate_arr = array_merge($cate_arr,$three_arr);
  170. }
  171. $good_id_list = GoodsCategoryIndex::where(['category_id'=>$cate_arr])->select()->toArray();
  172. $goods_list=[];
  173. if($good_id_list){
  174. $goods_id_arr = array_column($good_id_list,'goods_id');
  175. $goods_list = Goods::where(['id'=>$goods_id_arr,'status'=>1])->field('id,name,min_price,min_lineation_price,image')->limit(4)->select()->toArray();
  176. }
  177. $v['goods_list'] = $goods_list;
  178. }
  179. return ['goods_cate'=>$goods_cate];
  180. }
  181. /**
  182. * @notes 商品搜索记录
  183. * @param $userId
  184. * @param $limit
  185. * @return array
  186. * @author cjhao
  187. * @date 2021/8/11 17:12
  188. */
  189. public function searchRecord($userId,$limit){
  190. //读取缓存
  191. $HandleConcurrencyCache = new HandleConcurrencyCache();
  192. $recordList = $HandleConcurrencyCache->getCache($HandleConcurrencyCache->getGoodsSearchRecordKey($userId));
  193. if ($recordList !== false) {
  194. return $recordList;
  195. }
  196. $recordList = SearchRecord::where(['user_id'=>$userId])
  197. ->limit($limit)
  198. ->order('id desc')
  199. ->column('keyword');
  200. //设置缓存
  201. $HandleConcurrencyCache->setCache($HandleConcurrencyCache->getGoodsSearchRecordKey($userId),$recordList,3600);
  202. return $recordList;
  203. }
  204. /**
  205. * @notes 商品营销接口
  206. * @param int $goodsId
  207. * @param int $userId
  208. * @return array
  209. * @author cjhao
  210. * @date 2021/8/27 17:27
  211. */
  212. public function goodsMarketing(int $goodsId,int $userId):array
  213. {
  214. $coupon = CouponLogic::goodsCoupon($goodsId,$userId);
  215. $activityList = GoodsActivityLogic::activityInfo($goodsId)[$goodsId] ?? [];
  216. $marketing = [
  217. 'coupon' => $coupon,
  218. 'activity' => array_values($activityList),
  219. ];
  220. return $marketing;
  221. }
  222. /**
  223. * @notes 清空搜索记录
  224. * @param int $userId
  225. * @author cjhao
  226. * @date 2021/9/15 11:35
  227. */
  228. public function clearRecord(int $userId)
  229. {
  230. SearchRecord::where(['user_id'=>$userId])->delete();
  231. }
  232. /**
  233. * @notes 商品浏览记录
  234. * @param $goodsId
  235. * @param $userId
  236. * @return bool
  237. * @author Tab
  238. * @date 2021/9/15 14:04
  239. */
  240. public function visit($goodsId, $userId)
  241. {
  242. if (empty($userId)) {
  243. $userId = 0;
  244. }
  245. $ip = request()->ip();
  246. // 一个ip一个商品一个用户一天只生成一条记录
  247. $record = GoodsVisit::where([
  248. 'ip' => $ip,
  249. 'goods_id' => $goodsId,
  250. 'user_id' => $userId,
  251. ])->whereDay('create_time')->findOrEmpty();
  252. if (!$record->isEmpty()) {
  253. // 增加浏览量
  254. $record->visit += 1;
  255. $record->save();
  256. return true;
  257. }
  258. // 生成商品浏览记录
  259. GoodsVisit::create([
  260. 'ip' => $ip,
  261. 'goods_id' => $goodsId,
  262. 'user_id' => $userId,
  263. 'visit' => 1
  264. ]);
  265. }
  266. /**
  267. * @notes 获取最近的商品评价
  268. * @param $id
  269. * @param int $limit
  270. * @author cjhao
  271. * @date 2021/11/17 17:44
  272. */
  273. public static function getComment($id,$limit = 1){
  274. //商品评论
  275. $goodsComment = GoodsComment::with(['goods_comment_image','user'])
  276. ->where(['goods_id'=>$id,'status'=>GoodsCommentEnum::APPROVED])
  277. ->field('id,user_id,spec_value_str,comment,virtual')
  278. ->order('id desc')
  279. ->limit($limit)
  280. ->findOrEmpty();
  281. if(!$goodsComment->isEmpty()){
  282. $commentCount = GoodsComment::where(['goods_id'=>$id,'status'=>GoodsCommentEnum::APPROVED])->count();
  283. $goodsCommentCount = GoodsComment::where([['goods_id','=',$id],['goods_comment','>',3],['status', '=', GoodsCommentEnum::APPROVED]])->count();
  284. $goodsRate = $commentCount > 0 ? round(($goodsCommentCount/$commentCount)*100).'%' : '100%';
  285. $goodsComment->goods_rate = $goodsRate;
  286. $goodsComment->comment_image = array_column($goodsComment->goods_comment_image->toArray(),'uri');
  287. $goodsComment->hidden(['user_id','goods_comment_image']);
  288. if (!is_null($goodsComment->virtual)) {
  289. // 虚拟评价
  290. $vitual = json_decode($goodsComment->virtual, true);
  291. $goodsComment->nickname = $vitual['nickname'];
  292. $goodsComment->avatar = FileService::getFileUrl($vitual['avatar']);
  293. }
  294. //隐藏用户昵称
  295. $goodsComment->nickname = hide_substr($goodsComment->nickname);
  296. if(empty($goodsComment->comment)){
  297. $goodsComment->comment = '此用户没有填写评论';
  298. }
  299. }
  300. return $goodsComment->toArray();
  301. }
  302. /**
  303. * 计算最高可得预估佣金
  304. */
  305. public static function getDistribution($goodsId, $userId)
  306. {
  307. $earnings = 0;
  308. $ratio = 0;
  309. $rule = 0;
  310. $goods = Goods::findOrEmpty($goodsId)->toArray();
  311. // 用户分销等级
  312. $distribution_level_id = Distribution::where('user_id', $userId)->where('is_distribution', 1)->value('level_id', 0);
  313. $distribution_level = DistributionLevel::where('id', $distribution_level_id)->findOrEmpty()->toArray();
  314. // 分销等级
  315. $default_level = DistributionLevel::where('is_default', 1)->findOrEmpty()->toArray();
  316. $level = $distribution_level ? : $default_level;
  317. // 分销商品
  318. $distributionGoods = DistributionGoods::where('goods_id', $goodsId)->where('is_distribution', 1)->select()->toArray();
  319. $rule = $distributionGoods[0]['rule'] ?? $rule;
  320. // 按分销等级比例分佣
  321. if ($rule == 1) {
  322. $ratio = $level['first_ratio'] ?? 0;
  323. $earnings = bcdiv(($goods['max_price'] ?? 0) * $ratio , 100, 2);
  324. }
  325. // 单独设置分佣比例
  326. if ($rule == 2) {
  327. foreach ($distributionGoods as $distributionGood) {
  328. if ($distributionGood['level_id'] == $level['id']) {
  329. $ratio = $distributionGood['first_ratio'] ?? 0;
  330. $earnings = bcdiv(($goods['max_price'] ?? 0) * $ratio , 100, 2);
  331. break;
  332. }
  333. }
  334. }
  335. $dbConfig = DistributionConfig::column('value', 'key');
  336. // 分销总开关
  337. $switch = empty($dbConfig['switch']) ? 0 : 1;
  338. // 商品详情页是否显示佣金 0-不显示 1-显示
  339. if (!isset($dbConfig['is_show_earnings'])) {
  340. $isShowEarnings = 1;
  341. } else if(empty((int)$dbConfig['is_show_earnings'])) {
  342. $isShowEarnings = 0;
  343. } else {
  344. $isShowEarnings = 1;
  345. }
  346. // 详情页佣金可见用户 0-全部用户 1-分销商
  347. if (!isset($dbConfig['show_earnings_scope'])) {
  348. $showEarningsScope = 0;
  349. } else if(empty((int)$dbConfig['show_earnings_scope'])) {
  350. $showEarningsScope = 0;
  351. } else {
  352. $showEarningsScope = 1;
  353. }
  354. if (!$switch || empty($distributionGoods)) {
  355. $isShowEarnings = 0;
  356. }
  357. if ($isShowEarnings) {
  358. $user = Distribution::where(['user_id' => $userId])->findOrEmpty()->toArray();
  359. if ($showEarningsScope && empty($user['is_distribution'])) {
  360. $isShowEarnings = 0;
  361. }
  362. }
  363. return [
  364. 'is_show' => $isShowEarnings,
  365. 'earnings' => $earnings,
  366. 'ratio' => $ratio,
  367. 'rule' => $rule,
  368. ];
  369. }
  370. /**
  371. * @notes 自定义海报获取商品信息
  372. */
  373. public static function getGoodsByTypeId($type, $activityId, $goodsId, $userId) {
  374. // type 1普通通商品 2秒杀 3拼团 4砍价 5预售
  375. switch($type) {
  376. case 1:
  377. return Goods::field('name, image, min_lineation_price, min_price')->where('id', $goodsId)->findOrEmpty()->toArray();
  378. case 2:
  379. $data = SeckillLogic::detail([
  380. 'id' => $activityId,
  381. 'user_id' => $userId,
  382. ]);
  383. if (!is_array($data)) {
  384. return [];
  385. }
  386. return [
  387. 'name' => $data['name'],
  388. 'image' => $data['image'],
  389. 'min_lineation_price' => $data['min_price'],
  390. 'min_price' => $data['activity']['min_seckill_price'],
  391. ];
  392. case 3:
  393. $data = TeamLogic::detail($activityId, $userId);
  394. if (!is_array($data)) {
  395. return [];
  396. }
  397. return [
  398. 'name' => $data['name'],
  399. 'image' => $data['image'],
  400. 'min_lineation_price' => $data['min_price'],
  401. 'min_price' => $data['activity']['min_team_price'],
  402. ];
  403. case 4:
  404. $data = BargainLogic::detail([
  405. 'activity_id' => $activityId,
  406. 'goods_id' => $goodsId,
  407. ]);
  408. if (!is_array($data)) {
  409. return [];
  410. }
  411. return [
  412. 'name' => $data['goods_name'],
  413. 'image' => $data['image'],
  414. 'min_lineation_price' => $data['goods_max_price'],
  415. 'min_price' => $data['min_price'],
  416. ];
  417. case 5:
  418. $data = PresellGoods::where(['id'=>$goodsId])->findOrEmpty()->toArray();
  419. if (empty($data)) {
  420. return [];
  421. }
  422. $goods = Goods::where(['id'=>$data['goods_id']])->field('name,image')->findOrEmpty()->toArray();
  423. return [
  424. 'name' => $goods['name'],
  425. 'image' => $goods['image'],
  426. 'min_lineation_price' => '',
  427. 'min_price' => $data['min_price'],
  428. ];
  429. default:
  430. return [];
  431. }
  432. }
  433. public static function getFreeShippingTips($userId, $goods)
  434. {
  435. $expressTips = '';
  436. $activityTips = '';
  437. $address = $goods['address'] ?? [];
  438. // 用户未登录
  439. if (empty($userId) || empty($address['id'])) {
  440. return '免运费';
  441. }
  442. // 包邮活动
  443. $activity = FreeShipping::where([
  444. ['start_time', '<=', time()],
  445. ['end_time', '>', time()],
  446. ['status', '=', 1]
  447. ])->findOrEmpty()->toArray();
  448. if ($activity) {
  449. foreach($activity['region'] as $item) {
  450. if ($item->region_id == "100000") {
  451. // 全国区域
  452. if ($activity['condition_type'] == 1) {
  453. $activityTips = '订单满' . $item->threshold . '元包邮';
  454. } else {
  455. $activityTips = '订单满' . $item->threshold . '件包邮';
  456. }
  457. continue;
  458. }
  459. // 未设置地址
  460. if(empty($address)) {
  461. continue;
  462. }
  463. if (
  464. str_contains($item->region_id, $address['district_id'])
  465. ||
  466. str_contains($item->region_id, $address['city_id'])
  467. ||
  468. str_contains($item->region_id, $address['province_id'])
  469. ) {
  470. if ($activity['condition_type'] == 1) {
  471. $activityTips = '订单满' . $item->threshold . '元包邮';
  472. } else {
  473. $activityTips = '订单满' . (int)$item->threshold . '件包邮';
  474. }
  475. break;
  476. }
  477. }
  478. }
  479. switch ($goods['express_type']) {
  480. // 包邮
  481. case 1:
  482. $expressTips = '免运费';
  483. $activityTips = '';
  484. break;
  485. // 统一运费
  486. case 2:
  487. if ($goods['express_money'] > 0) {
  488. $expressTips = "¥{$goods['express_money']}";
  489. } else {
  490. $expressTips = '免运费';
  491. $activityTips = '';
  492. }
  493. break;
  494. // 运费模板
  495. case 3:
  496. $express = FreightLogic::calculateFreight([
  497. [
  498. 'weight' => $goods['spec_value_list'][0]['weight'] ?? 0,
  499. 'volume' => $goods['spec_value_list'][0]['volume'] ?? 0,
  500. 'goods_num' => 1,
  501. 'id' => $goods['id'],
  502. 'express_type' => $goods['express_type'],
  503. 'express_money' => $goods['express_money'],
  504. 'express_template_id' => $goods['express_template_id'],
  505. ]
  506. ], $address);
  507. $express_money = $express['express_price'] ?? 0;
  508. if ($express_money > 0) {
  509. $expressTips = "¥{$express_money}";
  510. } else {
  511. $expressTips = '免运费';
  512. $activityTips = '';
  513. }
  514. break;
  515. default:
  516. $expressTips = '免邮';
  517. $activityTips = '';
  518. break;
  519. }
  520. return "{$expressTips} {$activityTips}";
  521. }
  522. static function checkCanBuy($item_id, $num) : bool|string
  523. {
  524. $item = GoodsItem::findOrEmpty($item_id);
  525. $goods = Goods::findOrEmpty($item['goods_id'] ?? 0);
  526. if (empty($goods['id'])) {
  527. return '找不到商品';
  528. }
  529. if ($goods['status'] == 0) {
  530. return '商品不能购买';
  531. }
  532. if ($item['stock'] < $num) {
  533. return '商品库存不足';
  534. }
  535. return true;
  536. }
  537. }