StoreSeckillServices.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\activity;
  13. use app\Request;
  14. use app\services\BaseServices;
  15. use app\dao\activity\StoreSeckillDao;
  16. use app\services\order\StoreOrderServices;
  17. use app\services\other\QrcodeServices;
  18. use app\services\product\product\StoreCategoryServices;
  19. use app\services\product\product\StoreDescriptionServices;
  20. use app\services\product\product\StoreProductRelationServices;
  21. use app\services\product\product\StoreProductReplyServices;
  22. use app\services\product\product\StoreProductServices;
  23. use app\services\product\product\StoreVisitServices;
  24. use app\services\product\sku\StoreProductAttrResultServices;
  25. use app\services\product\sku\StoreProductAttrServices;
  26. use app\services\product\sku\StoreProductAttrValueServices;
  27. use app\services\system\config\SystemGroupDataServices;
  28. use crmeb\exceptions\AdminException;
  29. use app\jobs\ProductLogJob;
  30. use crmeb\services\CacheService;
  31. use crmeb\utils\Arr;
  32. use think\exception\ValidateException;
  33. /**
  34. *
  35. * Class StoreSeckillServices
  36. * @package app\services\activity
  37. * @method getSeckillIdsArray(array $ids, array $field)
  38. * @method get(int $id, array $field) 获取一条数据
  39. */
  40. class StoreSeckillServices extends BaseServices
  41. {
  42. /**
  43. * StoreSeckillServices constructor.
  44. * @param StoreSeckillDao $dao
  45. */
  46. public function __construct(StoreSeckillDao $dao)
  47. {
  48. $this->dao = $dao;
  49. }
  50. public function getCount(array $where)
  51. {
  52. $this->dao->count($where);
  53. }
  54. /**
  55. * 秒杀是否存在
  56. * @param int $id
  57. * @return int
  58. */
  59. public function getSeckillCount(int $id = 0)
  60. {
  61. $where = [];
  62. $where[] = ['is_del', '=', 0];
  63. $where[] = ['status', '=', 1];
  64. if ($id) {
  65. $time = time();
  66. $where[] = ['id', '=', $id];
  67. $where[] = ['start_time', '<=', $time];
  68. $where[] = ['stop_time', '>=', $time - 86400];
  69. $seckill_one = $this->dao->getOne($where, 'time_id');
  70. if (!$seckill_one) {
  71. throw new ValidateException('活动已结束');
  72. }
  73. /** @var SystemGroupDataServices $systemGroupDataService */
  74. $systemGroupDataService = app()->make(SystemGroupDataServices::class);
  75. $seckillTime = array_column($systemGroupDataService->getConfigNameValue('routine_seckill_time'), null, 'id');
  76. $config = $seckillTime[$seckill_one['time_id']] ?? false;
  77. if (!$config) {
  78. throw new ValidateException('活动已结束');
  79. }
  80. $now_hour = date('H', time());
  81. $start_hour = $config['time'];
  82. $end_hour = (int)$start_hour + (int)$config['continued'];
  83. if ($start_hour <= $now_hour && $end_hour > $now_hour) {
  84. return true;
  85. } else if ($start_hour > $now_hour) {
  86. throw new ValidateException('活动未开始');
  87. } else {
  88. throw new ValidateException('活动已结束');
  89. }
  90. } else {
  91. $seckillTime = sys_data('routine_seckill_time') ?: [];//秒杀时间段
  92. $timeInfo = ['time' => 0, 'continued' => 0];
  93. foreach ($seckillTime as $key => $value) {
  94. $currentHour = date('H');
  95. $activityEndHour = (int)$value['time'] + (int)$value['continued'];
  96. if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour && $activityEndHour <= 24) {
  97. $timeInfo = $value;
  98. break;
  99. }
  100. }
  101. if ($timeInfo['time'] == 0) return 0;
  102. $activityEndHour = $timeInfo['time'] + (int)$timeInfo['continued'];
  103. $startTime = strtotime(date('Y-m-d')) + (int)$timeInfo['time'] * 3600;
  104. $stopTime = strtotime(date('Y-m-d')) + (int)$activityEndHour * 3600;
  105. $where[] = ['start_time', '<', $startTime];
  106. $where[] = ['stop_time', '>', $stopTime];
  107. return $this->dao->getCount($where);
  108. }
  109. }
  110. /**
  111. * 保存数据
  112. * @param int $id
  113. * @param array $data
  114. */
  115. public function saveData(int $id, array $data)
  116. {
  117. $description = $data['description'];
  118. $detail = $data['attrs'];
  119. $items = $data['items'];
  120. $data['start_time'] = strtotime($data['section_time'][0]);
  121. $data['stop_time'] = strtotime($data['section_time'][1]);
  122. $data['images'] = json_encode($data['images']);
  123. $data['price'] = min(array_column($detail, 'price'));
  124. $data['ot_price'] = min(array_column($detail, 'ot_price'));
  125. $data['quota'] = $data['quota_show'] = array_sum(array_column($detail, 'quota'));
  126. $data['stock'] = array_sum(array_column($detail, 'stock'));
  127. unset($data['section_time'], $data['description'], $data['attrs'], $data['items']);
  128. /** @var StoreDescriptionServices $storeDescriptionServices */
  129. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  130. /** @var StoreProductAttrServices $storeProductAttrServices */
  131. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  132. /** @var StoreProductServices $storeProductServices */
  133. $storeProductServices = app()->make(StoreProductServices::class);
  134. if ($data['quota'] > $storeProductServices->value(['id' => $data['product_id']], 'stock')) {
  135. throw new ValidateException('限量不能超过商品库存');
  136. }
  137. $this->transaction(function () use ($id, $data, $description, $detail, $items, $storeDescriptionServices, $storeProductAttrServices, $storeProductServices) {
  138. if ($id) {
  139. $res = $this->dao->update($id, $data);
  140. $storeDescriptionServices->saveDescription((int)$id, $description, 1);
  141. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$id, 1);
  142. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$id, 1);
  143. if (!$res) throw new AdminException('修改失败');
  144. } else {
  145. if (!$storeProductServices->getOne(['is_show' => 1, 'is_del' => 0, 'id' => $data['product_id']])) {
  146. throw new AdminException('原商品已下架或移入回收站');
  147. }
  148. $data['add_time'] = time();
  149. $res = $this->dao->save($data);
  150. $storeDescriptionServices->saveDescription((int)$res->id, $description, 1);
  151. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$res->id, 1);
  152. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$res->id, 1);
  153. if (!$res) throw new AdminException('添加失败');
  154. }
  155. $res = true;
  156. foreach ($valueGroup->toArray() as $item) {
  157. $res = $res && $this->pushSeckillStock($item['unique'], 1, (int)$item['quota_show']);
  158. }
  159. if (!$res) {
  160. throw new AdminException('占用库存失败');
  161. }
  162. });
  163. }
  164. /**
  165. * 获取列表
  166. * @param array $where
  167. * @return array
  168. * @throws \think\db\exception\DataNotFoundException
  169. * @throws \think\db\exception\DbException
  170. * @throws \think\db\exception\ModelNotFoundException
  171. */
  172. public function systemPage(array $where)
  173. {
  174. [$page, $limit] = $this->getPageValue();
  175. $list = $this->dao->getList($where, $page, $limit);
  176. $count = $this->dao->count($where + ['is_del' => 0]);
  177. foreach ($list as &$item) {
  178. $item['store_name'] = $item['title'];
  179. if ($item['status']) {
  180. if ($item['start_time'] > time())
  181. $item['start_name'] = '未开始';
  182. else if (bcadd($item['stop_time'], '86400') < time())
  183. $item['start_name'] = '已结束';
  184. else if (bcadd($item['stop_time'], '86400') > time() && $item['start_time'] < time()) {
  185. $item['start_name'] = '进行中';
  186. }
  187. } else $item['start_name'] = '已结束';
  188. $end_time = $item['stop_time'] ? date('Y/m/d', (int)$item['stop_time']) : '';
  189. $item['_stop_time'] = $end_time;
  190. $item['stop_status'] = $item['stop_time'] + 86400 < time() ? 1 : 0;
  191. }
  192. return compact('list', 'count');
  193. }
  194. /**
  195. * 后台页面设计获取商品列表
  196. * @param $where
  197. * @return array
  198. * @throws \think\db\exception\DataNotFoundException
  199. * @throws \think\db\exception\DbException
  200. * @throws \think\db\exception\ModelNotFoundException
  201. */
  202. public function getDiySeckillList($where){
  203. unset($where['is_show']);
  204. $where['storeProductId'] = true;
  205. $where['status'] = 1;
  206. [$page, $limit] = $this->getPageValue();
  207. $list = $this->dao->getList($where, $page, $limit);
  208. $count = $this->dao->getCount($where);
  209. $cateIds = implode(',', array_column($list, 'cate_id'));
  210. /** @var StoreCategoryServices $storeCategoryServices */
  211. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  212. $cateList = $storeCategoryServices->getCateArray($cateIds);
  213. foreach ($list as &$item){
  214. $cateName = '';
  215. $item['cate_name'] = '';
  216. if($item['cate_id']){
  217. $cateName = array_filter($cateList, function ($val) use ($item) {
  218. if (in_array($val['id'], explode(',', $item['cate_id']))) {
  219. return $val;
  220. }
  221. });
  222. $item['cate_name'] = implode(',', array_column($cateName, 'cate_name'));
  223. }
  224. $item['store_name'] = $item['title'];
  225. $item['price'] = floatval($item['price']);
  226. $item['is_product_type'] = 3;
  227. }
  228. return compact('count', 'list');
  229. }
  230. /**
  231. * 首页秒杀数据
  232. * @param $where
  233. * @return array|int
  234. * @throws \think\db\exception\DataNotFoundException
  235. * @throws \think\db\exception\DbException
  236. * @throws \think\db\exception\ModelNotFoundException
  237. */
  238. public function getHomeSeckillList($where){
  239. $data=[];
  240. $seckillTime = sys_data('routine_seckill_time') ?: [];//秒杀时间段
  241. $today = strtotime(date('Y-m-d'));
  242. $timeInfo = ['time' => 0, 'continued' => 0];
  243. foreach ($seckillTime as $key => $value) {
  244. $currentHour = date('H');
  245. $activityEndHour = (int)$value['time'] + (int)$value['continued'];
  246. if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour && $activityEndHour <= 24) {
  247. $timeInfo = $value;
  248. break;
  249. }
  250. }
  251. if ($timeInfo['time'] == 0) return [];
  252. $data['time'] = $timeInfo['time'].':00';
  253. $activityEndHour = bcadd($timeInfo['time'] , $timeInfo['continued'],0);
  254. $data['stop'] =(int)bcadd((string)$today, bcmul($activityEndHour, '3600', 0));
  255. $where['time_id'] = $timeInfo['id'];
  256. [$page, $limit] = $this->getPageValue();
  257. $data['list'] = $this->dao->getHomeList($where,$page,$limit);
  258. foreach ($data['list'] as &$item){
  259. $item['price'] = floatval($item['price']);
  260. }
  261. return $data;
  262. }
  263. /**
  264. * 获取秒杀详情
  265. * @param int $id
  266. * @return array|\think\Model|null
  267. */
  268. public function getInfo(int $id)
  269. {
  270. $info = $this->dao->get($id);
  271. if ($info) {
  272. if ($info['start_time'])
  273. $start_time = date('Y-m-d', (int)$info['start_time']);
  274. if ($info['stop_time'])
  275. $stop_time = date('Y-m-d', (int)$info['stop_time']);
  276. if (isset($start_time) && isset($stop_time))
  277. $info['section_time'] = [$start_time, $stop_time];
  278. else
  279. $info['section_time'] = [];
  280. unset($info['start_time'], $info['stop_time']);
  281. $info['give_integral'] = intval($info['give_integral']);
  282. $info['price'] = floatval($info['price']);
  283. $info['ot_price'] = floatval($info['ot_price']);
  284. $info['postage'] = floatval($info['postage']);
  285. $info['cost'] = floatval($info['cost']);
  286. $info['weight'] = floatval($info['weight']);
  287. $info['volume'] = floatval($info['volume']);
  288. /** @var StoreDescriptionServices $storeDescriptionServices */
  289. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  290. $info['description'] = $storeDescriptionServices->getDescription(['product_id' => $id, 'type' => 1]);
  291. $info['attrs'] = $this->attrList($id, $info['product_id']);
  292. }
  293. return $info;
  294. }
  295. /**
  296. * 获取规格
  297. * @param int $id
  298. * @param int $pid
  299. * @return mixed
  300. */
  301. public function attrList(int $id, int $pid)
  302. {
  303. /** @var StoreProductAttrResultServices $storeProductAttrResultServices */
  304. $storeProductAttrResultServices = app()->make(StoreProductAttrResultServices::class);
  305. $seckillResult = $storeProductAttrResultServices->value(['product_id' => $id, 'type' => 1], 'result');
  306. $items = json_decode($seckillResult, true)['attr'];
  307. $productAttr = $this->getAttr($items, $pid, 0);
  308. $seckillAttr = $this->getAttr($items, $id, 1);
  309. foreach ($productAttr as $pk => $pv) {
  310. foreach ($seckillAttr as &$sv) {
  311. if ($pv['detail'] == $sv['detail']) {
  312. $productAttr[$pk] = $sv;
  313. }
  314. }
  315. $productAttr[$pk]['detail'] = json_decode($productAttr[$pk]['detail']);
  316. }
  317. $attrs['items'] = $items;
  318. $attrs['value'] = $productAttr;
  319. foreach ($items as $key => $item) {
  320. $header[] = ['title' => $item['value'], 'key' => 'value' . ($key + 1), 'align' => 'center', 'minWidth' => 80];
  321. }
  322. $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 120];
  323. $header[] = ['title' => '秒杀价', 'key' => 'price', 'type' => 1, 'align' => 'center', 'minWidth' => 80];
  324. $header[] = ['title' => '成本价', 'key' => 'cost', 'align' => 'center', 'minWidth' => 80];
  325. $header[] = ['title' => '原价', 'key' => 'ot_price', 'align' => 'center', 'minWidth' => 80];
  326. $header[] = ['title' => '库存', 'key' => 'stock', 'align' => 'center', 'minWidth' => 80];
  327. $header[] = ['title' => '限量', 'key' => 'quota', 'type' => 1, 'align' => 'center', 'minWidth' => 80];
  328. $header[] = ['title' => '重量(KG)', 'key' => 'weight', 'align' => 'center', 'minWidth' => 80];
  329. $header[] = ['title' => '体积(m³)', 'key' => 'volume', 'align' => 'center', 'minWidth' => 80];
  330. $header[] = ['title' => '商品编号', 'key' => 'bar_code', 'align' => 'center', 'minWidth' => 80];
  331. $attrs['header'] = $header;
  332. return $attrs;
  333. }
  334. /**
  335. * 获取规格
  336. * @param $attr
  337. * @param $id
  338. * @param $type
  339. * @return array
  340. */
  341. public function getAttr($attr, $id, $type)
  342. {
  343. /** @var StoreProductAttrValueServices $storeProductAttrValueServices */
  344. $storeProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
  345. $value = attr_format($attr)[1];
  346. $valueNew = [];
  347. $count = 0;
  348. foreach ($value as $key => $item) {
  349. $detail = $item['detail'];
  350. // sort($item['detail'], SORT_STRING);
  351. $suk = implode(',', $item['detail']);
  352. $sukValue = $storeProductAttrValueServices->getColumn(['product_id' => $id, 'type' => $type, 'suk' => $suk], 'bar_code,cost,price,ot_price,stock,image as pic,weight,volume,brokerage,brokerage_two,quota', 'suk');
  353. if (count($sukValue)) {
  354. foreach (array_values($detail) as $k => $v) {
  355. $valueNew[$count]['value' . ($k + 1)] = $v;
  356. }
  357. $valueNew[$count]['detail'] = json_encode($detail);
  358. $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
  359. $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
  360. $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
  361. $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
  362. $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
  363. $valueNew[$count]['quota'] = $sukValue[$suk]['quota'] ? intval($sukValue[$suk]['quota']) : 0;
  364. $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
  365. $valueNew[$count]['weight'] = $sukValue[$suk]['weight'] ? floatval($sukValue[$suk]['weight']) : 0;
  366. $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ? floatval($sukValue[$suk]['volume']) : 0;
  367. $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ? floatval($sukValue[$suk]['brokerage']) : 0;
  368. $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ? floatval($sukValue[$suk]['brokerage_two']) : 0;
  369. $valueNew[$count]['_checked'] = $type != 0 ? true : false;
  370. $count++;
  371. }
  372. }
  373. return $valueNew;
  374. }
  375. /**
  376. * 获取某个时间段的秒杀列表
  377. * @param int $time
  378. * @return array
  379. * @throws \think\db\exception\DataNotFoundException
  380. * @throws \think\db\exception\DbException
  381. * @throws \think\db\exception\ModelNotFoundException
  382. */
  383. public function getListByTime(int $time)
  384. {
  385. [$page, $limit] = $this->getPageValue();
  386. $seckillInfo = $this->dao->getListByTime($time, $page, $limit);
  387. if (count($seckillInfo)) {
  388. foreach ($seckillInfo as $key => &$item) {
  389. if ($item['quota'] > 0) {
  390. $percent = (int)(($item['quota_show'] - $item['quota']) / $item['quota_show'] * 100);
  391. $item['percent'] = $percent;
  392. $item['stock'] = $item['quota'];
  393. } else {
  394. $item['percent'] = 100;
  395. $item['stock'] = 0;
  396. }
  397. $item['price'] = floatval($item['price']);
  398. $item['ot_price'] = floatval($item['ot_price']);
  399. }
  400. }
  401. return $seckillInfo;
  402. }
  403. /**
  404. * 获取秒杀详情
  405. * @param Request $request
  406. * @param int $id
  407. * @return mixed
  408. * @throws \think\db\exception\DataNotFoundException
  409. * @throws \think\db\exception\DbException
  410. * @throws \think\db\exception\ModelNotFoundException
  411. */
  412. public function seckillDetail(Request $request, int $id)
  413. {
  414. $uid = (int)$request->uid();
  415. $storeInfo = $this->dao->getOne(['id' => $id], '*', ['description']);
  416. if (!$storeInfo) {
  417. throw new ValidateException('商品不存在');
  418. } else {
  419. $storeInfo = $storeInfo->toArray();
  420. }
  421. $siteUrl = sys_config('site_url');
  422. $storeInfo['image'] = set_file_url($storeInfo['image'], $siteUrl);
  423. $storeInfo['image_base'] = set_file_url($storeInfo['image'], $siteUrl);
  424. /** @var StoreProductServices $storeProductService */
  425. $storeProductService = app()->make(StoreProductServices::class);
  426. $productInfo = $storeProductService->get($storeInfo['product_id']);
  427. $storeInfo['total'] = $productInfo['sales'] + $productInfo['ficti'];
  428. /** @var QrcodeServices $qrcodeService */
  429. $qrcodeService = app()->make(QrcodeServices::class);
  430. $time = $request->param()['time'] ?? '';
  431. $status = $request->param()['status'] ?? '';
  432. $storeInfo['code_base'] = $qrcodeService->getWechatQrcodePath($id . '_product_seckill_detail_wap.jpg', '/pages/activity/goods_seckill_details/index?id=' . $id . '&time=' . $time . '&status=' . $status);
  433. /** @var StoreOrderServices $storeOrderServices */
  434. $storeOrderServices = app()->make(StoreOrderServices::class);
  435. $data['buy_num'] = $storeOrderServices->getBuyCount($uid, 'seckill_id', $id);
  436. /** @var StoreProductRelationServices $storeProductRelationServices */
  437. $storeProductRelationServices = app()->make(StoreProductRelationServices::class);
  438. $storeInfo['userCollect'] = $storeProductRelationServices->isProductRelation(['uid' => $uid, 'product_id' => $storeInfo['product_id'], 'type' => 'collect', 'category' => 'product']);
  439. $storeInfo['userLike'] = false;
  440. $storeInfo['uid'] = $uid;
  441. if ($storeInfo['quota'] > 0) {
  442. $percent = (int)(($storeInfo['quota_show'] - $storeInfo['quota']) / $storeInfo['quota_show'] * 100);
  443. $storeInfo['percent'] = $percent;
  444. $storeInfo['stock'] = $storeInfo['quota'];
  445. } else {
  446. $storeInfo['percent'] = 100;
  447. $storeInfo['stock'] = 0;
  448. }
  449. //商品详情
  450. $data['storeInfo'] = $storeInfo;
  451. /** @var StoreProductReplyServices $storeProductReplyService */
  452. $storeProductReplyService = app()->make(StoreProductReplyServices::class);
  453. $data['reply'] = $storeProductReplyService->getRecProductReply($storeInfo['product_id']);
  454. [$replyCount, $goodReply, $replyChance] = $storeProductReplyService->getProductReplyData((int)$storeInfo['product_id']);
  455. $data['replyChance'] = $replyChance;
  456. $data['replyCount'] = $replyCount;
  457. /** @var StoreProductAttrServices $storeProductAttrServices */
  458. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  459. list($productAttr, $productValue) = $storeProductAttrServices->getProductAttrDetail($id, $uid, 0, 1, $storeInfo['product_id']);
  460. $data['productAttr'] = $productAttr;
  461. $data['productValue'] = $productValue;
  462. $data['routine_contact_type'] = sys_config('routine_contact_type', 0);
  463. //用户访问事件
  464. event('user.userVisit', [$uid, $id, 'seckill', $storeInfo['product_id'], 'view']);
  465. //浏览记录
  466. ProductLogJob::dispatch(['visit', ['uid' => $uid, 'product_id' => $storeInfo['product_id']]]);
  467. return $data;
  468. }
  469. /**
  470. * 获取秒杀数据
  471. * @param array $ids
  472. * @param string $field
  473. * @return array
  474. * @throws \think\db\exception\DataNotFoundException
  475. * @throws \think\db\exception\DbException
  476. * @throws \think\db\exception\ModelNotFoundException
  477. */
  478. public function getSeckillColumn(array $ids, string $field = '')
  479. {
  480. $seckillProduct = $systemGroupData = [];
  481. $seckillInfoField = 'id,image,price,ot_price,postage,give_integral,sales,stock,title as store_name,unit_name,is_show,is_del,is_postage,cost,temp_id,weight,volume,start_time,stop_time,time_id';
  482. if (!empty($seckill_ids)) {
  483. $seckillProduct = $this->dao->idSeckillList($ids, $field ?: $seckillInfoField);
  484. if (!empty($seckillProduct)) {
  485. $timeIds = Arr::getUniqueKey($seckillProduct, 'time_id');
  486. $seckillProduct = array_combine(array_column($seckillProduct, 'id'), $seckillProduct);
  487. /** @var SystemGroupDataServices $groupServices */
  488. $groupServices = app()->make(SystemGroupDataServices::class);
  489. $systemGroupData = $groupServices->getGroupDataColumn($timeIds);
  490. }
  491. }
  492. return [$seckillProduct, $systemGroupData];
  493. }
  494. /**
  495. * 秒杀库存添加入redis的队列中
  496. * @param string $unique sku唯一值
  497. * @param int $type 类型
  498. * @param int $number 库存个数
  499. * @param bool $isPush 是否放入之前删除当前队列
  500. * @return bool|int
  501. */
  502. public function pushSeckillStock(string $unique, int $type, int $number, bool $isPush = false)
  503. {
  504. $name = 'seckill_' . $unique . '_' . $type;
  505. /** @var CacheService $cache */
  506. $cache = app()->make(CacheService::class);
  507. $res = true;
  508. if (!$isPush) {
  509. $cache->del($name);
  510. }
  511. for ($i = 1; $i <= $number; $i++) {
  512. $res = $res && $cache->lPush($name, $i);
  513. }
  514. return $res;
  515. }
  516. /**
  517. * @param int $productId
  518. * @param string $unique
  519. * @param int $cartNum
  520. * @param string $value
  521. * @return bool
  522. */
  523. public function checkSeckillStock(int $productId, string $unique, int $cartNum = 1, string $value = '')
  524. {
  525. $set_key = md5('seckill_set_attr_stock_' . $productId . '_' . $unique);
  526. $sum = CacheService::zCard($set_key);
  527. $fail = CacheService::zCount($set_key, 0, time());
  528. $sall = ($sum - $fail) < 0 ? 0 : ($sum - $fail);
  529. /** @var StoreProductAttrValueServices $skuValueServices */
  530. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  531. $seckillStock = $skuValueServices->getSeckillAttrStock($productId, $unique);
  532. if (($seckillStock['quota'] - $sall) < $cartNum) {
  533. return false;
  534. }
  535. $StoreSeckillinfo = $this->getValidProduct($productId);
  536. $product_stock = $skuValueServices->getProductAttrStock($StoreSeckillinfo['product_id'], $seckillStock['suk']);
  537. if (($product_stock - $sall) < $cartNum) {
  538. return false;
  539. }
  540. //秒杀成功成员
  541. $sall_member = CacheService::zRangeByScore($set_key, time());
  542. if ($value && $sall_member) {
  543. $i = 0;
  544. for ($i; $i < $cartNum; $i++) {
  545. if (in_array($value . $i, $sall_member)) {
  546. return false;
  547. }
  548. }
  549. }
  550. return true;
  551. }
  552. /**
  553. * 弹出redis队列中的库存条数
  554. * @param string $unique
  555. * @param int $type
  556. * @return mixed
  557. */
  558. public function popSeckillStock(string $unique, int $type, int $number = 1)
  559. {
  560. $name = 'seckill_' . $unique . '_' . $type;
  561. /** @var CacheService $cache */
  562. $cache = app()->make(CacheService::class);
  563. if ($number > $cache->lLen($name)) {
  564. return false;
  565. }
  566. $res = true;
  567. for ($i = 1; $i <= $number; $i++) {
  568. $res = $res && $cache->lPop($name);
  569. }
  570. return $res;
  571. }
  572. /**
  573. * 是否有库存
  574. * @param string $unique
  575. * @param int $type
  576. * @return mixed
  577. * @throws \Psr\SimpleCache\InvalidArgumentException
  578. */
  579. public function isSeckillStock(string $unique, int $type, int $number)
  580. {
  581. /** @var CacheService $cache */
  582. $cache = app()->make(CacheService::class);
  583. return $cache->redisHandler()->lLen('seckill_' . $unique . '_' . $type) >= $number;
  584. }
  585. /**
  586. * 回滚库存
  587. * @param array $cartInfo
  588. * @param int $number
  589. * @return bool
  590. */
  591. public function rollBackStock(array $cartInfo)
  592. {
  593. $res = true;
  594. foreach ($cartInfo as $item) {
  595. $value = $item['cart_info'];
  596. if ($value['seckill_id']) {
  597. $res = $res && $this->pushSeckillStock($value['product_attr_unique'], 1, (int)$value['cart_num'], true);
  598. }
  599. }
  600. return $res;
  601. }
  602. /**
  603. * 占用库存
  604. * @param $cartInfo
  605. */
  606. public function occupySeckillStock($cartInfo, $key, $time = 0)
  607. {
  608. //占用库存
  609. if ($cartInfo) {
  610. if (!$time) {
  611. $time = time() + 600;
  612. }
  613. foreach ($cartInfo as $val) {
  614. if ($val['seckill_id']) {
  615. $this->setSeckillStock($val['product_id'], $val['product_attr_unique'], $time, $key, (int)$val['cart_num']);
  616. }
  617. }
  618. }
  619. return true;
  620. }
  621. /**
  622. * 取消秒杀占用的库存
  623. * @param array $cartInfo
  624. * @param string $key
  625. * @return bool
  626. */
  627. public function cancelOccupySeckillStock(array $cartInfo, string $key)
  628. {
  629. if ($cartInfo) {
  630. foreach ($cartInfo as $val) {
  631. if (isset($val['seckill_id']) && $val['seckill_id']) {
  632. $this->backSeckillStock((int)$val['product_id'], $val['product_attr_unique'], $key, (int)$val['cart_num']);
  633. }
  634. }
  635. }
  636. return true;
  637. }
  638. /**
  639. * 存入当前秒杀商品属性有序集合
  640. * @param $product_id
  641. * @param $unique
  642. * @param $score
  643. * @param $value
  644. * @param int $cart_num
  645. * @return bool
  646. */
  647. public function setSeckillStock($product_id, $unique, $score, $value, $cart_num = 1)
  648. {
  649. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  650. $i = 0;
  651. for ($i; $i < $cart_num; $i++) {
  652. CacheService::zAdd($set_key, $score, $value . $i);
  653. }
  654. return true;
  655. }
  656. /**
  657. * 取消集合中的秒杀商品
  658. * @param int $product_id
  659. * @param string $unique
  660. * @param $value
  661. * @param int $cart_num
  662. * @return bool
  663. */
  664. public function backSeckillStock(int $product_id, string $unique, $value, int $cart_num = 1)
  665. {
  666. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  667. $i = 0;
  668. for ($i; $i < $cart_num; $i++) {
  669. CacheService::zRem($set_key, $value . $i);
  670. }
  671. return true;
  672. }
  673. /**
  674. * 修改秒杀库存
  675. * @param int $num
  676. * @param int $seckillId
  677. * @return bool
  678. */
  679. public function decSeckillStock(int $num, int $seckillId, string $unique = '')
  680. {
  681. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  682. if ($unique) {
  683. /** @var StoreProductAttrValueServices $skuValueServices */
  684. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  685. //减去秒杀商品的sku库存增加销量
  686. $res = false !== $skuValueServices->decProductAttrStock($seckillId, $unique, $num, 1);
  687. //减去秒杀库存
  688. $res = $res && $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  689. //减去当前普通商品sku的库存增加销量
  690. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId], 'suk');
  691. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  692. if ($productUnique) {
  693. $res = $res && $skuValueServices->decProductAttrStock($product_id, $productUnique, $num);
  694. }
  695. } else {
  696. $res = false !== $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  697. }
  698. /** @var StoreProductServices $services */
  699. $services = app()->make(StoreProductServices::class);
  700. //减去普通商品库存
  701. $res = $res && $services->decProductStock($num, $product_id);
  702. if ($res) {
  703. }
  704. return $res;
  705. }
  706. /**
  707. * 加库存减销量
  708. * @param int $num
  709. * @param int $seckillId
  710. * @param string $unique
  711. * @return bool
  712. */
  713. public function incSeckillStock(int $num, int $seckillId, string $unique = '')
  714. {
  715. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  716. if ($unique) {
  717. /** @var StoreProductAttrValueServices $skuValueServices */
  718. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  719. //减去秒杀商品的sku库存增加销量
  720. $res = false !== $skuValueServices->incProductAttrStock($seckillId, $unique, $num, 1);
  721. //减去秒杀库存
  722. $res = $res && $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  723. //减去当前普通商品sku的库存增加销量
  724. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId], 'suk');
  725. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  726. if ($productUnique) {
  727. $res = $res && $skuValueServices->incProductAttrStock($product_id, $productUnique, $num);
  728. }
  729. } else {
  730. $res = false !== $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  731. }
  732. /** @var StoreProductServices $services */
  733. $services = app()->make(StoreProductServices::class);
  734. //减去普通商品库存
  735. $res = $res && $services->incProductStock($num, $product_id);
  736. return $res;
  737. }
  738. /**
  739. * 获取一条秒杀商品
  740. * @param $id
  741. * @param string $field
  742. * @return array|false|\PDOStatement|string|\think\Model
  743. */
  744. public function getValidProduct($id, $field = '*')
  745. {
  746. return $this->dao->validProduct($id, $field);
  747. }
  748. }