StoreSeckillServices.php 43 KB

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