CouponController.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. // 有发行数量
  460. if ($coupon['coupon_number'] != 0) {
  461. // 查询还有多少张没领的
  462. $count = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
  463. ->whereIn('coupon_detail_status', ['INIT', 'PENDING'])
  464. ->count();
  465. if (!isset($couponNbr[$coupon['coupon_id']])) {
  466. $couponNbr[$coupon['coupon_id']] = $count;
  467. }
  468. if ($couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'] < 0) {
  469. throw new BusinessException($coupon['coupon_name'] . "超出发行数量");
  470. }
  471. $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'];
  472. $params['chooseCouponNbr'] = $chooseCoupon['nbr'];
  473. // 匹配已发行的优惠券
  474. CouponDetailService::customSendCouponHave($params);
  475. } else {
  476. for ($i = 0; $i < $chooseCoupon['nbr']; $i++) {
  477. CouponDetailService::customSendCoupon($params);
  478. }
  479. }
  480. }
  481. }
  482. }
  483. }
  484. }
  485. Db::commit();
  486. return json_success("发放成功");
  487. } catch (BusinessException $e) {
  488. Db::rollBack();
  489. return json_fail($e->getMessage());
  490. } catch (\Exception $e) {
  491. dump($e->getTrace());
  492. Db::rollBack();
  493. return json_fail('优惠券发放失败');
  494. }
  495. }
  496. /**
  497. * @Desc 修改优惠券
  498. * @Author Gorden
  499. * @Date 2024/8/14 15:48
  500. *
  501. * @param Request $request
  502. * @return Response
  503. */
  504. public function update(Request $request): Response
  505. {
  506. if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
  507. return json_fail($this->validateClass->getError());
  508. }
  509. $params = $request->post();
  510. Db::beginTransaction();
  511. try {
  512. [$id, $data] = $this->updateInput($request);
  513. $originCouponNumber = $data['origin_coupon_number'];
  514. $originCouponValiddateDay = $data['origin_coupon_validdate_day'];
  515. $originCouponValiddateEnd = $data['origin_coupon_validdate_end'];
  516. unset($data['origin_coupon_number'], $data['origin_coupon_validdate_day'], $data['origin_coupon_validdate_end']);
  517. $this->updateCouponGoods($request->post('goodsContentList'), $id);
  518. if ($originCouponNumber == 0 && $data['coupon_number'] != 0) {
  519. // 查已领取多少了
  520. $detailCount = CouponDetail::where('join_detail_coupon_id', $id)->count();
  521. if ($detailCount < $data['coupon_number']) {
  522. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $detailCount);
  523. }
  524. } else if ($originCouponNumber < $data['coupon_number']) {
  525. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $originCouponNumber);
  526. } else if ($originCouponNumber > $data['coupon_number']) {
  527. CouponDetail::where('join_detail_coupon_id', $id)
  528. ->where('join_coupon_detail_member_id', '')
  529. ->limit($originCouponNumber - $data['coupon_number'])
  530. ->delete();
  531. }
  532. // 修改时间了
  533. if ($params['coupon_use_time'] == 'day' && $originCouponValiddateDay != $data['coupon_validdate_day']) {
  534. $this->updateDetailTimeForDay($id, $data['coupon_validdate_day']);
  535. } elseif ($params['coupon_use_time'] == 'date' && $originCouponValiddateEnd != $data['coupon_validdate_end']) {
  536. $this->updateDetailTimeForDate($id, $data['coupon_validdate_end']);
  537. }
  538. // 激活状态,初始改为待领取
  539. if ($data['coupon_status'] == 'ACTIVED') {
  540. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', 'INIT')->update(['coupon_detail_status' => 'PENDING']);
  541. } elseif ($data['coupon_status'] == 'DISABLED') { // 禁用状态,未领取未使用的都是禁用
  542. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', '<>', 'USED')->update(['coupon_detail_status' => 'DISABLED']);
  543. }
  544. $this->doUpdate($id, $data);
  545. Db::commit();
  546. return json_success('success');
  547. } catch (BusinessException $e) {
  548. Db::rollBack();
  549. return json_fail($e->getMessage());
  550. } catch (\Exception $e) {
  551. Db::rollBack();
  552. dump($e->getMessage());
  553. return json_fail('数据更新失败');
  554. }
  555. }
  556. public function updateDetailTimeForDay($couponId, $day)
  557. {
  558. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  559. ->where('coupon_detail_status', '<>', 'USED')
  560. ->where('coupon_detail_deadline_datetime', '<>', '')
  561. ->get()
  562. ->toArray();
  563. try {
  564. foreach ($details as $detail) {
  565. $couponDetailGainDatetime = strtotime($detail['coupon_detail_gain_datetime']);
  566. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  567. ->update([
  568. 'coupon_detail_deadline_datetime' => date('Y-m-d H:i:s', $couponDetailGainDatetime + ($day * 24 * 3600))
  569. ]);
  570. }
  571. } catch (\Exception $e) {
  572. dump($e->getMessage());
  573. throw new BusinessException("优惠券更新失败");
  574. }
  575. }
  576. public function updateDetailTimeForDate($couponId, $endDate)
  577. {
  578. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  579. ->where('coupon_detail_status', '<>', 'USED')
  580. ->where('coupon_detail_deadline_datetime', '<>', '')
  581. ->get()
  582. ->toArray();
  583. try {
  584. foreach ($details as $detail) {
  585. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  586. ->update([
  587. 'coupon_detail_deadline_datetime' => $endDate
  588. ]);
  589. }
  590. } catch (\Exception $e) {
  591. dump($e->getMessage());
  592. throw new BusinessException("优惠券更新失败");
  593. }
  594. }
  595. public function updateCouponGoods($goods, $couponId)
  596. {
  597. try {
  598. $couponGoodsIds = CouponGoods::where('join_goods_coupon_id', $couponId)->pluck('join_coupon_goods_id')->toArray();
  599. $goodsIds = array_column($goods, 'goods_id');
  600. // 新的差集
  601. $goodsDiff = array_diff($goodsIds, $couponGoodsIds);
  602. // 旧的差集
  603. $couponDiff = array_diff($couponGoodsIds, $goodsIds);
  604. foreach ($goods as $good) {
  605. // 更新两个中都有的
  606. if (in_array($good['goods_id'], $couponGoodsIds)) {
  607. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $good['goods_id'])->update(['join_coupon_goods_sku_id' => $good['sku_id']]);
  608. } elseif (in_array($good['goods_id'], $goodsDiff)) { // 新加的
  609. CouponGoods::insert([
  610. 'join_goods_coupon_id' => $couponId,
  611. 'join_coupon_goods_id' => $good['goods_id'],
  612. 'join_coupon_goods_sku_id' => $good['sku_id'],
  613. 'coupon_goods_json' => '[]',
  614. 'coupon_goods_extend_json' => '[]',
  615. 'coupon_goods_addtimes' => time()
  616. ]);
  617. }
  618. }
  619. if (!empty($couponDiff)) { // 去掉的
  620. foreach ($couponDiff as $item) {
  621. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $item)->delete();
  622. }
  623. }
  624. } catch (\Exception $e) {
  625. throw new BusinessException('关联产品更新失败');
  626. }
  627. }
  628. protected function updateInput(Request $request): array
  629. {
  630. $params = $request->post();
  631. $primary_key = $this->model->getKeyName();
  632. $id = $request->post($primary_key);
  633. $data = $this->inputFilter($params);
  634. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  635. $data['coupon_validdate_day'] = 0;
  636. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  637. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  638. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  639. $data['coupon_validdate_begin'] = '';
  640. $data['coupon_validdate_end'] = '';
  641. }
  642. $model = $this->model->find($id);
  643. // 原数量
  644. $data['origin_coupon_number'] = $model->coupon_number;
  645. // 原优惠天数
  646. $data['origin_coupon_validdate_day'] = $model->coupon_validdate_day;
  647. // 原结束时间
  648. $data['origin_coupon_validdate_end'] = $model->coupon_validdate_end;
  649. if (!$model) {
  650. throw new BusinessException('记录不存在', 2);
  651. }
  652. $couponJson = [];
  653. if (!empty($model->coupon_json)) {
  654. $couponJson = json_decode($model->coupon_json, true);
  655. }
  656. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  657. $couponJson['member']['list'] = $params['member_list'];
  658. // if (isset($couponJson['member']['range'])) {
  659. $couponJson['member']['range'] = '';
  660. // }
  661. // if (isset($couponJson['member']['where'])) {
  662. $couponJson['member']['where'] = '';
  663. // }
  664. } else if ($params['coupon_use_member'] == 'condition') {
  665. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  666. $couponJson['member']['range'] = 'VIP会员';
  667. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  668. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  669. $couponJson['member']['range'] = '公司员工';
  670. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  671. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  672. $couponJson['member']['range'] = '会员';
  673. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  674. }
  675. // if (isset($couponJson['member']['list'])) {
  676. $couponJson['member']['list'] = [];
  677. // }
  678. } else if ($params['coupon_use_member'] == 'all') {
  679. $couponJson['member']['list'] = [];
  680. $couponJson['member']['range'] = '全部会员';
  681. $couponJson['member']['where'] = '';
  682. if (isset($couponJson['member']['list'])) {
  683. $couponJson['member']['list'] = [];
  684. }
  685. }
  686. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  687. $couponJson['premises_range'] = '所有门店可用';
  688. unset($couponJson['premises']);
  689. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  690. $couponJson['premises'] = $params['premises'];
  691. $couponJson['premises_range'] = '部分门店可用';
  692. }
  693. if (empty($data['coupon_validdate_day'])) {
  694. $data['coupon_validdate_day'] = 0;
  695. }
  696. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  697. $data['coupon_period_json'] = '[]';
  698. // 处理周期优惠券
  699. if ($params['coupon_is_period'] != 'N') {
  700. $this->disposePeriod($params);
  701. $data['coupon_period_json'] = json_encode([
  702. 'length' => $params['period'],
  703. 'unit' => $params['period_unit'],
  704. 'val' => $params['period_unit_num'],
  705. 'nbr' => $params['period_nbr']
  706. ]);
  707. }
  708. if (in_array($data['coupon_classify'], ['抵用券', '立减券', '赠品券', '福利券', '年卡', '季卡', '月卡'])) {
  709. $data['coupon_minimum_limit'] = 0;
  710. }
  711. unset($data[$primary_key]);
  712. return [$id, $data];
  713. }
  714. /**
  715. * 优惠券详情
  716. */
  717. public function info(Request $request): Response
  718. {
  719. try {
  720. $couponId = $request->get('coupon_id', '');
  721. if (!$couponId) {
  722. return json_fail('参数异常');
  723. }
  724. $coupon = Coupon::where('coupon_id', $couponId)->first();
  725. if (!$coupon) {
  726. return json_fail('数据异常');
  727. }
  728. // 拼选择的商品
  729. $couponGoods = CouponGoods::with([
  730. 'goods' => function ($query) {
  731. $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');
  732. },
  733. 'skus'=>function($query){
  734. $query->select('goods_sku_id','join_sku_goods_id','goods_sku_specs_json','goods_sku_sales_price');
  735. },
  736. 'sku'
  737. ])->where('join_goods_coupon_id', $couponId)
  738. ->get()
  739. ->toArray();
  740. $goodsIds = [];
  741. $goodsContent = [];
  742. foreach ($couponGoods as $couponGood) {
  743. $goodsIds[] = $couponGood['join_coupon_goods_id'];
  744. $content = [
  745. 'goods_id' => $couponGood['join_coupon_goods_id'],
  746. 'sku_id' => $couponGood['join_coupon_goods_sku_id'],
  747. ];
  748. if (isset($couponGood['goods'])) {
  749. $content['goods_name'] = $couponGood['goods']['name'];
  750. $content['goods_classify'] = $couponGood['goods']['goods_classify'];
  751. $content['goods_cover'] = getenv('STORAGE_DOMAIN') . $couponGood['goods']['goods_cover'];
  752. }
  753. if (isset($couponGood['sku']) && isset($couponGood['sku']['goods_sku_specs_json'])) {
  754. // $skuSpecsJson = json_decode($couponGood['sku']['goods_sku_specs_json'], true);
  755. // $skuName = '';
  756. // foreach ($skuSpecsJson as $item) {
  757. // if (is_array($item)) {
  758. // $item = implode('', $item);
  759. // }
  760. // $skuName .= $item . ',';
  761. // }
  762. // $content['sku_name'] = rtrim($skuName, ',');
  763. $content['goods_sales_price'] = $couponGood['sku']['goods_sku_sales_price'];
  764. }
  765. if (isset($couponGood['skus'])) {
  766. foreach ($couponGood['skus'] as $key => $skus) {
  767. if (!empty($skus['goods_sku_specs_json'])) {
  768. $skuSpecsJson = json_decode($skus['goods_sku_specs_json'], true);
  769. $skuName = '';
  770. foreach ($skuSpecsJson as $item) {
  771. if (is_array($item)) {
  772. $item = implode('', $item);
  773. }
  774. $skuName .= $item . ',';
  775. }
  776. $couponGood['skus'][$key]['sku_name'] = rtrim($skuName, ',');
  777. }
  778. }
  779. $content['skus'] = $couponGood['skus'];
  780. }
  781. $goodsContent[] = $content;
  782. }
  783. // 选中的会员
  784. $memberLists = [];
  785. // 可用门店
  786. $premises = [];
  787. if (!empty($coupon->coupon_json)) {
  788. $couponJson = json_decode($coupon->coupon_json, true);
  789. if (isset($couponJson['member']) && isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  790. $res = Db::table('member')
  791. ->leftjoin('member_cert', 'member.member_id', '=', 'member_cert.join_cert_member_id')
  792. ->leftjoin('member_info', 'member.member_id', '=', 'member_info.join_info_member_id')
  793. ->select('member.member_id', 'member.member_mobile', 'member_cert.member_cert_name', 'member_info.member_info_nickname')
  794. ->where('member_status', 'ACTIVED')
  795. ->whereIn('member_id', $couponJson['member']['list'])
  796. ->get();
  797. $memberLists = [];
  798. foreach ($res as $item) {
  799. $name = '';
  800. if (!empty($item->member_cert_name)) {
  801. $name = $item->member_cert_name;
  802. } else if (!empty($item->member_info_nickname)) {
  803. $name = $item->member_info_nickname;
  804. }
  805. $value = !empty($name) ? $name . '-' : '';
  806. if ($item->member_mobile != '0000') {
  807. $value .= $item->member_mobile;
  808. }
  809. if (empty($value)) {
  810. $value = $item->member_mobile;
  811. }
  812. $value = rtrim($value, '-');
  813. $memberLists[] = [
  814. 'key' => $item->member_id,
  815. 'value' => $value,
  816. ];
  817. }
  818. }
  819. if (isset($couponJson['premises']) && !empty($couponJson['premises'])) {
  820. $premises = SysDept::whereIn('dept_id', $couponJson['premises'])
  821. ->select('dept_id', 'dept_name')
  822. ->get()
  823. ->toArray();
  824. }
  825. }
  826. $data = [
  827. 'goods_ids' => $goodsIds,
  828. 'goods_content' => $goodsContent,
  829. 'member_lists' => $memberLists,
  830. 'premises_list' => $premises
  831. ];
  832. Log::info("查询优惠券详情成功");
  833. return json_success('', $data);
  834. } catch (\Exception $e) {
  835. Log::error("查询优惠券详情失败", ['msg' => $e->getMessage()]);
  836. return json_fail('查询失败');
  837. }
  838. }
  839. /**
  840. * 删除
  841. * @param Request $request
  842. * @return Response
  843. * @throws BusinessException
  844. */
  845. public function delete(Request $request): Response
  846. {
  847. $ids = $this->deleteInput($request);
  848. Db::beginTransaction();
  849. try {
  850. // 删除优惠券关联的产品
  851. foreach ($ids as $id) {
  852. $couponDetail = CouponDetail::with([
  853. 'coupon' => function ($query) {
  854. $query->select('coupon_id', 'coupon_name');
  855. }
  856. ])->where('join_detail_coupon_id', $id)
  857. ->where('join_coupon_detail_member_id', '<>', '')
  858. ->first();
  859. if (!empty($couponDetail)) {
  860. Db::rollBack();
  861. return json_fail($couponDetail->coupon && $couponDetail->coupon->coupon_name ? $couponDetail->coupon->coupon_name . "已被领取,无法删除,请禁用" : "删除的优惠券中有已被领取的,无法删除,请禁用");
  862. }
  863. CouponGoods::where('join_goods_coupon_id', $id)->delete();
  864. CouponDetail::where('join_detail_coupon_id', $id)->delete();
  865. }
  866. $this->doDelete($ids);
  867. Db::commit();
  868. return json_success('success');
  869. } catch (\Exception $e) {
  870. dump($e->getMessage());
  871. Db::rollBack();
  872. return json_fail('删除失败');
  873. }
  874. }
  875. public function disableCoupon(Request $request)
  876. {
  877. $couponId = $request->post('coupon_id');
  878. if (!$couponId) {
  879. return json_fail("参数异常");
  880. }
  881. Db::beginTransaction();
  882. try {
  883. Coupon::where('coupon_id', $couponId)->update(['coupon_status' => 'DISABLED']);
  884. CouponDetail::where('join_detail_coupon_id', $couponId)->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->update(['coupon_detail_status' => 'DISABLED']);
  885. Db::commit();
  886. return json_success('success');
  887. } catch (\Exception $e) {
  888. Db::rollBack();
  889. return json_fail("禁用失败");
  890. }
  891. }
  892. private function generateCouponDetail($couponId, $couponStatus, $nbr)
  893. {
  894. for ($i = 0; $i < intval($nbr); $i++) {
  895. CouponDetail::insert([
  896. 'coupon_detail_id' => 'CUDT' . date("ymdHi") . random_string(4, 'up'),
  897. 'join_detail_coupon_id' => $couponId,
  898. 'coupon_detail_status' => $couponStatus == 'ACTIVED' ? 'PENDING' : 'INIT',
  899. 'coupon_detail_addtimes' => time()
  900. ]);
  901. }
  902. }
  903. }