CouponPacketController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. <?php
  2. namespace app\admin\controller\coupon;
  3. use app\admin\service\coupon\CouponDetailService;
  4. use app\admin\service\coupon\CouponService;
  5. use app\admin\validate\coupon\CouponValidate;
  6. use app\admin\validate\device\DeviceValidate;
  7. use app\controller\Curd;
  8. use app\model\Coupon;
  9. use app\model\CouponDetail;
  10. use app\model\CouponGoods;
  11. use app\model\CouponPacket;
  12. use app\model\CouponPacketSequence;
  13. use app\model\Device;
  14. use app\model\Member;
  15. use app\model\SysDept;
  16. use app\model\SysSerial;
  17. use support\Db;
  18. use support\exception\BusinessException;
  19. use support\Request;
  20. use support\Response;
  21. use Tinywan\Jwt\JwtToken;
  22. class CouponPacketController extends Curd
  23. {
  24. public function __construct()
  25. {
  26. $this->model = new CouponPacket();
  27. }
  28. /**
  29. * @Desc 列表
  30. * @Author Gorden
  31. * @Date 2024/3/28 15:01
  32. *
  33. * @param Request $request
  34. * @return Response
  35. * @throws \support\exception\BusinessException
  36. */
  37. public function select(Request $request): Response
  38. {
  39. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  40. if (!empty($where['coupon_packet_addtimes'])) {
  41. $where['coupon_packet_addtimes'][0] = strtotime($where['coupon_packet_addtimes'][0]);
  42. $where['coupon_packet_addtimes'][1] = strtotime($where['coupon_packet_addtimes'][1]);
  43. }
  44. $order = $request->get('order', 'desc');
  45. $field = $field ?? 'coupon_packet_addtimes';
  46. $query = $this->doSelect($where, $field, $order);
  47. return $this->doFormat($query, $format, $limit);
  48. }
  49. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  50. {
  51. $model = $this->model->with([
  52. 'category' => function ($query) {
  53. $query->select('category_id', 'category_name');
  54. },
  55. 'user',
  56. 'dept'
  57. // 'detail'
  58. ]);
  59. foreach ($where as $column => $value) {
  60. if (is_array($value)) {
  61. if ($value[0] === 'like' || $value[0] === 'not like') {
  62. $model = $model->where($column, $value[0], "%$value[1]%");
  63. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  64. $model = $model->where($column, $value[0], $value[1]);
  65. } elseif ($value[0] == 'in' && !empty($value[1])) {
  66. $valArr = $value[1];
  67. if (is_string($value[1])) {
  68. $valArr = explode(",", trim($value[1]));
  69. }
  70. $model = $model->whereIn($column, $valArr);
  71. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  72. $valArr = $value[1];
  73. if (is_string($value[1])) {
  74. $valArr = explode(",", trim($value[1]));
  75. }
  76. $model = $model->whereNotIn($column, $valArr);
  77. } elseif ($value[0] == 'null') {
  78. $model = $model->whereNull($column);
  79. } elseif ($value[0] == 'not null') {
  80. $model = $model->whereNotNull($column);
  81. } elseif ($value[0] !== '' || $value[1] !== '') {
  82. $model = $model->whereBetween($column, $value);
  83. }
  84. } else {
  85. $model = $model->where($column, $value);
  86. }
  87. }
  88. if ($field) {
  89. $model = $model->orderBy($field, $order);
  90. }
  91. return $model;
  92. }
  93. protected function afterQuery($items)
  94. {
  95. foreach ($items as &$item) {
  96. if (empty($item['dept'])) {
  97. $item['dept_all'] = [
  98. 'dept_id' => 0,
  99. 'dept_name' => "所有门店"
  100. ];
  101. }
  102. $item['used_total'] = CouponPacketSequence::where('join_sequence_coupon_packet_id',$item['coupon_packet_id'])
  103. ->where('coupon_packet_sequence_status','USED')
  104. ->count();
  105. $item['unused_total'] = $item->coupon_packet_issue_num - $item['used_total'];
  106. }
  107. return $items;
  108. }
  109. public function selectList()
  110. {
  111. $coupons = Coupon::where('coupon_status', 'ACTIVED')
  112. ->select('coupon_id', 'coupon_name')
  113. ->orderBy('coupon_addtimes', 'DESC')
  114. ->get()
  115. ->toArray();
  116. return json_success('', $coupons);
  117. }
  118. // public function afterQuery($items)
  119. // {
  120. // foreach ($items as &$item) {
  121. // $item->coupon_begindate = date('Y-m-d H:i:s', $item->coupon_begindate);
  122. // $item->coupon_enddate = date('Y-m-d H:i:s', $item->coupon_enddate);
  123. // }
  124. //
  125. // return $items;
  126. // }
  127. /**
  128. * @Desc 添加优惠券
  129. * @Author Gorden
  130. * @Date 2024/8/14 15:16
  131. *
  132. * @param Request $request
  133. * @return Response
  134. */
  135. public function insert(Request $request): Response
  136. {
  137. if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
  138. return json_fail($this->validateClass->getError());
  139. }
  140. Db::beginTransaction();
  141. try {
  142. $data = $this->insertInput($request);
  143. $data['join_coupon_packet_user_id'] = JwtToken::getCurrentId();
  144. $data['coupon_packet_status'] = 'PENDING';
  145. $this->doInsert($data);
  146. Db::commit();
  147. return json_success('success');
  148. } catch (BusinessException $customException) {
  149. Db::rollBack();
  150. dump($customException->getMessage());
  151. return json_fail($customException->getMessage());
  152. } catch (\Exception $e) {
  153. Db::rollBack();
  154. dump($e->getMessage());
  155. return json_fail('数据写入失败');
  156. }
  157. }
  158. /**
  159. * @Desc 关联优惠券、产品、规格
  160. * @Author Gorden
  161. * @Date 2024/8/14 14:32
  162. *
  163. * @param $goods
  164. * @param $couponId
  165. * @return void
  166. * @throws BusinessException
  167. */
  168. public function insertCouponGoods($goods, $couponId)
  169. {
  170. try {
  171. foreach ($goods as $good) {
  172. CouponGoods::insert([
  173. 'join_goods_coupon_id' => $couponId,
  174. 'join_coupon_goods_id' => $good['goods_id'],
  175. 'join_coupon_goods_sku_id' => $good['sku_id'],
  176. 'coupon_goods_json' => '[]',
  177. 'coupon_goods_extend_json' => '[]',
  178. 'coupon_goods_addtimes' => time()
  179. ]);
  180. }
  181. } catch (\Exception $e) {
  182. throw new BusinessException("关联产品失败");
  183. }
  184. }
  185. protected function insertInput(Request $request): array
  186. {
  187. $params = $request->post();
  188. $data = $this->inputFilter($params);
  189. $data['coupon_packet_id'] = "CP" . date("ymdH") . random_string(6, 'up');
  190. $coupons = [];
  191. if (!empty($params['coupons'])) {
  192. foreach ($params['coupons'] as $coupon) {
  193. $coupons[$coupon['id']]['num'] = $coupon['nbr'];
  194. }
  195. }
  196. $data['coupon_packet_json'] = json_encode(['coupons' => $coupons]);
  197. dump($data);
  198. return $data;
  199. }
  200. /**
  201. * @Desc 修改优惠券
  202. * @Author Gorden
  203. * @Date 2024/8/14 15:48
  204. *
  205. * @param Request $request
  206. * @return Response
  207. */
  208. public function update(Request $request): Response
  209. {
  210. Db::beginTransaction();
  211. try {
  212. [$id, $data] = $this->updateInput($request);
  213. $this->doUpdate($id, $data);
  214. Db::commit();
  215. return json_success('success');
  216. } catch (BusinessException $e) {
  217. Db::rollBack();
  218. return json_fail($e->getMessage());
  219. } catch (\Exception $e) {
  220. Db::rollBack();
  221. dump($e->getMessage());
  222. return json_fail('数据更新失败');
  223. }
  224. }
  225. protected function updateInput(Request $request): array
  226. {
  227. $params = $request->post();
  228. $primary_key = $this->model->getKeyName();
  229. $id = $request->post($primary_key);
  230. $data = $this->inputFilter($params);
  231. $model = $this->model->find($id);
  232. $coupons = [];
  233. if (!empty($params['coupons'])) {
  234. foreach ($params['coupons'] as $coupon) {
  235. $coupons[$coupon['id']]['num'] = $coupon['nbr'];
  236. }
  237. }
  238. $packetJson = [];
  239. if (!empty($model->coupon_packet_json)) {
  240. $packetJson = json_decode($model->coupon_packet_json, true);
  241. }
  242. $packetJson['coupons'] = $coupons;
  243. $data['coupon_packet_json'] = json_encode($packetJson);
  244. unset($data[$primary_key]);
  245. return [$id, $data];
  246. }
  247. /**
  248. * 优惠券详情
  249. */
  250. public function info(Request $request): Response
  251. {
  252. $packetId = $request->get('packet_id', '');
  253. if (!$packetId) {
  254. return json_fail('参数异常');
  255. }
  256. $packet = CouponPacket::where('coupon_packet_id', $packetId)->first();
  257. if (!$packet) {
  258. return json_fail('数据异常');
  259. }
  260. $coupons = [];
  261. if (!empty($packet->coupon_packet_json)) {
  262. $packetJson = json_decode($packet->coupon_packet_json, true);
  263. if (isset($packetJson['coupons'])) {
  264. $couponIds = array_keys($packetJson['coupons']);
  265. $couponModel = Coupon::whereIn('coupon_id', $couponIds)
  266. ->select('coupon_id', 'coupon_name','coupon_classify','coupon_value','coupon_minimum_limit','coupon_category')
  267. ->get()
  268. ->toArray();
  269. foreach ($couponModel as $coupon) {
  270. foreach ($packetJson['coupons'] as $key => $jsonCoupon) {
  271. if ($coupon['coupon_id'] == $key) {
  272. $coupons[] = [
  273. 'id' => $key,
  274. 'name' => $coupon['coupon_name'],
  275. 'nbr' => $jsonCoupon['num'],
  276. 'classify'=>$coupon['coupon_classify'],
  277. 'info'=>CouponService::couponClassifyInfo($coupon['coupon_classify'],$coupon['coupon_category'],$coupon['coupon_value'],$coupon['coupon_minimum_limit'])
  278. ];
  279. }
  280. }
  281. }
  282. }
  283. }
  284. $data = [
  285. 'coupons' => $coupons
  286. ];
  287. return json_success('', $data);
  288. }
  289. /**
  290. * 删除
  291. * @param Request $request
  292. * @return Response
  293. * @throws BusinessException
  294. */
  295. public function delete(Request $request): Response
  296. {
  297. $ids = $this->deleteInput($request);
  298. Db::beginTransaction();
  299. try {
  300. if (CouponPacket::whereIn('coupon_packet_id', $ids)->where('coupon_packet_status', '=', 'ACTIVED')->exists()) {
  301. throw new BusinessException("有已发行的券包,无法删除");
  302. }
  303. $this->doDelete($ids);
  304. Db::commit();
  305. return json_success('success');
  306. } catch (BusinessException $e) {
  307. Db::rollBack();
  308. return json_fail($e->getMessage());
  309. } catch (\Exception $e) {
  310. dump($e->getMessage());
  311. Db::rollBack();
  312. return json_fail('删除失败');
  313. }
  314. }
  315. /**
  316. * @Desc 红包发行
  317. * @Author Gorden
  318. * @Date 2024/9/12 13:21
  319. *
  320. * @param Request $request
  321. * @return Response
  322. */
  323. public function packetIssue(Request $request)
  324. {
  325. $packetId = $request->post('packet_id');
  326. if (!$packetId) {
  327. return json_fail("参数异常");
  328. }
  329. $packet = CouponPacket::where('coupon_packet_id', $packetId)
  330. ->where('coupon_packet_status', 'PENDING')
  331. ->first();
  332. if (!$packet) {
  333. return json_fail('数据异常');
  334. }
  335. Db::beginTransaction();
  336. try {
  337. // 生成红包记录
  338. $this->generatePacket($packet);
  339. $packet->coupon_packet_status = 'ACTIVED';
  340. $packet->coupon_packet_issue_datetime = date('Y-m-d H:i:s');
  341. $packet->save();
  342. Db::commit();
  343. return json_success("success");
  344. } catch (BusinessException $e) {
  345. Db::rollBack();
  346. return json_fail($e->getMessage());
  347. } catch (\Exception $e) {
  348. Db::rollBack();
  349. dump($e->getMessage());
  350. return json_fail("发行失败");
  351. }
  352. }
  353. private function generatePacket(CouponPacket $couponPacket)
  354. {
  355. try {
  356. $length = $couponPacket->coupon_packet_seq_length;
  357. $prefixLength = strlen($couponPacket->coupon_packet_seq_prefix);
  358. $suffixLength = strlen($couponPacket->coupon_packet_seq_suffix);
  359. $seqBegin = $couponPacket->coupon_packet_seq_begin;
  360. $realLength = $length - $prefixLength - $suffixLength;
  361. $data = [];
  362. for ($i = 0; $i < $couponPacket->coupon_packet_issue_num; $i++) {
  363. if ($seqBegin > 0) {
  364. $seqBegin = $i === 0 ? $seqBegin : $seqBegin + 1;
  365. $data[] = $couponPacket->coupon_packet_seq_prefix . str_pad($seqBegin, $realLength, $couponPacket->coupon_packet_seq_fill, STR_PAD_LEFT) . $couponPacket->coupon_packet_seq_suffix;
  366. } else {
  367. $data[] = $this->generateRandomStr($data, $realLength, $couponPacket->coupon_packet_seq_prefix, $couponPacket->coupon_packet_seq_suffi);
  368. }
  369. }
  370. $chunk = collect($data);
  371. $chunks = $chunk->chunk(100);
  372. foreach ($chunks as $item) {
  373. $insertData = [];
  374. foreach ($item as $k => $value) {
  375. $insertData[$k] = [
  376. 'coupon_packet_sequence_id' => $value,
  377. 'join_sequence_coupon_packet_id' => $couponPacket->coupon_packet_id,
  378. 'coupon_packet_sequence_status' => 'PENDING',
  379. 'coupon_packet_sequence_json' => $couponPacket->coupon_packet_json,
  380. 'coupon_packet_sequence_addtimes' => time()
  381. ];
  382. }
  383. CouponPacketSequence::insert($insertData);
  384. }
  385. } catch (\Exception $e) {
  386. dump($e->getMessage());
  387. throw new BusinessException("发行失败");
  388. }
  389. }
  390. private function generateRandomStr($data, $length, $prefix, $suffix)
  391. {
  392. $str = $prefix . random_string($length, 'up') . $suffix;
  393. if (in_array($str, $data)) {
  394. $this->generateRandomStr($data, $length, $prefix, $suffix);
  395. }
  396. return $str;
  397. }
  398. /**
  399. * @Desc 红包重新发行
  400. * @Author Gorden
  401. * @Date 2024/9/12 13:21
  402. *
  403. * @param Request $request
  404. * @return Response
  405. */
  406. public function packetReIssue(Request $request)
  407. {
  408. $packetId = $request->post('packet_id');
  409. if (!$packetId) {
  410. return json_fail("参数异常");
  411. }
  412. if (CouponPacketSequence::where('join_sequence_coupon_packet_id',$packetId)->where('coupon_packet_sequence_status','USED')->exists()){
  413. return json_fail('已有领取记录,无法重新发行');
  414. }
  415. $packet = CouponPacket::where('coupon_packet_id', $packetId)
  416. ->where('coupon_packet_status', 'ACTIVED')
  417. ->first();
  418. if (!$packet) {
  419. return json_fail('数据异常');
  420. }
  421. Db::beginTransaction();
  422. try {
  423. // 删除旧的记录
  424. CouponPacketSequence::where('join_sequence_coupon_packet_id',$packetId)->delete();
  425. // 生成红包记录
  426. $this->generatePacket($packet);
  427. $packet->coupon_packet_issue_datetime = date('Y-m-d H:i:s');
  428. $packet->save();
  429. Db::commit();
  430. return json_success("success");
  431. } catch (BusinessException $e) {
  432. Db::rollBack();
  433. return json_fail($e->getMessage());
  434. } catch (\Exception $e) {
  435. Db::rollBack();
  436. return json_fail("发行失败");
  437. }
  438. }
  439. }