GoodsLogic.php 20 KB

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