CouponController.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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\Device;
  12. use app\model\Member;
  13. use app\model\SysDept;
  14. use app\model\SysSerial;
  15. use support\Db;
  16. use support\exception\BusinessException;
  17. use support\Log;
  18. use support\Request;
  19. use support\Response;
  20. use Tinywan\Jwt\JwtToken;
  21. class CouponController extends Curd
  22. {
  23. public function __construct()
  24. {
  25. $this->model = new Coupon();
  26. $this->validate = true;
  27. $this->validateClass = new CouponValidate();
  28. }
  29. /**
  30. * @Desc 列表
  31. * @Author Gorden
  32. * @Date 2024/3/28 15:01
  33. *
  34. * @param Request $request
  35. * @return Response
  36. * @throws \support\exception\BusinessException
  37. */
  38. public function select(Request $request): Response
  39. {
  40. $joinCouponCategoryId = $request->get('join_coupon_category_id', []);
  41. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  42. if (!empty($joinCouponCategoryId)) {
  43. $where['join_coupon_category_id'] = ['in', implode(',', $joinCouponCategoryId)];
  44. }
  45. if (!empty($where['coupon_addtimes'])) {
  46. $where['coupon_addtimes'][0] = strtotime($where['coupon_addtimes'][0]);
  47. $where['coupon_addtimes'][1] = strtotime($where['coupon_addtimes'][1]);
  48. }
  49. if (!empty($where['coupon_id'])) {
  50. $where['coupon_id'] = ['like', trim($where['coupon_id'])];
  51. }
  52. $order = $request->get('order', 'desc');
  53. $field = $field ?? 'coupon_addtimes';
  54. $query = $this->doSelect($where, $field, $order);
  55. return $this->doFormat($query, $format, $limit);
  56. }
  57. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  58. {
  59. $model = $this->model->with([
  60. 'category' => function ($query) {
  61. $query->select('category_id', 'category_name');
  62. },
  63. 'user',
  64. 'detail'
  65. ]);
  66. foreach ($where as $column => $value) {
  67. if (is_array($value)) {
  68. if ($value[0] === 'like' || $value[0] === 'not like') {
  69. $model = $model->where($column, $value[0], "%$value[1]%");
  70. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  71. $model = $model->where($column, $value[0], $value[1]);
  72. } elseif ($value[0] == 'in' && !empty($value[1])) {
  73. $valArr = $value[1];
  74. if (is_string($value[1])) {
  75. $valArr = explode(",", trim($value[1]));
  76. }
  77. $model = $model->whereIn($column, $valArr);
  78. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  79. $valArr = $value[1];
  80. if (is_string($value[1])) {
  81. $valArr = explode(",", trim($value[1]));
  82. }
  83. $model = $model->whereNotIn($column, $valArr);
  84. } elseif ($value[0] == 'null') {
  85. $model = $model->whereNull($column);
  86. } elseif ($value[0] == 'not null') {
  87. $model = $model->whereNotNull($column);
  88. } elseif ($value[0] !== '' || $value[1] !== '') {
  89. $model = $model->whereBetween($column, $value);
  90. }
  91. } else {
  92. $model = $model->where($column, $value);
  93. }
  94. }
  95. if ($field) {
  96. $model = $model->orderBy($field, $order);
  97. }
  98. return $model;
  99. }
  100. protected function afterQuery($items)
  101. {
  102. foreach ($items as &$item) {
  103. if (!empty($item['coupon_json'])) {
  104. $couponJson = json_decode($item['coupon_json'], true);
  105. if (isset($couponJson['member'])) {
  106. if (isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  107. $item['coupon_use_member'] = 'member';
  108. $item['memberList'] = $couponJson['member']['list'];
  109. } else if (isset($couponJson['member']['where']) && !empty($couponJson['member']['where'])) {
  110. if (trim($couponJson['member']['where']) == '1' || trim($couponJson['member']['where']) == '') {
  111. $item['coupon_use_member'] = 'all';
  112. } else {
  113. $item['coupon_use_member'] = 'condition';
  114. $where = str_replace('`', '', urldecode($couponJson['member']['where']));
  115. $whereArr = explode('=', $where);
  116. if (isset($whereArr[0]) && trim($whereArr[0]) == 'member_is_vip') {
  117. $item['condition'] = 'is_vip';
  118. } else if (isset($whereArr[0]) && trim($whereArr[0]) == 'member_classify') {
  119. if (isset($whereArr[1]) && str_replace("'", '', trim($whereArr[1])) == 'MEMBER') {
  120. $item['condition'] = 'is_member';
  121. } else if (isset($whereArr[1]) && str_replace("'", '', trim($whereArr[1])) == 'EMPLOY') {
  122. $item['condition'] = 'is_employ';
  123. }
  124. }
  125. }
  126. } else if (!isset($couponJson['member']['where']) || empty($couponJson['member']['where'])) {
  127. $item['coupon_use_member'] = 'all';
  128. }
  129. }
  130. if (isset($couponJson['premises'])) {
  131. $item['premises'] = $couponJson['premises'];
  132. } else {
  133. $item['premises_range'] = 'all';
  134. }
  135. }
  136. if (!empty($item['coupon_period_json'])) {
  137. $periodJson = json_decode($item['coupon_period_json'], true);
  138. $item['period'] = $periodJson['length'] ?? '';
  139. $item['period_unit'] = $periodJson['unit'] ?? '';
  140. $item['period_unit_num'] = $periodJson['val'] ?? '';
  141. $item['period_nbr'] = $periodJson['nbr'] ?? '';
  142. }
  143. if (!empty($item['coupon_validdate_begin']) && !empty($item['coupon_validdate_end'])) {
  144. $item['coupon_use_time'] = 'date';
  145. } elseif ($item['coupon_validdate_day']) {
  146. $item['coupon_use_time'] = 'day';
  147. }
  148. $item['member_count'] = 0;
  149. $item['pending_count'] = 0;
  150. $item['used_count'] = 0;
  151. if (!empty($item['detail'])) {
  152. foreach ($item['detail'] as $detail) {
  153. if (!empty($detail['join_coupon_detail_member_id'])) {
  154. $item['member_count'] += 1;
  155. }
  156. if ($detail['coupon_detail_status'] == 'PENDING') {
  157. $item['pending_count'] += 1;
  158. } elseif ($detail['coupon_detail_status'] == 'USED') {
  159. $item['used_count'] += 1;
  160. }
  161. }
  162. }
  163. $item['coupon_explain'] = CouponService::couponClassifyInfo($item['coupon_classify'], $item['coupon_category'], $item['coupon_value'], $item['coupon_minimum_limit']);
  164. unset($item['detail']);
  165. }
  166. return $items;
  167. }
  168. /**
  169. * @Desc 优惠券顶部统计
  170. * @Author Gorden
  171. * @Date 2024/10/31 16:36
  172. *
  173. * @param Request $request
  174. * @return Response
  175. */
  176. public function statistics(Request $request)
  177. {
  178. $params = $request->get();
  179. $coupons = Coupon::selectRaw('coupon_classify,count(coupon_id) as total')
  180. // ->where('coupon_status', 'ACTIVED')
  181. ->when(!empty($params['coupon_classify']), function ($query) use ($params) {
  182. $query->where('coupon_classify', $params['coupon_classify']);
  183. })
  184. ->when(!empty($params['join_coupon_category_id']), function ($query) use ($params) {
  185. $query->whereIn('join_coupon_category_id', $params['join_coupon_category_id']);
  186. })
  187. ->when(!empty($params['coupon_id']), function ($query) use ($params) {
  188. $query->where('coupon_id', 'like', '%' . trim($params['coupon_id']) . '%');
  189. })
  190. ->when(!empty($params['couponName']), function ($query) use ($params) {
  191. $query->where('coupon_name', 'like', '%' . trim($params['couponName']) . '%');
  192. })
  193. ->when(!empty($params['coupon_addtimes']), function ($query) use ($params) {
  194. $params['coupon_addtimes'][0] = strtotime($params['coupon_addtimes'][0]);
  195. $params['coupon_addtimes'][1] = strtotime($params['coupon_addtimes'][1]);
  196. $query->whereBetween('coupon_addtimes', $params['coupon_addtimes']);
  197. })
  198. ->groupBy('coupon_classify')
  199. ->get()
  200. ->toArray();
  201. $statistics = [];
  202. $statistics['total'] = 0;
  203. foreach ($coupons as $coupon) {
  204. $statistics['total'] += $coupon['total'];
  205. if ($coupon['coupon_classify'] == '季卡') {
  206. $statistics['jika'] = $coupon['total'];
  207. } else if ($coupon['coupon_classify'] == '年卡') {
  208. $statistics['nianka'] = $coupon['total'];
  209. } else if ($coupon['coupon_classify'] == '折扣券') {
  210. $statistics['zhekou'] = $coupon['total'];
  211. } else if ($coupon['coupon_classify'] == '抵用券') {
  212. $statistics['dikou'] = $coupon['total'];
  213. } else if ($coupon['coupon_classify'] == '月卡') {
  214. $statistics['yueka'] = $coupon['total'];
  215. } else if ($coupon['coupon_classify'] == '满减券') {
  216. $statistics['manjian'] = $coupon['total'];
  217. } else if ($coupon['coupon_classify'] == '福利券') {
  218. $statistics['fuli'] = $coupon['total'];
  219. } else if ($coupon['coupon_classify'] == '立减券') {
  220. $statistics['lijian'] = $coupon['total'];
  221. } else if ($coupon['coupon_classify'] == '赠品券') {
  222. $statistics['zengpin'] = $coupon['total'];
  223. }
  224. }
  225. // 领完的券
  226. $couponNumbers = Coupon::where('coupon_number', '>', 0)
  227. ->select('coupon_id', 'coupon_number')
  228. ->get()
  229. ->toArray();
  230. $statistics['done'] = 0;
  231. foreach ($couponNumbers as $item) {
  232. if (CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])->whereIn('coupon_detail_status', ['IN', 'PENDING'])->count('join_detail_coupon_id') >= $item['coupon_number']) {
  233. $statistics['done'] += 1;
  234. }
  235. }
  236. return json_success('success', $statistics);
  237. }
  238. public function selectList()
  239. {
  240. $coupons = Coupon::where('coupon_status', 'ACTIVED')
  241. ->select('coupon_id', 'coupon_name')
  242. ->orderBy('coupon_addtimes', 'DESC')
  243. ->get()
  244. ->toArray();
  245. return json_success('', $coupons);
  246. }
  247. // public function afterQuery($items)
  248. // {
  249. // foreach ($items as &$item) {
  250. // $item->coupon_begindate = date('Y-m-d H:i:s', $item->coupon_begindate);
  251. // $item->coupon_enddate = date('Y-m-d H:i:s', $item->coupon_enddate);
  252. // }
  253. //
  254. // return $items;
  255. // }
  256. /**
  257. * @Desc 添加优惠券
  258. * @Author Gorden
  259. * @Date 2024/8/14 15:16
  260. *
  261. * @param Request $request
  262. * @return Response
  263. */
  264. public function insert(Request $request): Response
  265. {
  266. if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
  267. return json_fail($this->validateClass->getError());
  268. }
  269. $goods = $request->post('goodsContentList', []);
  270. // if (empty($goods)) {
  271. // return json_fail("请选择关联的产品");
  272. // }
  273. Db::beginTransaction();
  274. try {
  275. $data = $this->insertInput($request);
  276. $data['coupon_creator_user_id'] = JwtToken::getCurrentId();
  277. $this->doInsert($data);
  278. // 关联优惠券和商品、规格
  279. $this->insertCouponGoods($goods, $data['coupon_id']);
  280. if ($data['coupon_number'] > 0) {
  281. $this->generateCouponDetail($data['coupon_id'], $data['coupon_status'], $data['coupon_number']);
  282. }
  283. Db::commit();
  284. return json_success('success');
  285. } catch (BusinessException $customException) {
  286. Db::rollBack();
  287. dump($customException->getMessage());
  288. return json_fail($customException->getMessage());
  289. } catch (\Exception $e) {
  290. Db::rollBack();
  291. dump($e->getMessage());
  292. return json_fail('数据写入失败');
  293. }
  294. }
  295. /**
  296. * @Desc 关联优惠券、产品、规格
  297. * @Author Gorden
  298. * @Date 2024/8/14 14:32
  299. *
  300. * @param $goods
  301. * @param $couponId
  302. * @return void
  303. * @throws BusinessException
  304. */
  305. public function insertCouponGoods($goods, $couponId)
  306. {
  307. try {
  308. foreach ($goods as $good) {
  309. CouponGoods::insert([
  310. 'join_goods_coupon_id' => $couponId,
  311. 'join_coupon_goods_id' => $good['goods_id'],
  312. 'join_coupon_goods_sku_id' => $good['sku_id'],
  313. 'coupon_goods_json' => '[]',
  314. 'coupon_goods_extend_json' => '[]',
  315. 'coupon_goods_addtimes' => time()
  316. ]);
  317. }
  318. } catch (\Exception $e) {
  319. throw new BusinessException("关联产品失败");
  320. }
  321. }
  322. protected function insertInput(Request $request): array
  323. {
  324. $params = $request->post();
  325. $data = $this->inputFilter($params);
  326. $data['coupon_id'] = "CU" . date("ymdHi") . random_string(4, 'up');
  327. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  328. $data['coupon_validdate_day'] = 0;
  329. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  330. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  331. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  332. $data['coupon_validdate_begin'] = '';
  333. $data['coupon_validdate_end'] = '';
  334. }
  335. $couponJson = [];
  336. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  337. $couponJson['member']['list'] = $params['member_list'];
  338. $couponJson['member']['range'] = '';
  339. $couponJson['member']['where'] = '';
  340. } else if ($params['coupon_use_member'] == 'condition') {
  341. $couponJson['member']['list'] = [];
  342. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  343. $couponJson['member']['range'] = 'VIP会员';
  344. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  345. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  346. $couponJson['member']['range'] = '公司员工';
  347. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  348. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  349. $couponJson['member']['range'] = '会员';
  350. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  351. }
  352. } else if ($params['coupon_use_member'] == 'all') {
  353. $couponJson['member']['list'] = [];
  354. $couponJson['member']['range'] = '全部会员';
  355. $couponJson['member']['where'] = '';
  356. }
  357. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  358. $couponJson['premises_range'] = '所有门店可用';
  359. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  360. $couponJson['premises'] = $params['premises'];
  361. $couponJson['premises_range'] = '部分门店可用';
  362. }
  363. if (in_array($data['coupon_classify'], ['抵用券', '立减券', '赠品券', '福利券', '年卡', '季卡', '月卡'])) {
  364. $data['coupon_minimum_limit'] = 0;
  365. }
  366. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  367. // 处理周期优惠券
  368. if ($params['coupon_is_period'] != 'N') {
  369. // $this->disposePeriod($params);
  370. $data['coupon_period_json'] = json_encode([
  371. 'length' => $params['period'],
  372. 'unit' => $params['period_unit'],
  373. 'val' => $params['period_unit_num'],
  374. 'nbr' => $params['period_nbr']
  375. ]);
  376. }
  377. return $data;
  378. }
  379. public function disposePeriod($params)
  380. {
  381. if (empty($params['period']) || empty($params['period_unit']) || empty($params['period_unit_num']) || empty($params['period_nbr'])) {
  382. throw new BusinessException("周期数据异常");
  383. }
  384. if ($params['period'] != 'TO_EXPIRE') {
  385. return $params;
  386. }
  387. // if (empty($params['coupon_validdate_end'])) {
  388. // throw new BusinessException("周期数据异常");
  389. // }
  390. try {
  391. $endTimeUnix = strtotime($params['coupon_validdate_end']);
  392. if ($params['period_unit'] == 'day') {
  393. $diff = ceil(($endTimeUnix - time()) / (3600 * 24));
  394. } else if ($params['period_unit'] == 'week') {
  395. $diff = ceil(($endTimeUnix - time()) / (3600 * 24));
  396. $diff = ceil($diff / 7);
  397. } else if ($params['period_unit'] == 'month') {
  398. $endTime = new \DateTime($params['coupon_validdate_end']);
  399. $nowTime = new \DateTime(date('Y-m-d'));
  400. $interval = $nowTime->diff($endTime);
  401. $diff = $interval->y * 12 + $interval->m + 1;
  402. }
  403. if ($params['period_nbr'] != ceil($diff / $params['period_unit_num'])) {
  404. throw new BusinessException("期数设置错误");
  405. }
  406. return $params;
  407. } catch (\Exception $e) {
  408. throw new BusinessException($e->getMessage());
  409. }
  410. }
  411. public function customSend(Request $request)
  412. {
  413. $chooseCoupons = $request->post('chooseCoupons', []);
  414. $couponUseMember = $request->post('coupon_use_member', '');
  415. $memberList = $request->post('member_list', []);
  416. $condition = $request->post('condition', '');
  417. if ($couponUseMember == 'condition') {
  418. if ($condition == 'is_employ') {
  419. $memberList = Member::where('member_classify', 'EMPLOY')->pluck('member_id')->toArray();
  420. } elseif ($condition == 'is_member') {
  421. $memberList = Member::where('member_classify', 'MEMBER')->pluck('member_id')->toArray();
  422. } elseif ($condition == 'is_vip') {
  423. $memberList = Member::where('member_is_vip', 'Y')->pluck('member_id')->toArray();
  424. }
  425. }
  426. $couponNbr = [];
  427. Db::beginTransaction();
  428. try {
  429. $couponIds = array_column($chooseCoupons, 'id');
  430. $coupons = Coupon::whereIn('coupon_id', $couponIds)->get()->toArray();
  431. foreach ($coupons as $coupon) {
  432. foreach ($chooseCoupons as $chooseCoupon) {
  433. if ($chooseCoupon['id'] == $coupon['coupon_id']) {
  434. if (empty($chooseCoupon['gain_datetime'])) {
  435. $chooseCoupon['gain_datetime'] = date('Y-m-d H:i:s');
  436. }
  437. $params['coupon_id'] = $coupon['coupon_id'];
  438. $params['coupon_detail_gain_datetime'] = date('Y-m-d H:i:s', strtotime($chooseCoupon['gain_datetime']));
  439. if (($coupon['coupon_validdate_day'] == 0 || $coupon['coupon_validdate_day'] == '') && !empty($coupon['coupon_validdate_end'])) {
  440. $params['coupon_detail_deadline_datetime'] = $coupon['coupon_validdate_end'];
  441. } elseif ($coupon['coupon_validdate_day'] > 0) {
  442. $endUnix = strtotime($chooseCoupon['gain_datetime']);
  443. $params['coupon_detail_deadline_datetime'] = date('Y-m-d H:i:s', $endUnix + ($coupon['coupon_validdate_day'] * 24 * 3600) - 1);
  444. }
  445. foreach ($memberList as $item) {
  446. $params['member_id'] = $item;
  447. if ($coupon['coupon_is_period'] == 'Y') {
  448. // if (CouponDetail::where('join_coupon_detail_member_id', $item)->where('join_detail_coupon_id', $coupon['coupon_id'])->exists()) {
  449. // throw new BusinessException("请勿重复发放周期券");
  450. // }
  451. $params['coupon_detail_period_num'] = 1;
  452. $periodJson = json_decode($coupon['coupon_period_json'], true);
  453. // for ($i=0;$i<$periodJson['nbr'];$i++){
  454. CouponDetailService::sendPeriodCoupon($params);
  455. // }
  456. continue;
  457. }
  458. if ($chooseCoupon['nbr'] > 0) {
  459. $params['chooseCouponNbr'] = $chooseCoupon['nbr'];
  460. // 有发行数量
  461. if ($coupon['coupon_number'] != 0) {
  462. // 查询还有多少张没领的
  463. $count = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
  464. ->whereIn('coupon_detail_status', ['INIT', 'PENDING'])
  465. ->count();
  466. if (!isset($couponNbr[$coupon['coupon_id']])) {
  467. $couponNbr[$coupon['coupon_id']] = $count;
  468. }
  469. if ($couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'] < 0) {
  470. Log::error("优惠券发放失败,超出发行数量", $params);
  471. throw new BusinessException($coupon['coupon_name'] . "超出发行数量");
  472. }
  473. $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'];
  474. // 匹配已发行的优惠券
  475. CouponDetailService::customSendCouponHave($params);
  476. } else {
  477. for ($i = 0; $i < $chooseCoupon['nbr']; $i++) {
  478. CouponDetailService::customSendCoupon($params);
  479. }
  480. }
  481. }
  482. }
  483. }
  484. }
  485. }
  486. Db::commit();
  487. return json_success("发放成功");
  488. } catch (BusinessException $e) {
  489. Db::rollBack();
  490. return json_fail($e->getMessage());
  491. } catch (\Exception $e) {
  492. dump($e->getTrace());
  493. Db::rollBack();
  494. return json_fail('优惠券发放失败');
  495. }
  496. }
  497. /**
  498. * @Desc 修改优惠券
  499. * @Author Gorden
  500. * @Date 2024/8/14 15:48
  501. *
  502. * @param Request $request
  503. * @return Response
  504. */
  505. public function update(Request $request): Response
  506. {
  507. if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
  508. return json_fail($this->validateClass->getError());
  509. }
  510. $params = $request->post();
  511. Db::beginTransaction();
  512. try {
  513. [$id, $data] = $this->updateInput($request);
  514. $originCouponNumber = $data['origin_coupon_number'];
  515. $originCouponValiddateDay = $data['origin_coupon_validdate_day'];
  516. $originCouponValiddateEnd = $data['origin_coupon_validdate_end'];
  517. unset($data['origin_coupon_number'], $data['origin_coupon_validdate_day'], $data['origin_coupon_validdate_end']);
  518. $this->updateCouponGoods($request->post('goodsContentList'), $id);
  519. if ($originCouponNumber == 0 && $data['coupon_number'] != 0) {
  520. // 查已领取多少了
  521. $detailCount = CouponDetail::where('join_detail_coupon_id', $id)->count();
  522. if ($detailCount < $data['coupon_number']) {
  523. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $detailCount);
  524. }
  525. } else if ($originCouponNumber < $data['coupon_number']) {
  526. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $originCouponNumber);
  527. } else if ($originCouponNumber > $data['coupon_number']) {
  528. CouponDetail::where('join_detail_coupon_id', $id)
  529. ->where('join_coupon_detail_member_id', '')
  530. ->limit($originCouponNumber - $data['coupon_number'])
  531. ->delete();
  532. }
  533. // 修改时间了
  534. if ($params['coupon_use_time'] == 'day' && $originCouponValiddateDay != $data['coupon_validdate_day']) {
  535. $this->updateDetailTimeForDay($id, $data['coupon_validdate_day']);
  536. } elseif ($params['coupon_use_time'] == 'date' && $originCouponValiddateEnd != $data['coupon_validdate_end']) {
  537. $this->updateDetailTimeForDate($id, $data['coupon_validdate_end']);
  538. }
  539. // 激活状态,初始改为待领取
  540. if ($data['coupon_status'] == 'ACTIVED') {
  541. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', 'INIT')->update(['coupon_detail_status' => 'PENDING']);
  542. } elseif ($data['coupon_status'] == 'DISABLED') { // 禁用状态,未领取未使用的都是禁用
  543. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', '<>', 'USED')->update(['coupon_detail_status' => 'DISABLED']);
  544. }
  545. $this->doUpdate($id, $data);
  546. Db::commit();
  547. return json_success('success');
  548. } catch (BusinessException $e) {
  549. Db::rollBack();
  550. return json_fail($e->getMessage());
  551. } catch (\Exception $e) {
  552. Db::rollBack();
  553. dump($e->getMessage());
  554. return json_fail('数据更新失败');
  555. }
  556. }
  557. public function updateDetailTimeForDay($couponId, $day)
  558. {
  559. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  560. ->where('coupon_detail_status', '<>', 'USED')
  561. ->where('coupon_detail_deadline_datetime', '<>', '')
  562. ->get()
  563. ->toArray();
  564. try {
  565. foreach ($details as $detail) {
  566. $couponDetailGainDatetime = strtotime($detail['coupon_detail_gain_datetime']);
  567. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  568. ->update([
  569. 'coupon_detail_deadline_datetime' => date('Y-m-d H:i:s', $couponDetailGainDatetime + ($day * 24 * 3600))
  570. ]);
  571. }
  572. } catch (\Exception $e) {
  573. dump($e->getMessage());
  574. throw new BusinessException("优惠券更新失败");
  575. }
  576. }
  577. public function updateDetailTimeForDate($couponId, $endDate)
  578. {
  579. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  580. ->where('coupon_detail_status', '<>', 'USED')
  581. ->where('coupon_detail_deadline_datetime', '<>', '')
  582. ->get()
  583. ->toArray();
  584. try {
  585. foreach ($details as $detail) {
  586. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  587. ->update([
  588. 'coupon_detail_deadline_datetime' => $endDate
  589. ]);
  590. }
  591. } catch (\Exception $e) {
  592. dump($e->getMessage());
  593. throw new BusinessException("优惠券更新失败");
  594. }
  595. }
  596. public function updateCouponGoods($goods, $couponId)
  597. {
  598. try {
  599. $couponGoodsIds = CouponGoods::where('join_goods_coupon_id', $couponId)->pluck('join_coupon_goods_id')->toArray();
  600. $goodsIds = array_column($goods, 'goods_id');
  601. // 新的差集
  602. $goodsDiff = array_diff($goodsIds, $couponGoodsIds);
  603. // 旧的差集
  604. $couponDiff = array_diff($couponGoodsIds, $goodsIds);
  605. foreach ($goods as $good) {
  606. // 更新两个中都有的
  607. if (in_array($good['goods_id'], $couponGoodsIds)) {
  608. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $good['goods_id'])->update(['join_coupon_goods_sku_id' => $good['sku_id']]);
  609. } elseif (in_array($good['goods_id'], $goodsDiff)) { // 新加的
  610. CouponGoods::insert([
  611. 'join_goods_coupon_id' => $couponId,
  612. 'join_coupon_goods_id' => $good['goods_id'],
  613. 'join_coupon_goods_sku_id' => $good['sku_id'],
  614. 'coupon_goods_json' => '[]',
  615. 'coupon_goods_extend_json' => '[]',
  616. 'coupon_goods_addtimes' => time()
  617. ]);
  618. }
  619. }
  620. if (!empty($couponDiff)) { // 去掉的
  621. foreach ($couponDiff as $item) {
  622. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $item)->delete();
  623. }
  624. }
  625. } catch (\Exception $e) {
  626. throw new BusinessException('关联产品更新失败');
  627. }
  628. }
  629. protected function updateInput(Request $request): array
  630. {
  631. $params = $request->post();
  632. $primary_key = $this->model->getKeyName();
  633. $id = $request->post($primary_key);
  634. $data = $this->inputFilter($params);
  635. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  636. $data['coupon_validdate_day'] = 0;
  637. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  638. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  639. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  640. $data['coupon_validdate_begin'] = '';
  641. $data['coupon_validdate_end'] = '';
  642. }
  643. $model = $this->model->find($id);
  644. // 原数量
  645. $data['origin_coupon_number'] = $model->coupon_number;
  646. // 原优惠天数
  647. $data['origin_coupon_validdate_day'] = $model->coupon_validdate_day;
  648. // 原结束时间
  649. $data['origin_coupon_validdate_end'] = $model->coupon_validdate_end;
  650. if (!$model) {
  651. throw new BusinessException('记录不存在', 2);
  652. }
  653. $couponJson = [];
  654. if (!empty($model->coupon_json)) {
  655. $couponJson = json_decode($model->coupon_json, true);
  656. }
  657. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  658. $couponJson['member']['list'] = $params['member_list'];
  659. // if (isset($couponJson['member']['range'])) {
  660. $couponJson['member']['range'] = '';
  661. // }
  662. // if (isset($couponJson['member']['where'])) {
  663. $couponJson['member']['where'] = '';
  664. // }
  665. } else if ($params['coupon_use_member'] == 'condition') {
  666. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  667. $couponJson['member']['range'] = 'VIP会员';
  668. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  669. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  670. $couponJson['member']['range'] = '公司员工';
  671. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  672. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  673. $couponJson['member']['range'] = '会员';
  674. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  675. }
  676. // if (isset($couponJson['member']['list'])) {
  677. $couponJson['member']['list'] = [];
  678. // }
  679. } else if ($params['coupon_use_member'] == 'all') {
  680. $couponJson['member']['list'] = [];
  681. $couponJson['member']['range'] = '全部会员';
  682. $couponJson['member']['where'] = '';
  683. if (isset($couponJson['member']['list'])) {
  684. $couponJson['member']['list'] = [];
  685. }
  686. }
  687. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  688. $couponJson['premises_range'] = '所有门店可用';
  689. unset($couponJson['premises']);
  690. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  691. $couponJson['premises'] = $params['premises'];
  692. $couponJson['premises_range'] = '部分门店可用';
  693. }
  694. if (empty($data['coupon_validdate_day'])) {
  695. $data['coupon_validdate_day'] = 0;
  696. }
  697. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  698. $data['coupon_period_json'] = '[]';
  699. // 处理周期优惠券
  700. if ($params['coupon_is_period'] != 'N') {
  701. $this->disposePeriod($params);
  702. $data['coupon_period_json'] = json_encode([
  703. 'length' => $params['period'],
  704. 'unit' => $params['period_unit'],
  705. 'val' => $params['period_unit_num'],
  706. 'nbr' => $params['period_nbr']
  707. ]);
  708. }
  709. if (in_array($data['coupon_classify'], ['抵用券', '立减券', '赠品券', '福利券', '年卡', '季卡', '月卡'])) {
  710. $data['coupon_minimum_limit'] = 0;
  711. }
  712. unset($data[$primary_key]);
  713. return [$id, $data];
  714. }
  715. /**
  716. * 优惠券详情
  717. */
  718. public function info(Request $request): Response
  719. {
  720. try {
  721. $couponId = $request->get('coupon_id', '');
  722. if (!$couponId) {
  723. return json_fail('参数异常');
  724. }
  725. $coupon = Coupon::where('coupon_id', $couponId)->first();
  726. if (!$coupon) {
  727. return json_fail('数据异常');
  728. }
  729. // 拼选择的商品
  730. $couponGoods = CouponGoods::with([
  731. 'goods' => function ($query) {
  732. $query->select('goods_id', 'goods_id as id', 'goods_name as name', 'join_goods_category_id as pid', 'goods_classify', 'goods_sales_price', 'goods_cover');
  733. },
  734. 'skus' => function ($query) {
  735. $query->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  736. },
  737. 'sku'
  738. ])->where('join_goods_coupon_id', $couponId)
  739. ->get()
  740. ->toArray();
  741. $goodsIds = [];
  742. $goodsContent = [];
  743. foreach ($couponGoods as $couponGood) {
  744. $goodsIds[] = $couponGood['join_coupon_goods_id'];
  745. $content = [
  746. 'goods_id' => $couponGood['join_coupon_goods_id'],
  747. 'sku_id' => $couponGood['join_coupon_goods_sku_id'],
  748. ];
  749. if (isset($couponGood['goods'])) {
  750. $content['goods_name'] = $couponGood['goods']['name'];
  751. $content['goods_classify'] = $couponGood['goods']['goods_classify'];
  752. $content['goods_cover'] = getenv('STORAGE_DOMAIN') . $couponGood['goods']['goods_cover'];
  753. }
  754. if (isset($couponGood['sku']) && isset($couponGood['sku']['goods_sku_specs_json'])) {
  755. // $skuSpecsJson = json_decode($couponGood['sku']['goods_sku_specs_json'], true);
  756. // $skuName = '';
  757. // foreach ($skuSpecsJson as $item) {
  758. // if (is_array($item)) {
  759. // $item = implode('', $item);
  760. // }
  761. // $skuName .= $item . ',';
  762. // }
  763. // $content['sku_name'] = rtrim($skuName, ',');
  764. $content['goods_sales_price'] = $couponGood['sku']['goods_sku_sales_price'];
  765. }
  766. if (isset($couponGood['skus'])) {
  767. foreach ($couponGood['skus'] as $key => $skus) {
  768. if (!empty($skus['goods_sku_specs_json'])) {
  769. $skuSpecsJson = json_decode($skus['goods_sku_specs_json'], true);
  770. $skuName = '';
  771. foreach ($skuSpecsJson as $item) {
  772. if (is_array($item)) {
  773. $item = implode('', $item);
  774. }
  775. $skuName .= $item . ',';
  776. }
  777. $couponGood['skus'][$key]['sku_name'] = rtrim($skuName, ',');
  778. }
  779. }
  780. $content['skus'] = $couponGood['skus'];
  781. }
  782. $goodsContent[] = $content;
  783. }
  784. // 选中的会员
  785. $memberLists = [];
  786. // 可用门店
  787. $premises = [];
  788. if (!empty($coupon->coupon_json)) {
  789. $couponJson = json_decode($coupon->coupon_json, true);
  790. if (isset($couponJson['member']) && isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  791. $res = Db::table('member')
  792. ->leftjoin('member_cert', 'member.member_id', '=', 'member_cert.join_cert_member_id')
  793. ->leftjoin('member_info', 'member.member_id', '=', 'member_info.join_info_member_id')
  794. ->select('member.member_id', 'member.member_mobile', 'member_cert.member_cert_name', 'member_info.member_info_nickname')
  795. ->where('member_status', 'ACTIVED')
  796. ->whereIn('member_id', $couponJson['member']['list'])
  797. ->get();
  798. $memberLists = [];
  799. foreach ($res as $item) {
  800. $name = '';
  801. if (!empty($item->member_cert_name)) {
  802. $name = $item->member_cert_name;
  803. } else if (!empty($item->member_info_nickname)) {
  804. $name = $item->member_info_nickname;
  805. }
  806. $value = !empty($name) ? $name . '-' : '';
  807. if ($item->member_mobile != '0000') {
  808. $value .= $item->member_mobile;
  809. }
  810. if (empty($value)) {
  811. $value = $item->member_mobile;
  812. }
  813. $value = rtrim($value, '-');
  814. $memberLists[] = [
  815. 'key' => $item->member_id,
  816. 'value' => $value,
  817. ];
  818. }
  819. }
  820. if (isset($couponJson['premises']) && !empty($couponJson['premises'])) {
  821. $premises = SysDept::whereIn('dept_id', $couponJson['premises'])
  822. ->select('dept_id', 'dept_name')
  823. ->get()
  824. ->toArray();
  825. }
  826. }
  827. $data = [
  828. 'goods_ids' => $goodsIds,
  829. 'goods_content' => $goodsContent,
  830. 'member_lists' => $memberLists,
  831. 'premises_list' => $premises
  832. ];
  833. Log::info("查询优惠券详情成功");
  834. return json_success('', $data);
  835. } catch (\Exception $e) {
  836. Log::error("查询优惠券详情失败", ['msg' => $e->getMessage()]);
  837. return json_fail('查询失败');
  838. }
  839. }
  840. /**
  841. * 删除
  842. * @param Request $request
  843. * @return Response
  844. * @throws BusinessException
  845. */
  846. public function delete(Request $request): Response
  847. {
  848. $ids = $this->deleteInput($request);
  849. Db::beginTransaction();
  850. try {
  851. // 删除优惠券关联的产品
  852. foreach ($ids as $id) {
  853. $couponDetail = CouponDetail::with([
  854. 'coupon' => function ($query) {
  855. $query->select('coupon_id', 'coupon_name');
  856. }
  857. ])->where('join_detail_coupon_id', $id)
  858. ->where('join_coupon_detail_member_id', '<>', '')
  859. ->first();
  860. if (!empty($couponDetail)) {
  861. Db::rollBack();
  862. return json_fail($couponDetail->coupon && $couponDetail->coupon->coupon_name ? $couponDetail->coupon->coupon_name . "已被领取,无法删除,请禁用" : "删除的优惠券中有已被领取的,无法删除,请禁用");
  863. }
  864. CouponGoods::where('join_goods_coupon_id', $id)->delete();
  865. CouponDetail::where('join_detail_coupon_id', $id)->delete();
  866. }
  867. $this->doDelete($ids);
  868. Db::commit();
  869. return json_success('success');
  870. } catch (\Exception $e) {
  871. dump($e->getMessage());
  872. Db::rollBack();
  873. return json_fail('删除失败');
  874. }
  875. }
  876. public function disableCoupon(Request $request)
  877. {
  878. $couponId = $request->post('coupon_id');
  879. if (!$couponId) {
  880. return json_fail("参数异常");
  881. }
  882. Db::beginTransaction();
  883. try {
  884. Coupon::where('coupon_id', $couponId)->update(['coupon_status' => 'DISABLED']);
  885. CouponDetail::where('join_detail_coupon_id', $couponId)->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->update(['coupon_detail_status' => 'DISABLED']);
  886. Db::commit();
  887. return json_success('success');
  888. } catch (\Exception $e) {
  889. Db::rollBack();
  890. return json_fail("禁用失败");
  891. }
  892. }
  893. private function generateCouponDetail($couponId, $couponStatus, $nbr)
  894. {
  895. for ($i = 0; $i < intval($nbr); $i++) {
  896. $insertData = [
  897. 'coupon_detail_id' => 'CUDT' . date("ymdHi") . random_string(4, 'up'),
  898. 'join_detail_coupon_id' => $couponId,
  899. 'coupon_detail_status' => $couponStatus == 'ACTIVED' ? 'PENDING' : 'INIT',
  900. 'coupon_detail_addtimes' => time()
  901. ];
  902. try {
  903. CouponDetail::insert($insertData);
  904. } catch (\Exception $e) {
  905. $insertData['coupon_detail_id'] = $insertData['coupon_detail_id'] . random_string(1, 'up');
  906. CouponDetail::insert($insertData);
  907. }
  908. }
  909. }
  910. }