StoreSeckillServices.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 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. /** @var QrcodeServices $qrcodeService */
  458. $qrcodeService = app()->make(QrcodeServices::class);
  459. $storeInfo['code_base'] = $qrcodeService->getWechatQrcodePath($id . '_' . $uid . '_product_seckill_detail_wap.jpg', '/pages/activity/goods_seckill_details/index?id=' . $id . '&spread=' . $uid);
  460. /** @var StoreOrderServices $storeOrderServices */
  461. $storeOrderServices = app()->make(StoreOrderServices::class);
  462. $data['buy_num'] = $storeOrderServices->getBuyCount($uid, 'seckill_id', $id);
  463. /** @var StoreProductRelationServices $storeProductRelationServices */
  464. $storeProductRelationServices = app()->make(StoreProductRelationServices::class);
  465. $storeInfo['userCollect'] = $storeProductRelationServices->isProductRelation(['uid' => $uid, 'product_id' => $storeInfo['product_id'], 'type' => 'collect', 'category' => 'product']);
  466. $storeInfo['userLike'] = false;
  467. $storeInfo['uid'] = $uid;
  468. if ($storeInfo['quota'] > 0) {
  469. $percent = (int)(($storeInfo['quota_show'] - $storeInfo['quota']) / $storeInfo['quota_show'] * 100);
  470. $storeInfo['percent'] = $percent;
  471. $storeInfo['stock'] = $storeInfo['quota'];
  472. } else {
  473. $storeInfo['percent'] = 100;
  474. $storeInfo['stock'] = 0;
  475. }
  476. //到期时间
  477. /** @var SystemGroupDataServices $groupDataService */
  478. $groupDataService = app()->make(SystemGroupDataServices::class);
  479. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  480. $today = strtotime(date('Y-m-d'));
  481. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  482. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  483. //获取秒杀商品状态
  484. if ($storeInfo['status'] == 1) {
  485. if ($storeInfo['start_time'] > time()) {
  486. $storeInfo['status'] = 2;
  487. } elseif ($storeInfo['stop_time'] < time()) {
  488. $storeInfo['status'] = 0;
  489. } else {
  490. /** @var SystemGroupDataServices $systemGroupDataService */
  491. $systemGroupDataService = app()->make(SystemGroupDataServices::class);
  492. $seckillTime = array_column($systemGroupDataService->getConfigNameValue('routine_seckill_time'), null, 'id');
  493. $config = $seckillTime[$storeInfo['time_id']] ?? false;
  494. if (!$config) {
  495. throw new ApiException(410322);
  496. }
  497. $now_hour = date('H', time());
  498. $start_hour = $config['time'];
  499. $end_hour = (int)$start_hour + (int)$config['continued'];
  500. if ($start_hour <= $now_hour && $end_hour > $now_hour) {
  501. $storeInfo['status'] = 1;
  502. } else if ($start_hour > $now_hour) {
  503. $storeInfo['status'] = 2;
  504. } else {
  505. $storeInfo['status'] = 0;
  506. }
  507. }
  508. } else {
  509. $storeInfo['status'] == 0;
  510. }
  511. /** @var SystemGroupDataServices $groupDataService */
  512. $groupDataService = app()->make(SystemGroupDataServices::class);
  513. $timeInfo = json_decode($groupDataService->value(['id' => $storeInfo['time_id']], 'value'), true);
  514. $today = strtotime(date('Y-m-d'));
  515. $activityEndHour = $timeInfo['time']['value'] + $timeInfo['continued']['value'];
  516. $storeInfo['last_time'] = (int)bcadd((string)$today, (string)bcmul((string)$activityEndHour, '3600', 0));
  517. //商品详情
  518. $data['storeInfo'] = get_thumb_water($storeInfo, 'big', ['image', 'images']);
  519. $storeInfoNew = get_thumb_water($storeInfo, 'small');
  520. $data['storeInfo']['small_image'] = $storeInfoNew['image'];
  521. /** @var StoreProductReplyServices $storeProductReplyService */
  522. $storeProductReplyService = app()->make(StoreProductReplyServices::class);
  523. $data['reply'] = get_thumb_water($storeProductReplyService->getRecProductReply($storeInfo['product_id']), 'small', ['pics']);
  524. [$replyCount, $goodReply, $replyChance] = $storeProductReplyService->getProductReplyData((int)$storeInfo['product_id']);
  525. $data['replyChance'] = $replyChance;
  526. $data['replyCount'] = $replyCount;
  527. /** @var StoreProductAttrServices $storeProductAttrServices */
  528. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  529. list($productAttr, $productValue) = $storeProductAttrServices->getProductAttrDetail($id, $uid, 0, 1, $storeInfo['product_id']);
  530. $data['productAttr'] = $productAttr;
  531. $data['productValue'] = $productValue;
  532. $data['routine_contact_type'] = sys_config('routine_contact_type', 0);
  533. //用户访问事件
  534. event('user.userVisit', [$uid, $id, 'seckill', $storeInfo['product_id'], 'view']);
  535. //浏览记录
  536. ProductLogJob::dispatch(['visit', ['uid' => $uid, 'product_id' => $storeInfo['product_id']]]);
  537. return $data;
  538. }
  539. /**
  540. * 获取秒杀数据
  541. * @param array $ids
  542. * @param string $field
  543. * @return array
  544. * @throws \think\db\exception\DataNotFoundException
  545. * @throws \think\db\exception\DbException
  546. * @throws \think\db\exception\ModelNotFoundException
  547. */
  548. public function getSeckillColumn(array $ids, string $field = '')
  549. {
  550. $seckillProduct = $systemGroupData = [];
  551. $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';
  552. if (!empty($seckill_ids)) {
  553. $seckillProduct = $this->dao->idSeckillList($ids, $field ?: $seckillInfoField);
  554. if (!empty($seckillProduct)) {
  555. $timeIds = Arr::getUniqueKey($seckillProduct, 'time_id');
  556. $seckillProduct = array_combine(array_column($seckillProduct, 'id'), $seckillProduct);
  557. /** @var SystemGroupDataServices $groupServices */
  558. $groupServices = app()->make(SystemGroupDataServices::class);
  559. $systemGroupData = $groupServices->getGroupDataColumn($timeIds);
  560. }
  561. }
  562. return [$seckillProduct, $systemGroupData];
  563. }
  564. /**
  565. * 秒杀库存添加入redis的队列中
  566. * @param string $unique sku唯一值
  567. * @param int $type 类型
  568. * @param int $number 库存个数
  569. * @param bool $isPush 是否放入之前删除当前队列
  570. * @return bool|int
  571. */
  572. public function pushSeckillStock(string $unique, int $type, int $number, bool $isPush = false)
  573. {
  574. $name = 'seckill_' . $unique . '_' . $type;
  575. /** @var CacheService $cache */
  576. $cache = app()->make(CacheService::class);
  577. $res = true;
  578. if (!$isPush) {
  579. $cache->del($name);
  580. }
  581. for ($i = 1; $i <= $number; $i++) {
  582. $res = $res && $cache->lPush($name, $i);
  583. }
  584. return $res;
  585. }
  586. /**
  587. * @param int $productId
  588. * @param string $unique
  589. * @param int $cartNum
  590. * @param string $value
  591. */
  592. public function checkSeckillStock(int $uid, int $seckillId, int $cartNum = 1, string $unique = '')
  593. {
  594. /** @var StoreProductAttrValueServices $attrValueServices */
  595. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  596. if ($unique == '') {
  597. $unique = $attrValueServices->value(['product_id' => $seckillId, 'type' => 1], 'unique');
  598. }
  599. //检查商品活动状态
  600. $StoreSeckillinfo = $this->getSeckillCount($seckillId, '*,title as store_name');
  601. if ($StoreSeckillinfo['once_num'] < $cartNum) {
  602. throw new ApiException(410313, ['num' => $StoreSeckillinfo['once_num']]);
  603. }
  604. /** @var StoreOrderServices $orderServices */
  605. $orderServices = app()->make(StoreOrderServices::class);
  606. $userBuyCount = $orderServices->getBuyCount($uid, 'seckill_id', $seckillId);
  607. if ($StoreSeckillinfo['num'] < ($userBuyCount + $cartNum)) {
  608. throw new ApiException(410298, ['num' => $StoreSeckillinfo['num']]);
  609. }
  610. if ($StoreSeckillinfo['num'] < $cartNum) {
  611. throw new ApiException(410317, ['num' => $StoreSeckillinfo['num']]);
  612. }
  613. $attrInfo = $attrValueServices->getOne(['product_id' => $seckillId, 'unique' => $unique, 'type' => 1]);
  614. if (!$attrInfo || $attrInfo['product_id'] != $seckillId) {
  615. throw new ApiException(410305);
  616. }
  617. if ($cartNum > $attrInfo['quota']) {
  618. throw new ApiException(410296);
  619. }
  620. return [$attrInfo, $unique, $StoreSeckillinfo];
  621. }
  622. /**
  623. * 弹出redis队列中的库存条数
  624. * @param string $unique
  625. * @param int $type
  626. * @return mixed
  627. */
  628. public function popSeckillStock(string $unique, int $type, int $number = 1)
  629. {
  630. $name = 'seckill_' . $unique . '_' . $type;
  631. /** @var CacheService $cache */
  632. $cache = app()->make(CacheService::class);
  633. if ($number > $cache->lLen($name)) {
  634. return false;
  635. }
  636. $res = true;
  637. for ($i = 1; $i <= $number; $i++) {
  638. $res = $res && $cache->lPop($name);
  639. }
  640. return $res;
  641. }
  642. /**
  643. * 是否有库存
  644. * @param string $unique
  645. * @param int $type
  646. * @return mixed
  647. * @throws \Psr\SimpleCache\InvalidArgumentException
  648. */
  649. public function isSeckillStock(string $unique, int $type, int $number)
  650. {
  651. /** @var CacheService $cache */
  652. $cache = app()->make(CacheService::class);
  653. return $cache->redisHandler()->lLen('seckill_' . $unique . '_' . $type) >= $number;
  654. }
  655. /**
  656. * 回滚库存
  657. * @param array $cartInfo
  658. * @param int $number
  659. * @return bool
  660. */
  661. public function rollBackStock(array $cartInfo)
  662. {
  663. $res = true;
  664. foreach ($cartInfo as $item) {
  665. $value = $item['cart_info'];
  666. if ($value['seckill_id']) {
  667. $res = $res && $this->pushSeckillStock($value['product_attr_unique'], 1, (int)$value['cart_num'], true);
  668. }
  669. }
  670. return $res;
  671. }
  672. /**
  673. * 占用库存
  674. * @param $cartInfo
  675. */
  676. public function occupySeckillStock($cartInfo, $key, $time = 0)
  677. {
  678. //占用库存
  679. if ($cartInfo) {
  680. if (!$time) {
  681. $time = time() + 600;
  682. }
  683. foreach ($cartInfo as $val) {
  684. if ($val['seckill_id']) {
  685. $this->setSeckillStock($val['product_id'], $val['product_attr_unique'], $time, $key, (int)$val['cart_num']);
  686. }
  687. }
  688. }
  689. return true;
  690. }
  691. /**
  692. * 取消秒杀占用的库存
  693. * @param array $cartInfo
  694. * @param string $key
  695. * @return bool
  696. */
  697. public function cancelOccupySeckillStock(array $cartInfo, string $key)
  698. {
  699. if ($cartInfo) {
  700. foreach ($cartInfo as $val) {
  701. if (isset($val['seckill_id']) && $val['seckill_id']) {
  702. $this->backSeckillStock((int)$val['product_id'], $val['product_attr_unique'], $key, (int)$val['cart_num']);
  703. }
  704. }
  705. }
  706. return true;
  707. }
  708. /**
  709. * 存入当前秒杀商品属性有序集合
  710. * @param $product_id
  711. * @param $unique
  712. * @param $score
  713. * @param $value
  714. * @param int $cart_num
  715. * @return bool
  716. */
  717. public function setSeckillStock($product_id, $unique, $score, $value, $cart_num = 1)
  718. {
  719. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  720. $i = 0;
  721. for ($i; $i < $cart_num; $i++) {
  722. CacheService::zAdd($set_key, $score, $value . $i);
  723. }
  724. return true;
  725. }
  726. /**
  727. * 取消集合中的秒杀商品
  728. * @param int $product_id
  729. * @param string $unique
  730. * @param $value
  731. * @param int $cart_num
  732. * @return bool
  733. */
  734. public function backSeckillStock(int $product_id, string $unique, $value, int $cart_num = 1)
  735. {
  736. $set_key = md5('seckill_set_attr_stock_' . $product_id . '_' . $unique);
  737. $i = 0;
  738. for ($i; $i < $cart_num; $i++) {
  739. CacheService::zRem($set_key, $value . $i);
  740. }
  741. return true;
  742. }
  743. /**
  744. * 修改秒杀库存
  745. * @param int $num
  746. * @param int $seckillId
  747. * @return bool
  748. */
  749. public function decSeckillStock(int $num, int $seckillId, string $unique = '')
  750. {
  751. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  752. if ($unique) {
  753. /** @var StoreProductAttrValueServices $skuValueServices */
  754. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  755. //减去秒杀商品的sku库存增加销量
  756. $res = false !== $skuValueServices->decProductAttrStock($seckillId, $unique, $num, 1);
  757. //减去秒杀库存
  758. $res = $res && $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  759. //减去当前普通商品sku的库存增加销量
  760. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId, 'type' => 1], 'suk');
  761. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id, 'type' => 0], 'unique');
  762. if ($productUnique) {
  763. $res = $res && $skuValueServices->decProductAttrStock($product_id, $productUnique, $num);
  764. }
  765. } else {
  766. $res = false !== $this->dao->decStockIncSales(['id' => $seckillId, 'type' => 1], $num);
  767. }
  768. /** @var StoreProductServices $services */
  769. $services = app()->make(StoreProductServices::class);
  770. //减去普通商品库存
  771. return $res && $services->decProductStock($num, $product_id);
  772. }
  773. /**
  774. * 加库存减销量
  775. * @param int $num
  776. * @param int $seckillId
  777. * @param string $unique
  778. * @return bool
  779. */
  780. public function incSeckillStock(int $num, int $seckillId, string $unique = '')
  781. {
  782. $product_id = $this->dao->value(['id' => $seckillId], 'product_id');
  783. if ($unique) {
  784. /** @var StoreProductAttrValueServices $skuValueServices */
  785. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  786. //减去秒杀商品的sku库存增加销量
  787. $res = false !== $skuValueServices->incProductAttrStock($seckillId, $unique, $num, 1);
  788. //减去秒杀库存
  789. $res = $res && $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  790. //减去当前普通商品sku的库存增加销量
  791. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $seckillId], 'suk');
  792. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  793. if ($productUnique) {
  794. $res = $res && $skuValueServices->incProductAttrStock($product_id, $productUnique, $num);
  795. }
  796. } else {
  797. $res = false !== $this->dao->incStockDecSales(['id' => $seckillId, 'type' => 1], $num);
  798. }
  799. /** @var StoreProductServices $services */
  800. $services = app()->make(StoreProductServices::class);
  801. //减去普通商品库存
  802. $res = $res && $services->incProductStock($num, $product_id);
  803. return $res;
  804. }
  805. /**
  806. * 获取一条秒杀商品
  807. * @param $id
  808. * @param string $field
  809. * @return array|false|\PDOStatement|string|\think\Model
  810. */
  811. public function getValidProduct($id, $field = '*')
  812. {
  813. return $this->dao->validProduct($id, $field);
  814. }
  815. /**
  816. * 秒杀统计
  817. * @return array
  818. */
  819. public function seckillStatistics($id)
  820. {
  821. /** @var StoreOrderServices $orderServices */
  822. $orderServices = app()->make(StoreOrderServices::class);
  823. $pay_count = $orderServices->getDistinctCount([['seckill_id', '=', $id], ['paid', '=', 1]], 'uid', false);
  824. $order_count = $orderServices->getDistinctCount([['seckill_id', '=', $id]], 'uid', false);
  825. $all_price = $orderServices->sum([['seckill_id', '=', $id], ['refund_type', 'in', [0, 3]]], 'pay_price');
  826. $seckillInfo = $this->dao->get($id);
  827. $pay_rate = $seckillInfo['quota'] . '/' . $seckillInfo['quota_show'];
  828. return compact('pay_count', 'order_count', 'all_price', 'pay_rate');
  829. }
  830. /**
  831. * 秒杀参与人统计
  832. * @param $id
  833. * @param string $keyword
  834. * @return array
  835. */
  836. public function seckillPeople($id, $keyword = '')
  837. {
  838. /** @var StoreOrderServices $orderServices */
  839. $orderServices = app()->make(StoreOrderServices::class);
  840. [$page, $limit] = $this->getPageValue();
  841. $list = $orderServices->seckillPeople($id, $keyword, $page, $limit);
  842. $count = $orderServices->getDistinctCount([['seckill_id', '=', $id], ['real_name|uid|user_phone', 'like', '%' . $keyword . '%']], 'uid', false);
  843. foreach ($list as &$item) {
  844. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  845. }
  846. return compact('list', 'count');
  847. }
  848. /**
  849. * 秒杀订单统计
  850. * @param $id
  851. * @param array $where
  852. * @return array
  853. */
  854. public function seckillOrder($id, $where = [])
  855. {
  856. /** @var StoreOrderServices $orderServices */
  857. $orderServices = app()->make(StoreOrderServices::class);
  858. [$page, $limit] = $this->getPageValue();
  859. $list = $orderServices->seckillOrder($id, $where, $page, $limit);
  860. $where['seckill_id'] = $id;
  861. $count = $orderServices->count($where);
  862. foreach ($list as &$item) {
  863. if ($item['status'] == 0) {
  864. if ($item['paid'] == 0) {
  865. $item['status'] = '未支付';
  866. } else {
  867. $item['status'] = '未发货';
  868. }
  869. } elseif ($item['status'] == 1) {
  870. $item['status'] = '待收货';
  871. } elseif ($item['status'] == 2) {
  872. $item['status'] = '待评价';
  873. } elseif ($item['status'] == 3) {
  874. $item['status'] = '已完成';
  875. } elseif ($item['status'] == -2) {
  876. $item['status'] = '已退款';
  877. } else {
  878. $item['status'] = '未知';
  879. }
  880. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  881. $item['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
  882. }
  883. return compact('list', 'count');
  884. }
  885. }