StoreSeckillServices.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 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\seckill;
  13. use app\Request;
  14. use app\services\BaseServices;
  15. use app\dao\activity\seckill\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\sku\StoreProductAttrResultServices;
  24. use app\services\product\sku\StoreProductAttrServices;
  25. use app\services\product\sku\StoreProductAttrValueServices;
  26. use app\services\system\config\SystemGroupDataServices;
  27. use crmeb\exceptions\AdminException;
  28. use app\jobs\ProductLogJob;
  29. use crmeb\exceptions\ApiException;
  30. use crmeb\services\CacheService;
  31. use crmeb\utils\Arr;
  32. /**
  33. *
  34. * Class StoreSeckillServices
  35. * @package app\services\activity
  36. * @method getSeckillIdsArray(array $ids, array $field)
  37. * @method get(int $id, array $field) 获取一条数据
  38. */
  39. class StoreSeckillServices extends BaseServices
  40. {
  41. /**
  42. * StoreSeckillServices constructor.
  43. * @param StoreSeckillDao $dao
  44. */
  45. public function __construct(StoreSeckillDao $dao)
  46. {
  47. $this->dao = $dao;
  48. }
  49. public function getCount(array $where)
  50. {
  51. $this->dao->count($where);
  52. }
  53. /**
  54. * 秒杀是否存在
  55. * @param int $id
  56. * @return int
  57. */
  58. public function getSeckillCount(int $id = 0, string $field = 'time_id')
  59. {
  60. $where = [];
  61. $where[] = ['is_del', '=', 0];
  62. $where[] = ['status', '=', 1];
  63. if ($id) {
  64. $time = time();
  65. $where[] = ['id', '=', $id];
  66. $where[] = ['start_time', '<=', $time];
  67. $where[] = ['stop_time', '>=', $time - 86400];
  68. $seckill_one = $this->dao->getOne($where, $field);
  69. if (!$seckill_one) {
  70. throw new ApiException(410322);
  71. }
  72. /** @var SystemGroupDataServices $systemGroupDataService */
  73. $systemGroupDataService = app()->make(SystemGroupDataServices::class);
  74. $seckillTime = array_column($systemGroupDataService->getConfigNameValue('routine_seckill_time'), null, 'id');
  75. $config = $seckillTime[$seckill_one['time_id']] ?? false;
  76. if (!$config) {
  77. throw new ApiException(410322);
  78. }
  79. $now_hour = date('H', time());
  80. $start_hour = $config['time'];
  81. $end_hour = (int)$start_hour + (int)$config['continued'];
  82. if ($start_hour <= $now_hour && $end_hour > $now_hour) {
  83. return $seckill_one;
  84. } else if ($start_hour > $now_hour) {
  85. throw new ApiException(410321);
  86. } else {
  87. throw new ApiException(410322);
  88. }
  89. } else {
  90. $seckillTime = sys_data('routine_seckill_time') ?: [];//秒杀时间段
  91. $timeInfo = ['time' => 0, 'continued' => 0];
  92. foreach ($seckillTime as $key => $value) {
  93. $currentHour = date('H');
  94. $activityEndHour = (int)$value['time'] + (int)$value['continued'];
  95. if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour && $activityEndHour < 24) {
  96. $timeInfo = $value;
  97. break;
  98. }
  99. }
  100. if ($timeInfo['time'] == 0) return 0;
  101. $activityEndHour = $timeInfo['time'] + (int)$timeInfo['continued'];
  102. $startTime = strtotime(date('Y-m-d')) + (int)$timeInfo['time'] * 3600;
  103. $stopTime = strtotime(date('Y-m-d')) + (int)$activityEndHour * 3600;
  104. $where[] = ['start_time', '<', $startTime];
  105. $where[] = ['stop_time', '>', $stopTime];
  106. return $this->dao->getCount($where);
  107. }
  108. }
  109. /**
  110. * 保存数据
  111. * @param int $id
  112. * @param array $data
  113. */
  114. public function saveData(int $id, array $data)
  115. {
  116. if ($data['section_time']) {
  117. [$start_time, $end_time] = $data['section_time'];
  118. if (strtotime($end_time) + 86400 < time()) {
  119. throw new AdminException(400507);
  120. }
  121. }
  122. $seckill = [];
  123. if ($id) {
  124. $seckill = $this->get((int)$id);
  125. if (!$seckill) {
  126. throw new AdminException(100026);
  127. }
  128. }
  129. //限制编辑
  130. if ($data['copy'] == 0 && $seckill) {
  131. if ($seckill['stop_time'] + 86400 < time()) {
  132. throw new AdminException(400508);
  133. }
  134. }
  135. if ($data['num'] < $data['once_num']) {
  136. throw new AdminException(400500);
  137. }
  138. if ($data['copy'] == 1) {
  139. $id = 0;
  140. unset($data['copy']);
  141. }
  142. $description = $data['description'];
  143. $detail = $data['attrs'];
  144. $items = $data['items'];
  145. $data['start_time'] = strtotime($data['section_time'][0]);
  146. $data['stop_time'] = strtotime($data['section_time'][1]);
  147. $data['image'] = $data['images'][0];
  148. $data['images'] = json_encode($data['images']);
  149. $data['price'] = min(array_column($detail, 'price'));
  150. $data['ot_price'] = min(array_column($detail, 'ot_price'));
  151. $data['quota'] = $data['quota_show'] = array_sum(array_column($detail, 'quota'));
  152. $data['stock'] = array_sum(array_column($detail, 'stock'));
  153. $data['logistics'] = implode(',', $data['logistics']);
  154. unset($data['section_time'], $data['description'], $data['attrs'], $data['items']);
  155. /** @var StoreDescriptionServices $storeDescriptionServices */
  156. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  157. /** @var StoreProductAttrServices $storeProductAttrServices */
  158. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  159. /** @var StoreProductServices $storeProductServices */
  160. $storeProductServices = app()->make(StoreProductServices::class);
  161. if ($data['quota'] > $storeProductServices->value(['id' => $data['product_id']], 'stock')) {
  162. throw new AdminException(400090);
  163. }
  164. $this->transaction(function () use ($id, $data, $description, $detail, $items, $storeDescriptionServices, $storeProductAttrServices, $storeProductServices) {
  165. if ($id) {
  166. $res = $this->dao->update($id, $data);
  167. $storeDescriptionServices->saveDescription((int)$id, $description, 1);
  168. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$id, 1);
  169. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$id, 1);
  170. if (!$res) throw new AdminException(100007);
  171. } else {
  172. if (!$storeProductServices->getOne(['is_show' => 1, 'is_del' => 0, 'id' => $data['product_id']])) {
  173. throw new AdminException(400091);
  174. }
  175. $data['add_time'] = time();
  176. $res = $this->dao->save($data);
  177. $storeDescriptionServices->saveDescription((int)$res->id, $description, 1);
  178. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$res->id, 1);
  179. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$res->id, 1);
  180. if (!$res) throw new AdminException(100022);
  181. }
  182. $res = true;
  183. foreach ($valueGroup->toArray() as $item) {
  184. $res = $res && CacheService::setStock($item['unique'], (int)$item['quota_show'], 1);
  185. }
  186. if (!$res) {
  187. throw new AdminException(400092);
  188. }
  189. });
  190. }
  191. /**
  192. * 获取列表
  193. * @param array $where
  194. * @return array
  195. * @throws \think\db\exception\DataNotFoundException
  196. * @throws \think\db\exception\DbException
  197. * @throws \think\db\exception\ModelNotFoundException
  198. */
  199. public function systemPage(array $where)
  200. {
  201. [$page, $limit] = $this->getPageValue();
  202. $list = $this->dao->getList($where, $page, $limit);
  203. $count = $this->dao->count($where + ['is_del' => 0]);
  204. foreach ($list as &$item) {
  205. $item['store_name'] = $item['title'];
  206. if ($item['status']) {
  207. if ($item['start_time'] > time())
  208. $item['start_name'] = '未开始';
  209. else if (bcadd($item['stop_time'], '86400') < time())
  210. $item['start_name'] = '已结束';
  211. else if (bcadd($item['stop_time'], '86400') > time() && $item['start_time'] < time()) {
  212. $item['start_name'] = '进行中';
  213. }
  214. } else $item['start_name'] = '已结束';
  215. $end_time = $item['stop_time'] ? date('Y/m/d', (int)$item['stop_time']) : '';
  216. $item['_stop_time'] = $end_time;
  217. $item['stop_status'] = $item['stop_time'] + 86400 < time() ? 1 : 0;
  218. }
  219. return compact('list', 'count');
  220. }
  221. /**
  222. * 后台页面设计获取商品列表
  223. * @param $where
  224. * @return array
  225. * @throws \think\db\exception\DataNotFoundException
  226. * @throws \think\db\exception\DbException
  227. * @throws \think\db\exception\ModelNotFoundException
  228. */
  229. public function getDiySeckillList($where)
  230. {
  231. unset($where['is_show']);
  232. $where['storeProductId'] = true;
  233. $where['status'] = 1;
  234. [$page, $limit] = $this->getPageValue();
  235. $list = $this->dao->getList($where, $page, $limit);
  236. $count = $this->dao->getCount($where);
  237. $cateIds = implode(',', array_column($list, 'cate_id'));
  238. /** @var StoreCategoryServices $storeCategoryServices */
  239. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  240. $cateList = $storeCategoryServices->getCateArray($cateIds);
  241. foreach ($list as &$item) {
  242. $cateName = '';
  243. $item['cate_name'] = '';
  244. if ($item['cate_id']) {
  245. $cateName = array_filter($cateList, function ($val) use ($item) {
  246. if (in_array($val['id'], explode(',', $item['cate_id']))) {
  247. return $val;
  248. }
  249. });
  250. $item['cate_name'] = implode(',', array_column($cateName, 'cate_name'));
  251. }
  252. $item['store_name'] = $item['title'];
  253. $item['price'] = floatval($item['price']);
  254. $item['is_product_type'] = 3;
  255. }
  256. return compact('count', 'list');
  257. }
  258. /**
  259. * 首页秒杀数据
  260. * @param $where
  261. * @return array|int
  262. * @throws \think\db\exception\DataNotFoundException
  263. * @throws \think\db\exception\DbException
  264. * @throws \think\db\exception\ModelNotFoundException
  265. */
  266. public function getHomeSeckillList($where)
  267. {
  268. $data = [];
  269. $seckillTime = sys_data('routine_seckill_time') ?: [];//秒杀时间段
  270. $today = strtotime(date('Y-m-d'));
  271. $timeInfo = ['time' => 0, 'continued' => 0];
  272. foreach ($seckillTime as $key => $value) {
  273. $currentHour = date('H');
  274. $activityEndHour = (int)$value['time'] + (int)$value['continued'];
  275. if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour && $activityEndHour <= 24) {
  276. $timeInfo = $value;
  277. break;
  278. }
  279. }
  280. if ($timeInfo['time'] == 0) return [];
  281. $data['time'] = $timeInfo['time'] . ':00';
  282. $activityEndHour = bcadd($timeInfo['time'], $timeInfo['continued'], 0);
  283. $data['stop'] = (int)bcadd((string)$today, bcmul($activityEndHour, '3600', 0));
  284. $where['time_id'] = $timeInfo['id'];
  285. [$page, $limit] = $this->getPageValue();
  286. $data['list'] = $this->dao->getHomeList($where, $page, $limit);
  287. foreach ($data['list'] as &$item) {
  288. $item['price'] = floatval($item['price']);
  289. }
  290. return $data;
  291. }
  292. /**
  293. * 获取秒杀详情
  294. * @param int $id
  295. * @return array|\think\Model|null
  296. */
  297. public function getInfo(int $id)
  298. {
  299. $info = $this->dao->get($id);
  300. if ($info) {
  301. if ($info['start_time'])
  302. $start_time = date('Y-m-d', (int)$info['start_time']);
  303. if ($info['stop_time'])
  304. $stop_time = date('Y-m-d', (int)$info['stop_time']);
  305. if (isset($start_time) && isset($stop_time))
  306. $info['section_time'] = [$start_time, $stop_time];
  307. else
  308. $info['section_time'] = [];
  309. unset($info['start_time'], $info['stop_time']);
  310. $info['give_integral'] = intval($info['give_integral']);
  311. $info['price'] = floatval($info['price']);
  312. $info['ot_price'] = floatval($info['ot_price']);
  313. $info['postage'] = floatval($info['postage']);
  314. $info['cost'] = floatval($info['cost']);
  315. $info['weight'] = floatval($info['weight']);
  316. $info['volume'] = floatval($info['volume']);
  317. $info['logistics'] = explode(',', $info['logistics']);
  318. /** @var StoreDescriptionServices $storeDescriptionServices */
  319. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  320. $info['description'] = $storeDescriptionServices->getDescription(['product_id' => $id, 'type' => 1]);
  321. $info['attrs'] = $this->attrList($id, $info['product_id']);
  322. }
  323. return $info;
  324. }
  325. /**
  326. * 获取规格
  327. * @param int $id
  328. * @param int $pid
  329. * @return mixed
  330. */
  331. public function attrList(int $id, int $pid)
  332. {
  333. /** @var StoreProductAttrResultServices $storeProductAttrResultServices */
  334. $storeProductAttrResultServices = app()->make(StoreProductAttrResultServices::class);
  335. $seckillResult = $storeProductAttrResultServices->value(['product_id' => $id, 'type' => 1], 'result');
  336. $items = json_decode($seckillResult, true)['attr'];
  337. $productAttr = $this->getAttr($items, $pid, 0);
  338. $seckillAttr = $this->getAttr($items, $id, 1);
  339. foreach ($productAttr as $pk => $pv) {
  340. foreach ($seckillAttr as &$sv) {
  341. if ($pv['detail'] == $sv['detail']) {
  342. $productAttr[$pk] = $sv;
  343. }
  344. }
  345. $productAttr[$pk]['detail'] = json_decode($productAttr[$pk]['detail']);
  346. }
  347. $attrs['items'] = $items;
  348. $attrs['value'] = $productAttr;
  349. foreach ($items as $key => $item) {
  350. $header[] = ['title' => $item['value'], 'key' => 'value' . ($key + 1), 'align' => 'center', 'minWidth' => 80];
  351. }
  352. $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 120];
  353. $header[] = ['title' => '秒杀价', 'slot' => 'price', 'align' => 'center', 'minWidth' => 80];
  354. $header[] = ['title' => '成本价', 'key' => 'cost', 'align' => 'center', 'minWidth' => 80];
  355. $header[] = ['title' => '原价', 'key' => 'ot_price', 'align' => 'center', 'minWidth' => 80];
  356. $header[] = ['title' => '库存', 'key' => 'stock', 'align' => 'center', 'minWidth' => 80];
  357. $header[] = ['title' => '限量', 'key' => 'quota', 'type' => 1, 'align' => 'center', 'minWidth' => 80];
  358. $header[] = ['title' => '重量(KG)', 'key' => 'weight', 'align' => 'center', 'minWidth' => 80];
  359. $header[] = ['title' => '体积(m³)', 'key' => 'volume', 'align' => 'center', 'minWidth' => 80];
  360. $header[] = ['title' => '商品编号', 'key' => 'bar_code', 'align' => 'center', 'minWidth' => 80];
  361. $attrs['header'] = $header;
  362. return $attrs;
  363. }
  364. /**
  365. * 获取规格
  366. * @param $attr
  367. * @param $id
  368. * @param $type
  369. * @return array
  370. */
  371. public function getAttr($attr, $id, $type)
  372. {
  373. /** @var StoreProductAttrValueServices $storeProductAttrValueServices */
  374. $storeProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
  375. list($value, $head) = attr_format($attr);
  376. $valueNew = [];
  377. $count = 0;
  378. foreach ($value as $suk) {
  379. $detail = explode(',', $suk);
  380. $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');
  381. if (count($sukValue)) {
  382. foreach ($detail as $k => $v) {
  383. $valueNew[$count]['value' . ($k + 1)] = $v;
  384. }
  385. $valueNew[$count]['detail'] = json_encode(array_combine($head, $detail));
  386. $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
  387. $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
  388. $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
  389. $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
  390. $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
  391. $valueNew[$count]['quota'] = $sukValue[$suk]['quota'] ? intval($sukValue[$suk]['quota']) : 0;
  392. $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
  393. $valueNew[$count]['weight'] = $sukValue[$suk]['weight'] ? floatval($sukValue[$suk]['weight']) : 0;
  394. $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ? floatval($sukValue[$suk]['volume']) : 0;
  395. $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ? floatval($sukValue[$suk]['brokerage']) : 0;
  396. $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ? floatval($sukValue[$suk]['brokerage_two']) : 0;
  397. $valueNew[$count]['_checked'] = $type != 0;
  398. $count++;
  399. }
  400. }
  401. return $valueNew;
  402. }
  403. /**
  404. * 获取某个时间段的秒杀列表
  405. * @param int $time
  406. * @return array
  407. * @throws \think\db\exception\DataNotFoundException
  408. * @throws \think\db\exception\DbException
  409. * @throws \think\db\exception\ModelNotFoundException
  410. */
  411. public function getListByTime(int $time)
  412. {
  413. [$page, $limit] = $this->getPageValue();
  414. $seckillInfo = $this->dao->getListByTime($time, $page, $limit);
  415. if (count($seckillInfo)) {
  416. foreach ($seckillInfo as $key => &$item) {
  417. if ($item['quota'] > 0) {
  418. $percent = (int)(($item['quota_show'] - $item['quota']) / $item['quota_show'] * 100);
  419. $item['percent'] = $percent;
  420. $item['stock'] = $item['quota'];
  421. } else {
  422. $item['percent'] = 100;
  423. $item['stock'] = 0;
  424. }
  425. $item['price'] = floatval($item['price']);
  426. $item['ot_price'] = floatval($item['ot_price']);
  427. }
  428. }
  429. return $seckillInfo;
  430. }
  431. /**
  432. * 获取秒杀详情
  433. * @param Request $request
  434. * @param int $id
  435. * @return mixed
  436. * @throws \think\db\exception\DataNotFoundException
  437. * @throws \think\db\exception\DbException
  438. * @throws \think\db\exception\ModelNotFoundException
  439. */
  440. public function seckillDetail(Request $request, int $id)
  441. {
  442. $uid = (int)$request->uid();
  443. $storeInfo = $this->dao->getOne(['id' => $id], '*', ['description']);
  444. if (!$storeInfo) {
  445. throw new ApiException(410294);
  446. } else {
  447. $storeInfo = $storeInfo->toArray();
  448. }
  449. $siteUrl = sys_config('site_url');
  450. $storeInfo['image'] = set_file_url($storeInfo['image'], $siteUrl);
  451. $storeInfo['image_base'] = set_file_url($storeInfo['image'], $siteUrl);
  452. $storeInfo['store_name'] = $storeInfo['title'];
  453. /** @var StoreProductServices $storeProductService */
  454. $storeProductService = app()->make(StoreProductServices::class);
  455. $productInfo = $storeProductService->get($storeInfo['product_id']);
  456. $storeInfo['total'] = $productInfo['sales'] + $productInfo['ficti'];
  457. if (sys_config('share_qrcode', 0) && request()->isWechat()) {
  458. /** @var QrcodeServices $qrcodeService */
  459. $qrcodeService = app()->make(QrcodeServices::class);
  460. $storeInfo['wechat_code'] = $qrcodeService->getTemporaryQrcode('seckill-' . $id, $uid)->url;
  461. } else {
  462. $storeInfo['wechat_code'] = '';
  463. }
  464. /** @var StoreOrderServices $storeOrderServices */
  465. $storeOrderServices = app()->make(StoreOrderServices::class);
  466. $data['buy_num'] = $storeOrderServices->getBuyCount($uid, 'seckill_id', $id);
  467. /** @var StoreProductRelationServices $storeProductRelationServices */
  468. $storeProductRelationServices = app()->make(StoreProductRelationServices::class);
  469. $storeInfo['userCollect'] = $storeProductRelationServices->isProductRelation(['uid' => $uid, 'product_id' => $storeInfo['product_id'], 'type' => 'collect', 'category' => 'product']);
  470. $storeInfo['userLike'] = false;
  471. $storeInfo['uid'] = $uid;
  472. if ($storeInfo['quota'] > 0) {
  473. $percent = (int)(($storeInfo['quota_show'] - $storeInfo['quota']) / $storeInfo['quota_show'] * 100);
  474. $storeInfo['percent'] = $percent;
  475. $storeInfo['stock'] = $storeInfo['quota'];
  476. } else {
  477. $storeInfo['percent'] = 100;
  478. $storeInfo['stock'] = 0;
  479. }
  480. //到期时间
  481. /** @var SystemGroupDataServices $groupDataService */
  482. $groupDataService = app()->make(SystemGroupDataServices::class);
  483. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  484. $today = strtotime(date('Y-m-d'));
  485. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  486. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  487. //获取秒杀商品状态
  488. if ($storeInfo['status'] == 1) {
  489. if ($storeInfo['start_time'] > time()) {
  490. $storeInfo['status'] = 2;
  491. } elseif (($storeInfo['stop_time'] + 86400) < time()) {
  492. $storeInfo['status'] = 0;
  493. } else {
  494. /** @var SystemGroupDataServices $systemGroupDataService */
  495. $systemGroupDataService = app()->make(SystemGroupDataServices::class);
  496. $seckillTime = array_column($systemGroupDataService->getConfigNameValue('routine_seckill_time'), null, 'id');
  497. $config = $seckillTime[$storeInfo['time_id']] ?? false;
  498. if (!$config) {
  499. throw new ApiException(410322);
  500. }
  501. $now_hour = date('H', time());
  502. $start_hour = $config['time'];
  503. $end_hour = (int)$start_hour + (int)$config['continued'];
  504. if ($start_hour <= $now_hour && $end_hour > $now_hour) {
  505. $storeInfo['status'] = 1;
  506. } else if ($start_hour > $now_hour) {
  507. $storeInfo['status'] = 2;
  508. } else {
  509. $storeInfo['status'] = 0;
  510. }
  511. }
  512. } else {
  513. $storeInfo['status'] == 0;
  514. }
  515. /** @var SystemGroupDataServices $groupDataService */
  516. $groupDataService = app()->make(SystemGroupDataServices::class);
  517. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  518. $today = strtotime(date('Y-m-d'));
  519. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  520. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  521. //商品详情
  522. $data['storeInfo'] = get_thumb_water($storeInfo, 'big', ['image', 'images']);
  523. $storeInfoNew = get_thumb_water($storeInfo, 'small');
  524. $data['storeInfo']['small_image'] = $storeInfoNew['image'];
  525. /** @var StoreProductReplyServices $storeProductReplyService */
  526. $storeProductReplyService = app()->make(StoreProductReplyServices::class);
  527. $data['reply'] = get_thumb_water($storeProductReplyService->getRecProductReply($storeInfo['product_id']), 'small', ['pics']);
  528. [$replyCount, $goodReply, $replyChance] = $storeProductReplyService->getProductReplyData((int)$storeInfo['product_id']);
  529. $data['replyChance'] = $replyChance;
  530. $data['replyCount'] = $replyCount;
  531. /** @var StoreProductAttrServices $storeProductAttrServices */
  532. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  533. list($productAttr, $productValue) = $storeProductAttrServices->getProductAttrDetail($id, $uid, 0, 1, $storeInfo['product_id']);
  534. $data['productAttr'] = $productAttr;
  535. $data['productValue'] = $productValue;
  536. $data['routine_contact_type'] = sys_config('routine_contact_type', 0);
  537. //用户访问事件
  538. event('UserVisitListener', [$uid, $id, 'seckill', $storeInfo['product_id'], 'view']);
  539. //浏览记录
  540. ProductLogJob::dispatch(['visit', ['uid' => $uid, 'product_id' => $storeInfo['product_id']]]);
  541. return $data;
  542. }
  543. /**
  544. * 获取秒杀数据
  545. * @param array $ids
  546. * @param string $field
  547. * @return array
  548. * @throws \think\db\exception\DataNotFoundException
  549. * @throws \think\db\exception\DbException
  550. * @throws \think\db\exception\ModelNotFoundException
  551. */
  552. public function getSeckillColumn(array $ids, string $field = '')
  553. {
  554. $seckillProduct = $systemGroupData = [];
  555. $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';
  556. if (!empty($seckill_ids)) {
  557. $seckillProduct = $this->dao->idSeckillList($ids, $field ?: $seckillInfoField);
  558. if (!empty($seckillProduct)) {
  559. $timeIds = Arr::getUniqueKey($seckillProduct, 'time_id');
  560. $seckillProduct = array_combine(array_column($seckillProduct, 'id'), $seckillProduct);
  561. /** @var SystemGroupDataServices $groupServices */
  562. $groupServices = app()->make(SystemGroupDataServices::class);
  563. $systemGroupData = $groupServices->getGroupDataColumn($timeIds);
  564. }
  565. }
  566. return [$seckillProduct, $systemGroupData];
  567. }
  568. /**
  569. * 秒杀库存添加入redis的队列中
  570. * @param string $unique sku唯一值
  571. * @param int $type 类型
  572. * @param int $number 库存个数
  573. * @param bool $isPush 是否放入之前删除当前队列
  574. * @return bool|int
  575. */
  576. public function pushSeckillStock(string $unique, int $type, int $number, bool $isPush = false)
  577. {
  578. $name = 'seckill_' . $unique . '_' . $type;
  579. /** @var CacheService $cache */
  580. $cache = app()->make(CacheService::class);
  581. $res = true;
  582. if (!$isPush) {
  583. $cache->delete($name);
  584. }
  585. for ($i = 1; $i <= $number; $i++) {
  586. $res = $res && $cache->lPush($name, $i);
  587. }
  588. return $res;
  589. }
  590. /**
  591. * @param int $productId
  592. * @param string $unique
  593. * @param int $cartNum
  594. * @param string $value
  595. */
  596. public function checkSeckillStock(int $uid, int $seckillId, int $cartNum = 1, string $unique = '')
  597. {
  598. /** @var StoreProductAttrValueServices $attrValueServices */
  599. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  600. if ($unique == '') {
  601. $unique = $attrValueServices->value(['product_id' => $seckillId, 'type' => 1], 'unique');
  602. }
  603. //检查商品活动状态
  604. $StoreSeckillinfo = $this->getSeckillCount($seckillId, '*,title as store_name');
  605. if ($StoreSeckillinfo['once_num'] < $cartNum) {
  606. throw new ApiException(410313, ['num' => $StoreSeckillinfo['once_num']]);
  607. }
  608. /** @var StoreOrderServices $orderServices */
  609. $orderServices = app()->make(StoreOrderServices::class);
  610. $userBuyCount = $orderServices->getBuyCount($uid, 'seckill_id', $seckillId);
  611. if ($StoreSeckillinfo['num'] < ($userBuyCount + $cartNum)) {
  612. throw new ApiException(410298, ['num' => $StoreSeckillinfo['num']]);
  613. }
  614. if ($StoreSeckillinfo['num'] < $cartNum) {
  615. throw new ApiException(410317, ['num' => $StoreSeckillinfo['num']]);
  616. }
  617. $attrInfo = $attrValueServices->getOne(['product_id' => $seckillId, 'unique' => $unique, 'type' => 1]);
  618. if (!$attrInfo || $attrInfo['product_id'] != $seckillId) {
  619. throw new ApiException(410305);
  620. }
  621. if ($cartNum > $attrInfo['quota']) {
  622. throw new ApiException(410296);
  623. }
  624. return [$attrInfo, $unique, $StoreSeckillinfo];
  625. }
  626. /**
  627. * 弹出redis队列中的库存条数
  628. * @param string $unique
  629. * @param int $type
  630. * @return mixed
  631. */
  632. public function popSeckillStock(string $unique, int $type, int $number = 1)
  633. {
  634. $name = 'seckill_' . $unique . '_' . $type;
  635. /** @var CacheService $cache */
  636. $cache = app()->make(CacheService::class);
  637. if ($number > $cache->lLen($name)) {
  638. return false;
  639. }
  640. $res = true;
  641. for ($i = 1; $i <= $number; $i++) {
  642. $res = $res && $cache->lPop($name);
  643. }
  644. return $res;
  645. }
  646. /**
  647. * 是否有库存
  648. * @param string $unique
  649. * @param int $type
  650. * @return mixed
  651. * @throws \Psr\SimpleCache\InvalidArgumentException
  652. */
  653. public function isSeckillStock(string $unique, int $type, int $number)
  654. {
  655. /** @var CacheService $cache */
  656. $cache = app()->make(CacheService::class);
  657. return $cache->lLen('seckill_' . $unique . '_' . $type) >= $number;
  658. }
  659. /**
  660. * 回滚库存
  661. * @param array $cartInfo
  662. * @param int $number
  663. * @return bool
  664. */
  665. public function rollBackStock(array $cartInfo)
  666. {
  667. $res = true;
  668. foreach ($cartInfo as $item) {
  669. $value = $item['cart_info'];
  670. if ($value['seckill_id']) {
  671. $res = $res && $this->pushSeckillStock($value['product_attr_unique'], 1, (int)$value['cart_num'], true);
  672. }
  673. }
  674. return $res;
  675. }
  676. /**
  677. * 占用库存
  678. * @param $cartInfo
  679. */
  680. public function occupySeckillStock($cartInfo, $key, $time = 0)
  681. {
  682. //占用库存
  683. if ($cartInfo) {
  684. if (!$time) {
  685. $time = time() + 600;
  686. }
  687. foreach ($cartInfo as $val) {
  688. if ($val['seckill_id']) {
  689. $this->setSeckillStock($val['product_id'], $val['product_attr_unique'], $time, $key, (int)$val['cart_num']);
  690. }
  691. }
  692. }
  693. return true;
  694. }
  695. /**
  696. * 取消秒杀占用的库存
  697. * @param array $cartInfo
  698. * @param string $key
  699. * @return bool
  700. */
  701. public function cancelOccupySeckillStock(array $cartInfo, string $key)
  702. {
  703. if ($cartInfo) {
  704. foreach ($cartInfo as $val) {
  705. if (isset($val['seckill_id']) && $val['seckill_id']) {
  706. $this->backSeckillStock((int)$val['product_id'], $val['product_attr_unique'], $key, (int)$val['cart_num']);
  707. }
  708. }
  709. }
  710. return true;
  711. }
  712. /**
  713. * 存入当前秒杀商品属性有序集合
  714. * @param $product_id
  715. * @param $unique
  716. * @param $score
  717. * @param $value
  718. * @param int $cart_num
  719. * @return bool
  720. */
  721. public function setSeckillStock($product_id, $unique, $score, $value, $cart_num = 1)
  722. {
  723. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  724. $i = 0;
  725. for ($i; $i < $cart_num; $i++) {
  726. CacheService::zAdd($set_key, $score, $value . $i);
  727. }
  728. return true;
  729. }
  730. /**
  731. * 取消集合中的秒杀商品
  732. * @param int $product_id
  733. * @param string $unique
  734. * @param $value
  735. * @param int $cart_num
  736. * @return bool
  737. */
  738. public function backSeckillStock(int $product_id, string $unique, $value, int $cart_num = 1)
  739. {
  740. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  741. $i = 0;
  742. for ($i; $i < $cart_num; $i++) {
  743. CacheService::zRem($set_key, $value . $i);
  744. }
  745. return true;
  746. }
  747. /**
  748. * 修改秒杀库存
  749. * @param int $num
  750. * @param int $seckillId
  751. * @return bool
  752. */
  753. public function decSeckillStock(int $num, int $seckillId, string $unique = '')
  754. {
  755. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  756. if ($unique) {
  757. /** @var StoreProductAttrValueServices $skuValueServices */
  758. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  759. //减去秒杀商品的sku库存增加销量
  760. $res = false !== $skuValueServices->decProductAttrStock($seckillId, $unique, $num, 1);
  761. //减去秒杀库存
  762. $res = $res && $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  763. //减去当前普通商品sku的库存增加销量
  764. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId, 'type' => 1], 'suk');
  765. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id, 'type' => 0], 'unique');
  766. if ($productUnique) {
  767. $res = $res && $skuValueServices->decProductAttrStock($product_id, $productUnique, $num);
  768. }
  769. } else {
  770. $res = false !== $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  771. }
  772. /** @var StoreProductServices $services */
  773. $services = app()->make(StoreProductServices::class);
  774. //减去普通商品库存
  775. return $res && $services->decProductStock($num, $product_id);
  776. }
  777. /**
  778. * 加库存减销量
  779. * @param int $num
  780. * @param int $seckillId
  781. * @param string $unique
  782. * @return bool
  783. */
  784. public function incSeckillStock(int $num, int $seckillId, string $unique = '')
  785. {
  786. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  787. if ($unique) {
  788. /** @var StoreProductAttrValueServices $skuValueServices */
  789. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  790. //减去秒杀商品的sku库存增加销量
  791. $res = false !== $skuValueServices->incProductAttrStock($seckillId, $unique, $num, 1);
  792. //减去秒杀库存
  793. $res = $res && $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  794. //减去当前普通商品sku的库存增加销量
  795. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId], 'suk');
  796. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  797. if ($productUnique) {
  798. $res = $res && $skuValueServices->incProductAttrStock($product_id, $productUnique, $num);
  799. }
  800. } else {
  801. $res = false !== $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  802. }
  803. /** @var StoreProductServices $services */
  804. $services = app()->make(StoreProductServices::class);
  805. //减去普通商品库存
  806. $res = $res && $services->incProductStock($num, $product_id);
  807. return $res;
  808. }
  809. /**
  810. * 获取一条秒杀商品
  811. * @param $id
  812. * @param string $field
  813. * @return array|false|\PDOStatement|string|\think\Model
  814. */
  815. public function getValidProduct($id, $field = '*')
  816. {
  817. return $this->dao->validProduct($id, $field);
  818. }
  819. /**
  820. * 秒杀统计
  821. * @return array
  822. */
  823. public function seckillStatistics($id)
  824. {
  825. /** @var StoreOrderServices $orderServices */
  826. $orderServices = app()->make(StoreOrderServices::class);
  827. $pay_count = $orderServices->getDistinctCount([['seckill_id', '=', $id], ['paid', '=', 1]], 'uid', false);
  828. $order_count = $orderServices->getDistinctCount([['seckill_id', '=', $id]], 'uid', false);
  829. $all_price = $orderServices->sum([['seckill_id', '=', $id], ['refund_type', 'in', [0, 3]]], 'pay_price');
  830. $seckillInfo = $this->dao->get($id);
  831. $pay_rate = $seckillInfo['quota'] . '/' . $seckillInfo['quota_show'];
  832. return compact('pay_count', 'order_count', 'all_price', 'pay_rate');
  833. }
  834. /**
  835. * 秒杀参与人统计
  836. * @param $id
  837. * @param string $keyword
  838. * @return array
  839. */
  840. public function seckillPeople($id, $keyword = '')
  841. {
  842. /** @var StoreOrderServices $orderServices */
  843. $orderServices = app()->make(StoreOrderServices::class);
  844. [$page, $limit] = $this->getPageValue();
  845. $list = $orderServices->seckillPeople($id, $keyword, $page, $limit);
  846. $count = $orderServices->getDistinctCount([['seckill_id', '=', $id], ['real_name|uid|user_phone', 'like', '%' . $keyword . '%']], 'uid', false);
  847. foreach ($list as &$item) {
  848. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  849. }
  850. return compact('list', 'count');
  851. }
  852. /**
  853. * 秒杀订单统计
  854. * @param $id
  855. * @param array $where
  856. * @return array
  857. */
  858. public function seckillOrder($id, $where = [])
  859. {
  860. /** @var StoreOrderServices $orderServices */
  861. $orderServices = app()->make(StoreOrderServices::class);
  862. [$page, $limit] = $this->getPageValue();
  863. $list = $orderServices->seckillOrder($id, $where, $page, $limit);
  864. $where['seckill_id'] = $id;
  865. $count = $orderServices->count($where);
  866. foreach ($list as &$item) {
  867. if ($item['status'] == 0) {
  868. if ($item['paid'] == 0) {
  869. $item['status'] = '未支付';
  870. } else {
  871. $item['status'] = '未发货';
  872. }
  873. } elseif ($item['status'] == 1) {
  874. $item['status'] = '待收货';
  875. } elseif ($item['status'] == 2) {
  876. $item['status'] = '待评价';
  877. } elseif ($item['status'] == 3) {
  878. $item['status'] = '已完成';
  879. } elseif ($item['status'] == -2) {
  880. $item['status'] = '已退款';
  881. } else {
  882. $item['status'] = '未知';
  883. }
  884. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  885. $item['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
  886. }
  887. return compact('list', 'count');
  888. }
  889. }