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