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