Flash.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2020/2/9
  6. * Time: 6:18 PM
  7. */
  8. namespace addons\unishop\controller;
  9. use addons\unishop\extend\Hashids;
  10. use addons\unishop\extend\Redis;
  11. use addons\unishop\model\Address as AddressModel;
  12. use addons\unishop\model\Area;
  13. use addons\unishop\model\Config;
  14. use addons\unishop\model\DeliveryRule as DeliveryRuleModel;
  15. use addons\unishop\model\Evaluate;
  16. use addons\unishop\model\FlashProduct;
  17. use addons\unishop\model\FlashSale;
  18. use addons\unishop\model\Product;
  19. use think\Db;
  20. use think\Exception;
  21. use think\Hook;
  22. use think\Loader;
  23. /**
  24. * 秒杀
  25. */
  26. class Flash extends Base
  27. {
  28. protected $noNeedLogin = ['index', 'navbar', 'product', 'productDetail'];
  29. public function _initialize()
  30. {
  31. parent::_initialize();
  32. }
  33. /**
  34. * @ApiTitle (首页秒杀信息)
  35. * @ApiSummary (首页秒杀信息)
  36. * @ApiMethod (POST)
  37. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  38. * @ApiReturn ({"code":1,"msg":"","data":[]})
  39. *
  40. * @ApiReturnParams (name="title", type="string", description="当前秒杀活动标题")
  41. * @ApiReturnParams (name="introdution", type="string", description="当前秒杀活动简介")
  42. * @ApiReturnParams (name="product.name", type="string", description="商品图片")
  43. * @ApiReturnParams (name="product.title", type="string", description="商品标题")
  44. * @ApiReturnParams (name="product.sales_price", type="string", description="商品价钱")
  45. * @ApiReturnParams (name="product.flash_product_id", type="string", description="商品id")
  46. * @ApiReturnParams (name="flash_id", type="string", description="秒杀id")
  47. * @ApiReturnParams (name="starttime_hour", type="string", description="开始时间的所在小时")
  48. * @ApiReturnParams (name="current", type="bool", description="当前展示的秒杀活动是否正在进行中")
  49. * @ApiReturnParams (name="countdown", type="json", description="下一场秒杀活动的时间等信息")
  50. *
  51. */
  52. public function index()
  53. {
  54. $flashSaleModel = new FlashSale();
  55. $hour = strtotime(date('Y-m-d H:00:00'));
  56. $flash = $flashSaleModel
  57. ->where('endtime', '>=', $hour)
  58. ->where([
  59. 'switch' => FlashSale::SWITCH_YES,
  60. 'status' => FlashSale::STATUS_NO,
  61. ])
  62. ->with([
  63. 'product' => function ($query) {
  64. //$query->with('product')->where(['switch' => FlashProduct::SWITCH_ON]);
  65. $query->alias('fp')->join('unishop_product p', 'fp.product_id = p.id')
  66. ->field('fp.id,fp.flash_id,fp.product_id,p.image,p.title,p.sales_price')
  67. ->where([
  68. 'fp.switch' => FlashProduct::SWITCH_ON,
  69. 'p.deletetime' => NULL
  70. ]);
  71. }
  72. ])
  73. ->order('starttime ASC')
  74. ->find();
  75. if ($flash) {
  76. $flash = $flash->toArray();
  77. foreach ($flash['product'] as &$product) {
  78. $product['image'] = Config::getImagesFullUrl($product['image']);
  79. }
  80. // 寻找下一场的倒计时
  81. $nextFlash = $flashSaleModel
  82. ->where('starttime', '>', $hour)
  83. ->where([
  84. 'switch' => FlashSale::SWITCH_YES,
  85. 'status' => FlashSale::STATUS_NO,
  86. ])
  87. ->order("starttime ASC")
  88. ->cache(10)
  89. ->find();
  90. $flash['starttime'] = $nextFlash['starttime'];
  91. $flash['countdown'] = FlashSale::countdown($flash['starttime']);
  92. }
  93. $this->success('', $flash);
  94. }
  95. /**
  96. * @ApiTitle (获取秒杀时间段)
  97. * @ApiSummary (获取秒杀时间段)
  98. * @ApiMethod (POST)
  99. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  100. * @ApiReturn ({"code":1,"msg":"","data":[]})
  101. *
  102. * @ApiReturnParams (name="title", type="string", description="当前秒杀活动标题")
  103. * @ApiReturnParams (name="introdution", type="string", description="当前秒杀活动简介")、
  104. * @ApiReturnParams (name="flash_id", type="string", description="秒杀id")
  105. * @ApiReturnParams (name="starttime_hour", type="string", description="开始时间的所在小时")
  106. * @ApiReturnParams (name="current", type="bool", description="是否进行中")
  107. *
  108. */
  109. public function navbar()
  110. {
  111. $flashSaleModel = new FlashSale();
  112. $flash = $flashSaleModel
  113. ->where('endtime', '>', time())
  114. ->where([
  115. 'switch' => FlashSale::SWITCH_YES,
  116. 'status' => FlashSale::STATUS_NO
  117. ])
  118. ->field('id,starttime,title,introdution,endtime')
  119. ->order('starttime ASC')
  120. ->cache(2)
  121. ->select();
  122. $this->success('', $flash);
  123. }
  124. /**
  125. * @ApiTitle (获取秒杀的产品列表)
  126. * @ApiSummary (获取秒杀的产品列表)
  127. * @ApiMethod (POST)
  128. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  129. * @ApiParams (name="flash_id", type=string, required=true, description="秒杀活动id")
  130. * @ApiParams (name=page, type=integer, required=true, description="第几页")
  131. * @ApiParams (name=pagesize, type=integer, required=true, description="每页展示数量")
  132. * @ApiReturn ({"code":1,"msg":"","data":[]})
  133. *
  134. * @ApiReturnParams (name="number", type="integer", description="秒杀数量")
  135. * @ApiReturnParams (name="introduction", type="string", description="秒杀简介")
  136. * @ApiReturnParams (name="sold", type="integer", description="已售数量")
  137. * @ApiReturnParams (name="product.title", type="integer", description="商品名称")
  138. * @ApiReturnParams (name="product.sales_price", type="integer", description="销售价钱")
  139. * @ApiReturnParams (name="product.market_price", type="integer", description="市场价钱")
  140. * @ApiReturnParams (name="product.image", type="integer", description="商品图片")
  141. * @ApiReturnParams (name="product.product_id", type="integer", description="商品id")
  142. * @ApiReturnParams (name="flash_product_id", type="integer", description="秒杀商品id")
  143. *
  144. */
  145. public function product()
  146. {
  147. $flash_id = $this->request->request('flash_id', 0);
  148. $page = $this->request->request('page', 1);
  149. $pagesize = $this->request->request('pagesize', 15);
  150. $flash_id = Hashids::decodeHex($flash_id);
  151. $productModel = new FlashProduct();
  152. $products = $productModel
  153. ->with('product')
  154. ->where(['flash_id' => $flash_id, 'switch' => FlashProduct::SWITCH_ON])
  155. ->limit(($page - 1) * $pagesize, $pagesize)
  156. ->cache(2)
  157. ->select();
  158. foreach ($products as &$product) {
  159. $product['sold'] = $product['sold'] > $product['number'] ? $product['number'] : $product['sold'];
  160. }
  161. $this->success('', $products);
  162. }
  163. /**
  164. * @ApiTitle (获取秒杀产品)
  165. * @ApiSummary (获取秒杀产品数据)
  166. * @ApiMethod (GET)
  167. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  168. * @ApiParams (name="flash_id", type=string, required=true, description="秒杀活动id")
  169. * @ApiParams (name="id", type=string, required=true, description="商品id")
  170. * @ApiReturn ({"code":1,"msg":"","data":{}})
  171. *
  172. * @ApiReturnParams (name="category_id", type="integer", description="分类id")
  173. * @ApiReturnParams (name="title", type="string", description="商品名称")
  174. * @ApiReturnParams (name="image", type="string", description="商品图片")
  175. * @ApiReturnParams (name="images_text", type="array", description="商品图片组")
  176. * @ApiReturnParams (name="desc", type="string", description="商品详情")
  177. * @ApiReturnParams (name="sales", type="integer", description="销量")
  178. * @ApiReturnParams (name="sales_price", type="string", description="销售价钱")
  179. * @ApiReturnParams (name="market_price", type="string", description="市场价钱")
  180. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  181. * @ApiReturnParams (name="stock", type="integer", description="库存")
  182. * @ApiReturnParams (name="look", type="integer", description="观看量")
  183. * @ApiReturnParams (name="use_spec", type="integer", description="是否使用规格")
  184. * @ApiReturnParams (name="server", type="string", description="支持的服务")
  185. * @ApiReturnParams (name="favorite", type="integer", description="是否已收藏")
  186. * @ApiReturnParams (name="evaluate_data", type="json", description="{count:'评论数据',avg:'好评平均值'}")
  187. * @ApiReturnParams (name="coupon", type="array", description="可用优惠券")
  188. * @ApiReturnParams (name="cart_num", type="integer", description="购物车数量")
  189. * @ApiReturnParams (name="spec_list", type="array", description="规格键值数据")
  190. * @ApiReturnParams (name="spec_table_list", type="array", description="规格值数据")
  191. * @ApiReturnParams (name="flash.starttime", type="string", description="秒杀开始时间")
  192. * @ApiReturnParams (name="flash.endtime", type="string", description="秒杀结束时间")
  193. * @ApiReturnParams (name="flash.sold", type="string", description="秒杀商品已售数量")
  194. * @ApiReturnParams (name="flash.number", type="string", description="提供秒杀商品数量")
  195. * @ApiReturnParams (name="flash.text", type="string", description="倒计时时态描述")
  196. * @ApiReturnParams (name="flash.countdown", type="string", description="倒计时")
  197. * @ApiReturnParams (name="flash.countdown.day", type="string", description="天")
  198. * @ApiReturnParams (name="flash.countdown.hour", type="string", description="时")
  199. * @ApiReturnParams (name="flash.countdown.minute", type="string", description="分")
  200. * @ApiReturnParams (name="flash.countdown.second", type="string", description="秒")
  201. *
  202. */
  203. public function productDetail()
  204. {
  205. $productId = $this->request->get('id');
  206. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  207. $flashId = $this->request->get('flash_id');
  208. $flashId = \addons\unishop\extend\Hashids::decodeHex($flashId);
  209. try {
  210. $productModel = new Product();
  211. $data = $productModel->where(['id' => $productId])->cache(true, 20, 'flashProduct')->find();
  212. if (!$data) {
  213. $this->error(__('Product not exist'));
  214. }
  215. // 真实浏览量加一
  216. $data->real_look++;
  217. $data->look++;
  218. $data->save();
  219. //服务
  220. $server = explode(',', $data->server);
  221. $configServer = json_decode(Config::getByName('server')['value'],true);
  222. $serverValue = [];
  223. foreach ($server as $k => $v) {
  224. if (isset($configServer[$v])) {
  225. $serverValue[] = $configServer[$v];
  226. }
  227. }
  228. $data->server = count($serverValue) ? implode(' · ', $serverValue) : '';
  229. // 默认没有收藏
  230. $data->favorite = false;
  231. // 评价
  232. $data['evaluate_data'] = (new Evaluate)->where(['product_id' => $productId])
  233. ->field('COUNT(*) as count, IFNULL(CEIL(AVG(rate)/5*100),0) as avg')
  234. ->cache(true, 20, 'flashEvaluate')->find();
  235. $redis = new Redis();
  236. $flash['starttime'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'starttime');
  237. $flash['endtime'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'endtime');
  238. $flash['sold'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'sold');
  239. $flash['number'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'number');
  240. $flash['sold'] = $flash['sold'] > $flash['number'] ? $flash['number'] : $flash['sold'];
  241. $flash['text'] = $flash['starttime'] > time() ? '距开始:' : '距结束:';
  242. // 秒杀类型不加载优惠券、促销活动、是否已收藏、评价等等,会影响返回速度
  243. $targetTime = $flash['starttime'] > time() ? $flash['starttime'] : $flash['endtime'];
  244. $flash['countdown'] = FlashSale::countdown($targetTime);
  245. $data['coupon'] = [];
  246. // 秒杀数据
  247. $data['flash'] = $flash;
  248. $data->append(['images_text', 'spec_list', 'spec_table_list'])->toArray();
  249. // 购物车数量
  250. $data['cart_num'] = (new \addons\unishop\model\Cart)->where(['user_id' => $this->auth->id])->count();
  251. } catch (Exception $e) {
  252. $this->error($e->getMessage());
  253. }
  254. $this->success('', $data);
  255. }
  256. /**
  257. * @ApiTitle (创建订单)
  258. * @ApiSummary (创建订单)
  259. * @ApiMethod (POST)
  260. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  261. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  262. * @ApiParams (name="flash_id", type=string, required=true, description="秒杀活动id")
  263. * @ApiParams (name="id", type=string, required=true, description="商品id")
  264. * @ApiReturn ({"code":1,"msg":"","data":{}})
  265. *
  266. * @ApiReturnParams (name="product.title", type="string", description="商品名称")
  267. * @ApiReturnParams (name="product.image", type="string", description="商品图片")
  268. * @ApiReturnParams (name="product.sales", type="integer", description="销量")
  269. * @ApiReturnParams (name="product.sales_price", type="string", description="销售价钱")
  270. * @ApiReturnParams (name="product.market_price", type="string", description="市场价钱")
  271. * @ApiReturnParams (name="product.id", type="string", description="商品id")
  272. * @ApiReturnParams (name="product.stock", type="integer", description="库存")
  273. * @ApiReturnParams (name="product.spec", type="integer", description="选中的规格")
  274. * @ApiReturnParams (name="product.number", type="integer", description="购买数量")
  275. *
  276. * @ApiReturnParams (name="address.id", type="integer", description="地址id")
  277. * @ApiReturnParams (name="address.name", type="string", description="收货人名称")
  278. * @ApiReturnParams (name="address.mobile", type="string", description="收货人电话")
  279. * @ApiReturnParams (name="address.address", type="string", description="收货人地址")
  280. * @ApiReturnParams (name="address.province_id", type="integer", description="省份id")
  281. * @ApiReturnParams (name="address.city_id", type="integer", description="城市id")
  282. * @ApiReturnParams (name="address.area_id", type="integer", description="地区id")
  283. * @ApiReturnParams (name="address.is_default", type="integer", description="是否默认")
  284. * @ApiReturnParams (name="address.province.name", type="integer", description="省份")
  285. * @ApiReturnParams (name="address.city.name", type="integer", description="城市")
  286. * @ApiReturnParams (name="address.area.name", type="integer", description="地区")
  287. *
  288. * @ApiReturnParams (name="delivery.id", type="integer", description="货运id")
  289. * @ApiReturnParams (name="delivery.name", type="string", description="货运名称")
  290. * @ApiReturnParams (name="delivery.type", type="string", description="收费类型")
  291. * @ApiReturnParams (name="delivery.min", type="integer", description="至少购买量")
  292. * @ApiReturnParams (name="delivery.first", type="integer", description="首重数量")
  293. * @ApiReturnParams (name="delivery.first_fee", type="string", description="首重价钱")
  294. * @ApiReturnParams (name="delivery.additional", type="integer", description="需重数量")
  295. * @ApiReturnParams (name="delivery.additional_fee", type="string", description="需重价钱")
  296. * @ApiReturnParams (name="flash.sold", type="integer", description="已秒数量")
  297. * @ApiReturnParams (name="flash.sold", type="integer", description="还剩数量")
  298. */
  299. public function createOrder()
  300. {
  301. $productId = $this->request->post('id', 0);
  302. $flashId = $this->request->post('flash_id', 0);
  303. $flashId = \addons\unishop\extend\Hashids::decodeHex($flashId);
  304. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  305. try {
  306. $redis = new Redis();
  307. $sold = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'sold');
  308. $number = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'number');
  309. $switch = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'switch');
  310. $starttime = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'starttime');
  311. $endtime = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'endtime');
  312. //判断是否开始或结束
  313. if (time() < $starttime) {
  314. $this->error(__('Activity not started'));
  315. }
  316. if ($endtime < time()) {
  317. $this->error(__('Activity ended'));
  318. }
  319. // 截流
  320. if ($sold >= $number) {
  321. $this->error(__('Item sold out'));
  322. }
  323. if ($switch == FlashSale::SWITCH_NO || $switch == false) {
  324. $this->error(__('Item is off the shelves'));
  325. }
  326. $product = (new Product)->where(['id' => $productId, 'deletetime' => null])->find();
  327. /** 产品基础数据 **/
  328. $spec = $this->request->post('spec', '');
  329. $productData[0] = $product->getDataOnCreateOrder($spec);
  330. if (!$productData) {
  331. $this->error(__('Product not exist'));
  332. }
  333. $productData[0]['image'] = Config::getImagesFullUrl($productData[0]['image']);
  334. $productData[0]['sales_price'] = round($productData[0]['sales_price'], 2);
  335. $productData[0]['market_price'] = round($productData[0]['market_price'], 2);
  336. /** 默认地址 **/
  337. $address = AddressModel::get(['user_id' => $this->auth->id, 'is_default' => AddressModel::IS_DEFAULT_YES]);
  338. if ($address) {
  339. $area = (new Area)->whereIn('id', [$address->province_id, $address->city_id, $address->area_id])->column('name', 'id');
  340. $address = $address->toArray();
  341. $address['province']['name'] = $area[$address['province_id']];
  342. $address['city']['name'] = $area[$address['city_id']];
  343. $address['area']['name'] = $area[$address['area_id']];
  344. }
  345. /** 运费数据 **/
  346. $cityId = $address['city_id'] ? $address['city_id'] : 0;
  347. $delivery = (new DeliveryRuleModel())->getDelivetyByArea($cityId);
  348. $msg = '';
  349. // if ($delivery['status'] == 0) {
  350. // $msg = __('Your receiving address is not within the scope of delivery');
  351. // }
  352. $redis = new Redis();
  353. //$flash['starttime'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'starttime');
  354. //$flash['endtime'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'endtime');
  355. $flash['sold'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'sold');
  356. $flash['number'] = $redis->handler->hGet('flash_sale_' . $flashId . '_' . $productId, 'number');
  357. $flash['sold'] = $flash['sold'] > $flash['number'] ? $flash['number'] : $flash['sold'];
  358. //$flash['text'] = $flash['starttime'] > time() ? '距开始:' : '距结束:';
  359. // 秒杀类型不加载优惠券、促销活动、是否已收藏、评价等等,会影响返回速度
  360. //$targetTime = $flash['starttime'] > time() ? $flash['starttime'] : $flash['endtime'];
  361. //$flash['countdown'] = FlashSale::countdown($targetTime);
  362. } catch (Exception $e) {
  363. $this->error($e->getMessage(), false);
  364. }
  365. $this->success($msg, [
  366. 'product' => $productData,
  367. 'address' => $address,
  368. 'delivery' => $delivery['list'],
  369. 'flash' => $flash
  370. ]);
  371. }
  372. /**
  373. * @ApiTitle (提交订单)
  374. * @ApiSummary (提交订单)
  375. * @ApiMethod (POST)
  376. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  377. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  378. * @ApiParams (name="flash_id", type=string, required=true, description="秒杀活动id")
  379. * @ApiParams (name="product_id", type=string, required=true, description="商品id")
  380. * @ApiParams (name="number", type=string, required=true, description="商品数量")
  381. * @ApiParams (name="city_id", type=integer, required=true, description="城市id")
  382. * @ApiParams (name="address_id", type=string, required=true, description="收货地址id")
  383. * @ApiParams (name="delivery_id", type=integer, required=true, description="运费模板id")
  384. * @ApiParams (name="spec", type=string, required=true, description="规格")
  385. * @ApiParams (name="remark", type=string, required=true, description="备注")
  386. * @ApiReturn ({"code":1,"msg":"","data":{}})
  387. *
  388. * @ApiReturnParams (name="order_id", type="string", description="订单编号")
  389. * @ApiReturnParams (name="out_trade_no", type="string", description="商户订单号(支付用)")
  390. *
  391. */
  392. public function submitOrder()
  393. {
  394. $data = $this->request->post();
  395. try {
  396. $validate = Loader::validate('\\addons\\unishop\\validate\\Order');
  397. if (!$validate->check($data, [], 'submitFlash')) {
  398. throw new Exception($validate->getError());
  399. }
  400. Db::startTrans();
  401. // 判断创建订单的条件
  402. if (empty(Hook::get('create_order_before'))) { // 由于自动化测试的时候会注册多个同名行为
  403. Hook::add('create_order_before', 'addons\\unishop\\behavior\\OrderFlash');
  404. }
  405. if (empty(Hook::get('create_order_after'))) {
  406. Hook::add('create_order_after', 'addons\\unishop\\behavior\\OrderFlash');
  407. }
  408. $data['flash_id'] = Hashids::decodeHex($data['flash_id']);
  409. $data['product_id'] = Hashids::decodeHex($data['product_id']);
  410. $orderModel = new \addons\unishop\model\Order();
  411. $result = $orderModel->createOrder($this->auth->id, $data);
  412. Db::commit();
  413. $this->success('', $result);
  414. } catch (Exception $e) {
  415. Db::rollback();
  416. $this->error($e->getMessage(), false);
  417. }
  418. }
  419. }