GoodsLogic.php 20 KB

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