StoreSeckillServices.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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, string $field = 'time_id')
  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, $field);
  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 $seckill_one;
  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 && CacheService::setStock($item['unique'], (int)$item['quota_show'], 1);
  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. {
  204. unset($where['is_show']);
  205. $where['storeProductId'] = true;
  206. $where['status'] = 1;
  207. [$page, $limit] = $this->getPageValue();
  208. $list = $this->dao->getList($where, $page, $limit);
  209. $count = $this->dao->getCount($where);
  210. $cateIds = implode(',', array_column($list, 'cate_id'));
  211. /** @var StoreCategoryServices $storeCategoryServices */
  212. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  213. $cateList = $storeCategoryServices->getCateArray($cateIds);
  214. foreach ($list as &$item) {
  215. $cateName = '';
  216. $item['cate_name'] = '';
  217. if ($item['cate_id']) {
  218. $cateName = array_filter($cateList, function ($val) use ($item) {
  219. if (in_array($val['id'], explode(',', $item['cate_id']))) {
  220. return $val;
  221. }
  222. });
  223. $item['cate_name'] = implode(',', array_column($cateName, 'cate_name'));
  224. }
  225. $item['store_name'] = $item['title'];
  226. $item['price'] = floatval($item['price']);
  227. $item['is_product_type'] = 3;
  228. }
  229. return compact('count', 'list');
  230. }
  231. /**
  232. * 首页秒杀数据
  233. * @param $where
  234. * @return array|int
  235. * @throws \think\db\exception\DataNotFoundException
  236. * @throws \think\db\exception\DbException
  237. * @throws \think\db\exception\ModelNotFoundException
  238. */
  239. public function getHomeSeckillList($where)
  240. {
  241. $data = [];
  242. $seckillTime = sys_data('routine_seckill_time') ?: [];//秒杀时间段
  243. $today = strtotime(date('Y-m-d'));
  244. $timeInfo = ['time' => 0, 'continued' => 0];
  245. foreach ($seckillTime as $key => $value) {
  246. $currentHour = date('H');
  247. $activityEndHour = (int)$value['time'] + (int)$value['continued'];
  248. if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour && $activityEndHour <= 24) {
  249. $timeInfo = $value;
  250. break;
  251. }
  252. }
  253. if ($timeInfo['time'] == 0) return [];
  254. $data['time'] = $timeInfo['time'] . ':00';
  255. $activityEndHour = bcadd($timeInfo['time'], $timeInfo['continued'], 0);
  256. $data['stop'] = (int)bcadd((string)$today, bcmul($activityEndHour, '3600', 0));
  257. $where['time_id'] = $timeInfo['id'];
  258. [$page, $limit] = $this->getPageValue();
  259. $data['list'] = $this->dao->getHomeList($where, $page, $limit);
  260. foreach ($data['list'] as &$item) {
  261. $item['price'] = floatval($item['price']);
  262. }
  263. return $data;
  264. }
  265. /**
  266. * 获取秒杀详情
  267. * @param int $id
  268. * @return array|\think\Model|null
  269. */
  270. public function getInfo(int $id)
  271. {
  272. $info = $this->dao->get($id);
  273. if ($info) {
  274. if ($info['start_time'])
  275. $start_time = date('Y-m-d', (int)$info['start_time']);
  276. if ($info['stop_time'])
  277. $stop_time = date('Y-m-d', (int)$info['stop_time']);
  278. if (isset($start_time) && isset($stop_time))
  279. $info['section_time'] = [$start_time, $stop_time];
  280. else
  281. $info['section_time'] = [];
  282. unset($info['start_time'], $info['stop_time']);
  283. $info['give_integral'] = intval($info['give_integral']);
  284. $info['price'] = floatval($info['price']);
  285. $info['ot_price'] = floatval($info['ot_price']);
  286. $info['postage'] = floatval($info['postage']);
  287. $info['cost'] = floatval($info['cost']);
  288. $info['weight'] = floatval($info['weight']);
  289. $info['volume'] = floatval($info['volume']);
  290. /** @var StoreDescriptionServices $storeDescriptionServices */
  291. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  292. $info['description'] = $storeDescriptionServices->getDescription(['product_id' => $id, 'type' => 1]);
  293. $info['attrs'] = $this->attrList($id, $info['product_id']);
  294. }
  295. return $info;
  296. }
  297. /**
  298. * 获取规格
  299. * @param int $id
  300. * @param int $pid
  301. * @return mixed
  302. */
  303. public function attrList(int $id, int $pid)
  304. {
  305. /** @var StoreProductAttrResultServices $storeProductAttrResultServices */
  306. $storeProductAttrResultServices = app()->make(StoreProductAttrResultServices::class);
  307. $seckillResult = $storeProductAttrResultServices->value(['product_id' => $id, 'type' => 1], 'result');
  308. $items = json_decode($seckillResult, true)['attr'];
  309. $productAttr = $this->getAttr($items, $pid, 0);
  310. $seckillAttr = $this->getAttr($items, $id, 1);
  311. foreach ($productAttr as $pk => $pv) {
  312. foreach ($seckillAttr as &$sv) {
  313. if ($pv['detail'] == $sv['detail']) {
  314. $productAttr[$pk] = $sv;
  315. }
  316. }
  317. $productAttr[$pk]['detail'] = json_decode($productAttr[$pk]['detail']);
  318. }
  319. $attrs['items'] = $items;
  320. $attrs['value'] = $productAttr;
  321. foreach ($items as $key => $item) {
  322. $header[] = ['title' => $item['value'], 'key' => 'value' . ($key + 1), 'align' => 'center', 'minWidth' => 80];
  323. }
  324. $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 120];
  325. $header[] = ['title' => '秒杀价', 'key' => 'price', 'type' => 1, 'align' => 'center', 'minWidth' => 80];
  326. $header[] = ['title' => '成本价', 'key' => 'cost', 'align' => 'center', 'minWidth' => 80];
  327. $header[] = ['title' => '原价', 'key' => 'ot_price', 'align' => 'center', 'minWidth' => 80];
  328. $header[] = ['title' => '库存', 'key' => 'stock', 'align' => 'center', 'minWidth' => 80];
  329. $header[] = ['title' => '限量', 'key' => 'quota', 'type' => 1, 'align' => 'center', 'minWidth' => 80];
  330. $header[] = ['title' => '重量(KG)', 'key' => 'weight', 'align' => 'center', 'minWidth' => 80];
  331. $header[] = ['title' => '体积(m³)', 'key' => 'volume', 'align' => 'center', 'minWidth' => 80];
  332. $header[] = ['title' => '商品编号', 'key' => 'bar_code', 'align' => 'center', 'minWidth' => 80];
  333. $attrs['header'] = $header;
  334. return $attrs;
  335. }
  336. /**
  337. * 获取规格
  338. * @param $attr
  339. * @param $id
  340. * @param $type
  341. * @return array
  342. */
  343. public function getAttr($attr, $id, $type)
  344. {
  345. /** @var StoreProductAttrValueServices $storeProductAttrValueServices */
  346. $storeProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
  347. $value = attr_format($attr)[1];
  348. $valueNew = [];
  349. $count = 0;
  350. foreach ($value as $key => $item) {
  351. $detail = $item['detail'];
  352. // sort($item['detail'], SORT_STRING);
  353. $suk = implode(',', $item['detail']);
  354. $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');
  355. if (count($sukValue)) {
  356. foreach (array_values($detail) as $k => $v) {
  357. $valueNew[$count]['value' . ($k + 1)] = $v;
  358. }
  359. $valueNew[$count]['detail'] = json_encode($detail);
  360. $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
  361. $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
  362. $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
  363. $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
  364. $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
  365. $valueNew[$count]['quota'] = $sukValue[$suk]['quota'] ? intval($sukValue[$suk]['quota']) : 0;
  366. $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
  367. $valueNew[$count]['weight'] = $sukValue[$suk]['weight'] ? floatval($sukValue[$suk]['weight']) : 0;
  368. $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ? floatval($sukValue[$suk]['volume']) : 0;
  369. $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ? floatval($sukValue[$suk]['brokerage']) : 0;
  370. $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ? floatval($sukValue[$suk]['brokerage_two']) : 0;
  371. $valueNew[$count]['_checked'] = $type != 0 ? true : false;
  372. $count++;
  373. }
  374. }
  375. return $valueNew;
  376. }
  377. /**
  378. * 获取某个时间段的秒杀列表
  379. * @param int $time
  380. * @return array
  381. * @throws \think\db\exception\DataNotFoundException
  382. * @throws \think\db\exception\DbException
  383. * @throws \think\db\exception\ModelNotFoundException
  384. */
  385. public function getListByTime(int $time)
  386. {
  387. [$page, $limit] = $this->getPageValue();
  388. $seckillInfo = $this->dao->getListByTime($time, $page, $limit);
  389. if (count($seckillInfo)) {
  390. foreach ($seckillInfo as $key => &$item) {
  391. if ($item['quota'] > 0) {
  392. $percent = (int)(($item['quota_show'] - $item['quota']) / $item['quota_show'] * 100);
  393. $item['percent'] = $percent;
  394. $item['stock'] = $item['quota'];
  395. } else {
  396. $item['percent'] = 100;
  397. $item['stock'] = 0;
  398. }
  399. $item['price'] = floatval($item['price']);
  400. $item['ot_price'] = floatval($item['ot_price']);
  401. }
  402. }
  403. return $seckillInfo;
  404. }
  405. /**
  406. * 获取秒杀详情
  407. * @param Request $request
  408. * @param int $id
  409. * @return mixed
  410. * @throws \think\db\exception\DataNotFoundException
  411. * @throws \think\db\exception\DbException
  412. * @throws \think\db\exception\ModelNotFoundException
  413. */
  414. public function seckillDetail(Request $request, int $id)
  415. {
  416. $uid = (int)$request->uid();
  417. $storeInfo = $this->dao->getOne(['id' => $id], '*', ['description']);
  418. if (!$storeInfo) {
  419. throw new ValidateException('商品不存在');
  420. } else {
  421. $storeInfo = $storeInfo->toArray();
  422. }
  423. $siteUrl = sys_config('site_url');
  424. $storeInfo['image'] = set_file_url($storeInfo['image'], $siteUrl);
  425. $storeInfo['image_base'] = set_file_url($storeInfo['image'], $siteUrl);
  426. /** @var StoreProductServices $storeProductService */
  427. $storeProductService = app()->make(StoreProductServices::class);
  428. $productInfo = $storeProductService->get($storeInfo['product_id']);
  429. $storeInfo['total'] = $productInfo['sales'] + $productInfo['ficti'];
  430. /** @var QrcodeServices $qrcodeService */
  431. $qrcodeService = app()->make(QrcodeServices::class);
  432. $storeInfo['code_base'] = $qrcodeService->getWechatQrcodePath($id . '_' . $uid . '_product_seckill_detail_wap.jpg', '/pages/activity/goods_seckill_details/index?id=' . $id . '&spread=' . $uid);
  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. /** @var SystemGroupDataServices $groupDataService */
  451. $groupDataService = app()->make(SystemGroupDataServices::class);
  452. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  453. $today = strtotime(date('Y-m-d'));
  454. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  455. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  456. //获取秒杀商品状态
  457. if ($storeInfo['status'] == 1) {
  458. /** @var SystemGroupDataServices $systemGroupDataService */
  459. $systemGroupDataService = app()->make(SystemGroupDataServices::class);
  460. $seckillTime = array_column($systemGroupDataService->getConfigNameValue('routine_seckill_time'), null, 'id');
  461. $config = $seckillTime[$storeInfo['time_id']] ?? false;
  462. if (!$config) {
  463. throw new ValidateException('活动已结束');
  464. }
  465. $now_hour = date('H', time());
  466. $start_hour = $config['time'];
  467. $end_hour = (int)$start_hour + (int)$config['continued'];
  468. if ($start_hour <= $now_hour && $end_hour > $now_hour) {
  469. $storeInfo['status'] = 1;
  470. } else if ($start_hour > $now_hour) {
  471. $storeInfo['status'] = 2;
  472. } else {
  473. $storeInfo['status'] = 0;
  474. }
  475. } else {
  476. $storeInfo['status'] == 0;
  477. }
  478. /** @var SystemGroupDataServices $groupDataService */
  479. $groupDataService = app()->make(SystemGroupDataServices::class);
  480. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  481. $today = strtotime(date('Y-m-d'));
  482. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  483. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  484. //商品详情
  485. $data['storeInfo'] = get_thumb_water($storeInfo, 'big', ['image', 'images']);
  486. $storeInfoNew = get_thumb_water($storeInfo, 'small');
  487. $data['storeInfo']['small_image'] = $storeInfoNew['image'];
  488. /** @var StoreProductReplyServices $storeProductReplyService */
  489. $storeProductReplyService = app()->make(StoreProductReplyServices::class);
  490. $data['reply'] = get_thumb_water($storeProductReplyService->getRecProductReply($storeInfo['product_id']), 'small', ['pics']);
  491. [$replyCount, $goodReply, $replyChance] = $storeProductReplyService->getProductReplyData((int)$storeInfo['product_id']);
  492. $data['replyChance'] = $replyChance;
  493. $data['replyCount'] = $replyCount;
  494. /** @var StoreProductAttrServices $storeProductAttrServices */
  495. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  496. list($productAttr, $productValue) = $storeProductAttrServices->getProductAttrDetail($id, $uid, 0, 1, $storeInfo['product_id']);
  497. $data['productAttr'] = $productAttr;
  498. $data['productValue'] = $productValue;
  499. $data['routine_contact_type'] = sys_config('routine_contact_type', 0);
  500. //用户访问事件
  501. event('user.userVisit', [$uid, $id, 'seckill', $storeInfo['product_id'], 'view']);
  502. //浏览记录
  503. ProductLogJob::dispatch(['visit', ['uid' => $uid, 'product_id' => $storeInfo['product_id']]]);
  504. return $data;
  505. }
  506. /**
  507. * 获取秒杀数据
  508. * @param array $ids
  509. * @param string $field
  510. * @return array
  511. * @throws \think\db\exception\DataNotFoundException
  512. * @throws \think\db\exception\DbException
  513. * @throws \think\db\exception\ModelNotFoundException
  514. */
  515. public function getSeckillColumn(array $ids, string $field = '')
  516. {
  517. $seckillProduct = $systemGroupData = [];
  518. $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';
  519. if (!empty($seckill_ids)) {
  520. $seckillProduct = $this->dao->idSeckillList($ids, $field ?: $seckillInfoField);
  521. if (!empty($seckillProduct)) {
  522. $timeIds = Arr::getUniqueKey($seckillProduct, 'time_id');
  523. $seckillProduct = array_combine(array_column($seckillProduct, 'id'), $seckillProduct);
  524. /** @var SystemGroupDataServices $groupServices */
  525. $groupServices = app()->make(SystemGroupDataServices::class);
  526. $systemGroupData = $groupServices->getGroupDataColumn($timeIds);
  527. }
  528. }
  529. return [$seckillProduct, $systemGroupData];
  530. }
  531. /**
  532. * 秒杀库存添加入redis的队列中
  533. * @param string $unique sku唯一值
  534. * @param int $type 类型
  535. * @param int $number 库存个数
  536. * @param bool $isPush 是否放入之前删除当前队列
  537. * @return bool|int
  538. */
  539. public function pushSeckillStock(string $unique, int $type, int $number, bool $isPush = false)
  540. {
  541. $name = 'seckill_' . $unique . '_' . $type;
  542. /** @var CacheService $cache */
  543. $cache = app()->make(CacheService::class);
  544. $res = true;
  545. if (!$isPush) {
  546. $cache->del($name);
  547. }
  548. for ($i = 1; $i <= $number; $i++) {
  549. $res = $res && $cache->lPush($name, $i);
  550. }
  551. return $res;
  552. }
  553. /**
  554. * @param int $productId
  555. * @param string $unique
  556. * @param int $cartNum
  557. * @param string $value
  558. */
  559. public function checkSeckillStock(int $uid, int $seckillId, int $cartNum = 1, string $unique = '')
  560. {
  561. /** @var StoreProductAttrValueServices $attrValueServices */
  562. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  563. if ($unique == '') {
  564. $unique = $attrValueServices->value(['product_id' => $seckillId, 'type' => 1], 'unique');
  565. }
  566. //检查商品活动状态
  567. $StoreSeckillinfo = $this->getSeckillCount($seckillId, '*,title as store_name');
  568. if ($StoreSeckillinfo['once_num'] < $cartNum) {
  569. throw new ValidateException('每个订单限购' . $StoreSeckillinfo['once_num'] . '件');
  570. }
  571. /** @var StoreOrderServices $orderServices */
  572. $orderServices = app()->make(StoreOrderServices::class);
  573. $userBuyCount = $orderServices->getBuyCount($uid, 'seckill_id', $seckillId);
  574. if ($StoreSeckillinfo['num'] < ($userBuyCount + $cartNum)) {
  575. throw new ValidateException('每人总共限购' . $StoreSeckillinfo['num'] . '件');
  576. }
  577. if ($StoreSeckillinfo['num'] < $cartNum) {
  578. throw new ValidateException('每人限购' . $StoreSeckillinfo['num'] . '件');
  579. }
  580. $attrInfo = $attrValueServices->getOne(['product_id' => $seckillId, 'unique' => $unique, 'type' => 1]);
  581. if (!$attrInfo || $attrInfo['product_id'] != $seckillId) {
  582. throw new ValidateException('请选择有效的商品属性');
  583. }
  584. if ($cartNum > $attrInfo['quota']) {
  585. throw new ValidateException('该商品库存不足' . $cartNum);
  586. }
  587. return [$attrInfo, $unique, $StoreSeckillinfo];
  588. }
  589. /**
  590. * 弹出redis队列中的库存条数
  591. * @param string $unique
  592. * @param int $type
  593. * @return mixed
  594. */
  595. public function popSeckillStock(string $unique, int $type, int $number = 1)
  596. {
  597. $name = 'seckill_' . $unique . '_' . $type;
  598. /** @var CacheService $cache */
  599. $cache = app()->make(CacheService::class);
  600. if ($number > $cache->lLen($name)) {
  601. return false;
  602. }
  603. $res = true;
  604. for ($i = 1; $i <= $number; $i++) {
  605. $res = $res && $cache->lPop($name);
  606. }
  607. return $res;
  608. }
  609. /**
  610. * 是否有库存
  611. * @param string $unique
  612. * @param int $type
  613. * @return mixed
  614. * @throws \Psr\SimpleCache\InvalidArgumentException
  615. */
  616. public function isSeckillStock(string $unique, int $type, int $number)
  617. {
  618. /** @var CacheService $cache */
  619. $cache = app()->make(CacheService::class);
  620. return $cache->redisHandler()->lLen('seckill_' . $unique . '_' . $type) >= $number;
  621. }
  622. /**
  623. * 回滚库存
  624. * @param array $cartInfo
  625. * @param int $number
  626. * @return bool
  627. */
  628. public function rollBackStock(array $cartInfo)
  629. {
  630. $res = true;
  631. foreach ($cartInfo as $item) {
  632. $value = $item['cart_info'];
  633. if ($value['seckill_id']) {
  634. $res = $res && $this->pushSeckillStock($value['product_attr_unique'], 1, (int)$value['cart_num'], true);
  635. }
  636. }
  637. return $res;
  638. }
  639. /**
  640. * 占用库存
  641. * @param $cartInfo
  642. */
  643. public function occupySeckillStock($cartInfo, $key, $time = 0)
  644. {
  645. //占用库存
  646. if ($cartInfo) {
  647. if (!$time) {
  648. $time = time() + 600;
  649. }
  650. foreach ($cartInfo as $val) {
  651. if ($val['seckill_id']) {
  652. $this->setSeckillStock($val['product_id'], $val['product_attr_unique'], $time, $key, (int)$val['cart_num']);
  653. }
  654. }
  655. }
  656. return true;
  657. }
  658. /**
  659. * 取消秒杀占用的库存
  660. * @param array $cartInfo
  661. * @param string $key
  662. * @return bool
  663. */
  664. public function cancelOccupySeckillStock(array $cartInfo, string $key)
  665. {
  666. if ($cartInfo) {
  667. foreach ($cartInfo as $val) {
  668. if (isset($val['seckill_id']) && $val['seckill_id']) {
  669. $this->backSeckillStock((int)$val['product_id'], $val['product_attr_unique'], $key, (int)$val['cart_num']);
  670. }
  671. }
  672. }
  673. return true;
  674. }
  675. /**
  676. * 存入当前秒杀商品属性有序集合
  677. * @param $product_id
  678. * @param $unique
  679. * @param $score
  680. * @param $value
  681. * @param int $cart_num
  682. * @return bool
  683. */
  684. public function setSeckillStock($product_id, $unique, $score, $value, $cart_num = 1)
  685. {
  686. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  687. $i = 0;
  688. for ($i; $i < $cart_num; $i++) {
  689. CacheService::zAdd($set_key, $score, $value . $i);
  690. }
  691. return true;
  692. }
  693. /**
  694. * 取消集合中的秒杀商品
  695. * @param int $product_id
  696. * @param string $unique
  697. * @param $value
  698. * @param int $cart_num
  699. * @return bool
  700. */
  701. public function backSeckillStock(int $product_id, string $unique, $value, int $cart_num = 1)
  702. {
  703. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  704. $i = 0;
  705. for ($i; $i < $cart_num; $i++) {
  706. CacheService::zRem($set_key, $value . $i);
  707. }
  708. return true;
  709. }
  710. /**
  711. * 修改秒杀库存
  712. * @param int $num
  713. * @param int $seckillId
  714. * @return bool
  715. */
  716. public function decSeckillStock(int $num, int $seckillId, string $unique = '')
  717. {
  718. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  719. if ($unique) {
  720. /** @var StoreProductAttrValueServices $skuValueServices */
  721. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  722. //减去秒杀商品的sku库存增加销量
  723. $res = false !== $skuValueServices->decProductAttrStock($seckillId, $unique, $num, 1);
  724. //减去秒杀库存
  725. $res = $res && $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  726. //减去当前普通商品sku的库存增加销量
  727. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId, 'type' => 1], 'suk');
  728. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id, 'type' => 0], 'unique');
  729. if ($productUnique) {
  730. $res = $res && $skuValueServices->decProductAttrStock($product_id, $productUnique, $num);
  731. }
  732. } else {
  733. $res = false !== $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  734. }
  735. /** @var StoreProductServices $services */
  736. $services = app()->make(StoreProductServices::class);
  737. //减去普通商品库存
  738. $res = $res && $services->decProductStock($num, $product_id);
  739. if ($res) {
  740. }
  741. return $res;
  742. }
  743. /**
  744. * 加库存减销量
  745. * @param int $num
  746. * @param int $seckillId
  747. * @param string $unique
  748. * @return bool
  749. */
  750. public function incSeckillStock(int $num, int $seckillId, string $unique = '')
  751. {
  752. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  753. if ($unique) {
  754. /** @var StoreProductAttrValueServices $skuValueServices */
  755. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  756. //减去秒杀商品的sku库存增加销量
  757. $res = false !== $skuValueServices->incProductAttrStock($seckillId, $unique, $num, 1);
  758. //减去秒杀库存
  759. $res = $res && $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  760. //减去当前普通商品sku的库存增加销量
  761. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId], 'suk');
  762. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  763. if ($productUnique) {
  764. $res = $res && $skuValueServices->incProductAttrStock($product_id, $productUnique, $num);
  765. }
  766. } else {
  767. $res = false !== $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  768. }
  769. /** @var StoreProductServices $services */
  770. $services = app()->make(StoreProductServices::class);
  771. //减去普通商品库存
  772. $res = $res && $services->incProductStock($num, $product_id);
  773. return $res;
  774. }
  775. /**
  776. * 获取一条秒杀商品
  777. * @param $id
  778. * @param string $field
  779. * @return array|false|\PDOStatement|string|\think\Model
  780. */
  781. public function getValidProduct($id, $field = '*')
  782. {
  783. return $this->dao->validProduct($id, $field);
  784. }
  785. }