GoodsLogic.php 22 KB

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