CouponController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. <?php
  2. namespace app\admin\controller\coupon;
  3. use app\admin\service\coupon\CouponDetailService;
  4. use app\admin\validate\coupon\CouponValidate;
  5. use app\admin\validate\device\DeviceValidate;
  6. use app\controller\Curd;
  7. use app\model\Coupon;
  8. use app\model\CouponDetail;
  9. use app\model\CouponGoods;
  10. use app\model\Device;
  11. use app\model\Member;
  12. use app\model\SysDept;
  13. use app\model\SysSerial;
  14. use support\Db;
  15. use support\exception\BusinessException;
  16. use support\Request;
  17. use support\Response;
  18. use Tinywan\Jwt\JwtToken;
  19. class CouponController extends Curd
  20. {
  21. public function __construct()
  22. {
  23. $this->model = new Coupon();
  24. $this->validate = true;
  25. $this->validateClass = new CouponValidate();
  26. }
  27. /**
  28. * @Desc 列表
  29. * @Author Gorden
  30. * @Date 2024/3/28 15:01
  31. *
  32. * @param Request $request
  33. * @return Response
  34. * @throws \support\exception\BusinessException
  35. */
  36. public function select(Request $request): Response
  37. {
  38. $joinCouponCategoryId = $request->get('join_coupon_category_id', []);
  39. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  40. if (!empty($joinCouponCategoryId)) {
  41. $where['join_coupon_category_id'] = ['in', implode(',', $joinCouponCategoryId)];
  42. }
  43. if (!empty($where['coupon_addtimes'])){
  44. $where['coupon_addtimes'][0] = strtotime($where['coupon_addtimes'][0]);
  45. $where['coupon_addtimes'][1] = strtotime($where['coupon_addtimes'][1]);
  46. }
  47. $order = $request->get('order', 'desc');
  48. $field = $field ?? 'coupon_addtimes';
  49. $query = $this->doSelect($where, $field, $order);
  50. return $this->doFormat($query, $format, $limit);
  51. }
  52. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  53. {
  54. $model = $this->model->with([
  55. 'category' => function ($query) {
  56. $query->select('category_id', 'category_name');
  57. },
  58. 'user',
  59. 'detail'
  60. ]);
  61. foreach ($where as $column => $value) {
  62. if (is_array($value)) {
  63. if ($value[0] === 'like' || $value[0] === 'not like') {
  64. $model = $model->where($column, $value[0], "%$value[1]%");
  65. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  66. $model = $model->where($column, $value[0], $value[1]);
  67. } elseif ($value[0] == 'in' && !empty($value[1])) {
  68. $valArr = $value[1];
  69. if (is_string($value[1])) {
  70. $valArr = explode(",", trim($value[1]));
  71. }
  72. $model = $model->whereIn($column, $valArr);
  73. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  74. $valArr = $value[1];
  75. if (is_string($value[1])) {
  76. $valArr = explode(",", trim($value[1]));
  77. }
  78. $model = $model->whereNotIn($column, $valArr);
  79. } elseif ($value[0] == 'null') {
  80. $model = $model->whereNull($column);
  81. } elseif ($value[0] == 'not null') {
  82. $model = $model->whereNotNull($column);
  83. } elseif ($value[0] !== '' || $value[1] !== '') {
  84. $model = $model->whereBetween($column, $value);
  85. }
  86. } else {
  87. $model = $model->where($column, $value);
  88. }
  89. }
  90. if ($field) {
  91. $model = $model->orderBy($field, $order);
  92. }
  93. return $model;
  94. }
  95. protected function afterQuery($items)
  96. {
  97. foreach ($items as &$item) {
  98. if (!empty($item['coupon_json'])) {
  99. $couponJson = json_decode($item['coupon_json'], true);
  100. if (isset($couponJson['member'])) {
  101. if (isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  102. $item['coupon_use_member'] = 'member';
  103. $item['memberList'] = $couponJson['member']['list'];
  104. } else if (isset($couponJson['member']['where']) && !empty($couponJson['member']['where'])) {
  105. if (trim($couponJson['member']['where']) == '1') {
  106. $item['coupon_use_member'] = 'all';
  107. } else {
  108. $item['coupon_use_member'] = 'condition';
  109. $where = str_replace('`', '', urldecode($couponJson['member']['where']));
  110. $whereArr = explode('=', $where);
  111. if (isset($whereArr[0]) && trim($whereArr[0]) == 'member_is_vip') {
  112. $item['condition'] = 'is_vip';
  113. } else if (isset($whereArr[0]) && trim($whereArr[0]) == 'member_classify') {
  114. if (isset($whereArr[1]) && str_replace("'", '', trim($whereArr[1])) == 'MEMBER') {
  115. $item['condition'] = 'is_member';
  116. } else if (isset($whereArr[1]) && str_replace("'", '', trim($whereArr[1])) == 'EMPLOY') {
  117. $item['condition'] = 'is_employ';
  118. }
  119. }
  120. }
  121. }
  122. }
  123. if (isset($couponJson['premises'])) {
  124. $item['premises'] = $couponJson['premises'];
  125. } else {
  126. $item['premises_range'] = 'all';
  127. }
  128. }
  129. if (!empty($item['coupon_validdate_begin']) && !empty($item['coupon_validdate_end'])) {
  130. $item['coupon_use_time'] = 'date';
  131. } elseif ($item['coupon_validdate_day']) {
  132. $item['coupon_use_time'] = 'day';
  133. }
  134. $item['member_count'] = 0;
  135. $item['pending_count'] = 0;
  136. $item['used_count'] = 0;
  137. if (!empty($item['detail'])) {
  138. foreach ($item['detail'] as $detail) {
  139. if (!empty($detail['join_coupon_detail_member_id'])) {
  140. $item['member_count'] += 1;
  141. }
  142. if ($detail['coupon_detail_status'] == 'PENDING') {
  143. $item['pending_count'] += 1;
  144. } elseif ($detail['coupon_detail_status'] == 'USED') {
  145. $item['used_count'] += 1;
  146. }
  147. }
  148. }
  149. unset($item['detail']);
  150. }
  151. return $items;
  152. }
  153. public function selectList()
  154. {
  155. $coupons = Coupon::where('coupon_status', 'ACTIVED')
  156. ->select('coupon_id', 'coupon_name')
  157. ->orderBy('coupon_addtimes', 'DESC')
  158. ->get()
  159. ->toArray();
  160. return json_success('', $coupons);
  161. }
  162. // public function afterQuery($items)
  163. // {
  164. // foreach ($items as &$item) {
  165. // $item->coupon_begindate = date('Y-m-d H:i:s', $item->coupon_begindate);
  166. // $item->coupon_enddate = date('Y-m-d H:i:s', $item->coupon_enddate);
  167. // }
  168. //
  169. // return $items;
  170. // }
  171. /**
  172. * @Desc 添加优惠券
  173. * @Author Gorden
  174. * @Date 2024/8/14 15:16
  175. *
  176. * @param Request $request
  177. * @return Response
  178. */
  179. public function insert(Request $request): Response
  180. {
  181. if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
  182. return json_fail($this->validateClass->getError());
  183. }
  184. $goods = $request->post('goodsContentList', []);
  185. // if (empty($goods)) {
  186. // return json_fail("请选择关联的产品");
  187. // }
  188. Db::beginTransaction();
  189. try {
  190. $data = $this->insertInput($request);
  191. $data['coupon_creator_user_id'] = JwtToken::getCurrentId();
  192. $this->doInsert($data);
  193. // 关联优惠券和商品、规格
  194. $this->insertCouponGoods($goods, $data['coupon_id']);
  195. if ($data['coupon_number'] > 0) {
  196. $this->generateCouponDetail($data['coupon_id'], $data['coupon_status'], $data['coupon_number']);
  197. }
  198. Db::commit();
  199. return json_success('success');
  200. } catch (BusinessException $customException) {
  201. Db::rollBack();
  202. dump($customException->getMessage());
  203. return json_fail($customException->getMessage());
  204. } catch (\Exception $e) {
  205. Db::rollBack();
  206. dump($e->getMessage());
  207. return json_fail('数据写入失败');
  208. }
  209. }
  210. /**
  211. * @Desc 关联优惠券、产品、规格
  212. * @Author Gorden
  213. * @Date 2024/8/14 14:32
  214. *
  215. * @param $goods
  216. * @param $couponId
  217. * @return void
  218. * @throws BusinessException
  219. */
  220. public function insertCouponGoods($goods, $couponId)
  221. {
  222. try {
  223. foreach ($goods as $good) {
  224. CouponGoods::insert([
  225. 'join_goods_coupon_id' => $couponId,
  226. 'join_coupon_goods_id' => $good['goods_id'],
  227. 'join_coupon_goods_sku_id' => $good['sku_id'],
  228. 'coupon_goods_json' => '[]',
  229. 'coupon_goods_extend_json' => '[]',
  230. 'coupon_goods_addtimes' => time()
  231. ]);
  232. }
  233. } catch (\Exception $e) {
  234. throw new BusinessException("关联产品失败");
  235. }
  236. }
  237. protected function insertInput(Request $request): array
  238. {
  239. $params = $request->post();
  240. $data = $this->inputFilter($params);
  241. $data['coupon_id'] = "CU" . date("ymdH") . random_string(6, 'up');
  242. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  243. $data['coupon_validdate_day'] = 0;
  244. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  245. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  246. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  247. $data['coupon_validdate_begin'] = '';
  248. $data['coupon_validdate_end'] = '';
  249. }
  250. $couponJson = [];
  251. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  252. $couponJson['member']['list'] = $params['member_list'];
  253. $couponJson['member']['range'] = '';
  254. $couponJson['member']['where'] = '';
  255. } else if ($params['coupon_use_member'] == 'condition') {
  256. $couponJson['member']['list'] = [];
  257. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  258. $couponJson['member']['range'] = 'VIP会员';
  259. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  260. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  261. $couponJson['member']['range'] = '公司员工';
  262. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  263. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  264. $couponJson['member']['range'] = '会员';
  265. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  266. }
  267. } else if ($params['coupon_use_member'] == 'all') {
  268. $couponJson['member']['list'] = [];
  269. $couponJson['member']['range'] = '全部会员';
  270. $couponJson['member']['where'] = '';
  271. }
  272. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  273. $couponJson['premises_range'] = '所有门店可用';
  274. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  275. $couponJson['premises'] = $params['premises'];
  276. $couponJson['premises_range'] = '部分门店可用';
  277. }
  278. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  279. return $data;
  280. }
  281. public function customSend(Request $request)
  282. {
  283. $chooseCoupons = $request->post('chooseCoupons', []);
  284. $couponUseMember = $request->post('coupon_use_member', '');
  285. $memberList = $request->post('member_list', []);
  286. $condition = $request->post('condition', '');
  287. if ($couponUseMember == 'condition') {
  288. if ($condition == 'is_employ') {
  289. $memberList = Member::where('member_classify', 'EMPLOY')->pluck('member_id')->toArray();
  290. } elseif ($condition == 'is_member') {
  291. $memberList = Member::where('member_classify', 'MEMBER')->pluck('member_id')->toArray();
  292. } elseif ($condition == 'is_vip') {
  293. $memberList = Member::where('member_is_vip', 'Y')->pluck('member_id')->toArray();
  294. }
  295. }
  296. $couponNbr = [];
  297. Db::beginTransaction();
  298. try {
  299. $couponIds = array_column($chooseCoupons, 'id');
  300. $coupons = Coupon::whereIn('coupon_id', $couponIds)->get()->toArray();
  301. foreach ($coupons as $coupon) {
  302. foreach ($chooseCoupons as $chooseCoupon) {
  303. if ($chooseCoupon['id'] == $coupon['coupon_id']) {
  304. if (empty($chooseCoupon['gain_datetime'])) {
  305. $chooseCoupon['gain_datetime'] = date('Y-m-d H:i:s');
  306. }
  307. $params['coupon_id'] = $coupon['coupon_id'];
  308. $params['coupon_detail_gain_datetime'] = date('Y-m-d H:i:s', strtotime($chooseCoupon['gain_datetime']));
  309. if (($coupon['coupon_validdate_day'] == 0 || $coupon['coupon_validdate_day'] == '') && !empty($coupon['coupon_validdate_end'])) {
  310. $params['coupon_detail_deadline_datetime'] = $coupon['coupon_validdate_end'];
  311. } elseif ($coupon['coupon_validdate_day'] > 0) {
  312. $endUnix = strtotime($chooseCoupon['gain_datetime']);
  313. $params['coupon_detail_deadline_datetime'] = date('Y-m-d H:i:s', $endUnix + ($coupon['coupon_validdate_day'] * 24 * 3600) -1);
  314. }
  315. foreach ($memberList as $item) {
  316. $params['member_id'] = $item;
  317. if ($chooseCoupon['nbr'] > 0) {
  318. // 有发行数量
  319. if ($coupon['coupon_number'] != 0){
  320. // 查询共发行了多少张了
  321. $count = CouponDetail::where('join_detail_coupon_id',$coupon['coupon_id'])->count();
  322. if (!isset($couponNbr[$coupon['coupon_id']])){
  323. $couponNbr[$coupon['coupon_id']] = $count;
  324. }
  325. if ($couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'] > $coupon['coupon_number']){
  326. throw new BusinessException($coupon['coupon_name']."超出发行数量");
  327. }
  328. $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'];
  329. }
  330. for ($i = 0; $i < $chooseCoupon['nbr']; $i++) {
  331. CouponDetailService::customSendCoupon($params);
  332. }
  333. }
  334. }
  335. }
  336. }
  337. }
  338. Db::commit();
  339. return json_success("发放成功");
  340. } catch (BusinessException $e) {
  341. Db::rollBack();
  342. return json_fail($e->getMessage());
  343. } catch (\Exception $e) {
  344. Db::rollBack();
  345. return json_fail('优惠券发放失败');
  346. }
  347. }
  348. /**
  349. * @Desc 修改优惠券
  350. * @Author Gorden
  351. * @Date 2024/8/14 15:48
  352. *
  353. * @param Request $request
  354. * @return Response
  355. */
  356. public function update(Request $request): Response
  357. {
  358. if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
  359. return json_fail($this->validateClass->getError());
  360. }
  361. $params = $request->post();
  362. Db::beginTransaction();
  363. try {
  364. [$id, $data] = $this->updateInput($request);
  365. $originCouponNumber = $data['origin_coupon_number'];
  366. $originCouponValiddateDay = $data['origin_coupon_validdate_day'];
  367. $originCouponValiddateEnd = $data['origin_coupon_validdate_end'];
  368. unset($data['origin_coupon_number'], $data['origin_coupon_validdate_day'], $data['origin_coupon_validdate_end']);
  369. $this->updateCouponGoods($request->post('goodsContentList'), $id);
  370. if ($originCouponNumber == 0 && $data['coupon_number'] != 0) {
  371. // 查已领取多少了
  372. $detailCount = CouponDetail::where('join_detail_coupon_id', $id)->count();
  373. if ($detailCount < $data['coupon_number']) {
  374. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $detailCount);
  375. }
  376. } else if ($originCouponNumber < $data['coupon_number']) {
  377. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $originCouponNumber);
  378. } else if ($originCouponNumber > $data['coupon_number']) {
  379. CouponDetail::where('join_detail_coupon_id', $id)
  380. ->where('join_coupon_detail_member_id', '')
  381. ->limit($originCouponNumber - $data['coupon_number'])
  382. ->delete();
  383. }
  384. // 修改时间了
  385. if ($params['coupon_use_time'] == 'day' && $originCouponValiddateDay != $data['coupon_validdate_day']) {
  386. $this->updateDetailTimeForDay($id, $data['coupon_validdate_day']);
  387. } elseif ($params['coupon_use_time'] == 'date' && $originCouponValiddateEnd != $data['coupon_validdate_end']) {
  388. $this->updateDetailTimeForDate($id, $data['coupon_validdate_end']);
  389. }
  390. // 激活状态,初始改为待领取
  391. if ($data['coupon_status'] == 'ACTIVED') {
  392. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', 'INIT')->update(['coupon_detail_status' => 'PENDING']);
  393. } elseif ($data['coupon_status'] == 'DISABLED') { // 禁用状态,未领取未使用的都是禁用
  394. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', '<>', 'USED')->update(['coupon_detail_status' => 'DISABLED']);
  395. }
  396. $this->doUpdate($id, $data);
  397. Db::commit();
  398. return json_success('success');
  399. } catch (BusinessException $e) {
  400. Db::rollBack();
  401. return json_fail($e->getMessage());
  402. } catch (\Exception $e) {
  403. Db::rollBack();
  404. dump($e->getMessage());
  405. return json_fail('数据更新失败');
  406. }
  407. }
  408. public function updateDetailTimeForDay($couponId, $day)
  409. {
  410. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  411. ->where('coupon_detail_status', '<>', 'USED')
  412. ->where('coupon_detail_deadline_datetime', '<>', '')
  413. ->get()
  414. ->toArray();
  415. try {
  416. foreach ($details as $detail) {
  417. $couponDetailGainDatetime = strtotime($detail['coupon_detail_gain_datetime']);
  418. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  419. ->update([
  420. 'coupon_detail_deadline_datetime' => date('Y-m-d H:i:s', $couponDetailGainDatetime + ($day * 24 * 3600))
  421. ]);
  422. }
  423. } catch (\Exception $e) {
  424. dump($e->getMessage());
  425. throw new BusinessException("优惠券更新失败");
  426. }
  427. }
  428. public function updateDetailTimeForDate($couponId, $endDate)
  429. {
  430. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  431. ->where('coupon_detail_status', '<>', 'USED')
  432. ->where('coupon_detail_deadline_datetime', '<>', '')
  433. ->get()
  434. ->toArray();
  435. try {
  436. foreach ($details as $detail) {
  437. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  438. ->update([
  439. 'coupon_detail_deadline_datetime' => $endDate
  440. ]);
  441. }
  442. } catch (\Exception $e) {
  443. dump($e->getMessage());
  444. throw new BusinessException("优惠券更新失败");
  445. }
  446. }
  447. public function updateCouponGoods($goods, $couponId)
  448. {
  449. try {
  450. $couponGoodsIds = CouponGoods::where('join_goods_coupon_id', $couponId)->pluck('join_coupon_goods_id')->toArray();
  451. $goodsIds = array_column($goods, 'goods_id');
  452. // 新的差集
  453. $goodsDiff = array_diff($goodsIds, $couponGoodsIds);
  454. // 旧的差集
  455. $couponDiff = array_diff($couponGoodsIds, $goodsIds);
  456. foreach ($goods as $good) {
  457. // 更新两个中都有的
  458. if (in_array($good['goods_id'], $couponGoodsIds)) {
  459. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $good['goods_id'])->update(['join_coupon_goods_sku_id' => $good['sku_id']]);
  460. } elseif (in_array($good['goods_id'], $goodsDiff)) { // 新加的
  461. CouponGoods::insert([
  462. 'join_goods_coupon_id' => $couponId,
  463. 'join_coupon_goods_id' => $good['goods_id'],
  464. 'join_coupon_goods_sku_id' => $good['sku_id'],
  465. 'coupon_goods_json' => '[]',
  466. 'coupon_goods_extend_json' => '[]',
  467. 'coupon_goods_addtimes' => time()
  468. ]);
  469. }
  470. }
  471. if (!empty($couponDiff)) { // 去掉的
  472. foreach ($couponDiff as $item) {
  473. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $item)->delete();
  474. }
  475. }
  476. } catch (\Exception $e) {
  477. throw new BusinessException('关联产品更新失败');
  478. }
  479. }
  480. protected function updateInput(Request $request): array
  481. {
  482. $params = $request->post();
  483. $primary_key = $this->model->getKeyName();
  484. $id = $request->post($primary_key);
  485. $data = $this->inputFilter($params);
  486. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  487. $data['coupon_validdate_day'] = 0;
  488. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  489. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  490. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  491. $data['coupon_validdate_begin'] = '';
  492. $data['coupon_validdate_end'] = '';
  493. }
  494. $model = $this->model->find($id);
  495. // 原数量
  496. $data['origin_coupon_number'] = $model->coupon_number;
  497. // 原优惠天数
  498. $data['origin_coupon_validdate_day'] = $model->coupon_validdate_day;
  499. // 原结束时间
  500. $data['origin_coupon_validdate_end'] = $model->coupon_validdate_end;
  501. if (!$model) {
  502. throw new BusinessException('记录不存在', 2);
  503. }
  504. $couponJson = [];
  505. if (!empty($model->coupon_json)) {
  506. $couponJson = json_decode($model->coupon_json, true);
  507. }
  508. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  509. $couponJson['member']['list'] = $params['member_list'];
  510. // if (isset($couponJson['member']['range'])) {
  511. $couponJson['member']['range'] = '';
  512. // }
  513. // if (isset($couponJson['member']['where'])) {
  514. $couponJson['member']['where'] = '';
  515. // }
  516. } else if ($params['coupon_use_member'] == 'condition') {
  517. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  518. $couponJson['member']['range'] = 'VIP会员';
  519. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  520. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  521. $couponJson['member']['range'] = '公司员工';
  522. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  523. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  524. $couponJson['member']['range'] = '会员';
  525. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  526. }
  527. // if (isset($couponJson['member']['list'])) {
  528. $couponJson['member']['list'] = [];
  529. // }
  530. } else if ($params['coupon_use_member'] == 'all') {
  531. $couponJson['member']['list'] = [];
  532. $couponJson['member']['range'] = '全部会员';
  533. $couponJson['member']['where'] = '';
  534. if (isset($couponJson['member']['list'])) {
  535. $couponJson['member']['list'] = [];
  536. }
  537. }
  538. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  539. $couponJson['premises_range'] = '所有门店可用';
  540. unset($couponJson['premises']);
  541. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  542. $couponJson['premises'] = $params['premises'];
  543. $couponJson['premises_range'] = '部分门店可用';
  544. }
  545. if (empty($data['coupon_validdate_day'])) {
  546. $data['coupon_validdate_day'] = 0;
  547. }
  548. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  549. unset($data[$primary_key]);
  550. return [$id, $data];
  551. }
  552. /**
  553. * 优惠券详情
  554. */
  555. public function info(Request $request): Response
  556. {
  557. $couponId = $request->get('coupon_id', '');
  558. if (!$couponId) {
  559. return json_fail('参数异常');
  560. }
  561. $coupon = Coupon::where('coupon_id', $couponId)->first();
  562. if (!$coupon) {
  563. return json_fail('数据异常');
  564. }
  565. // 拼选择的商品
  566. $couponGoods = CouponGoods::with([
  567. 'goods' => function ($query) {
  568. $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');
  569. },
  570. 'skus',
  571. 'sku'
  572. ])->where('join_goods_coupon_id', $couponId)
  573. ->get()
  574. ->toArray();
  575. $goodsIds = [];
  576. $goodsContent = [];
  577. foreach ($couponGoods as $couponGood) {
  578. $goodsIds[] = $couponGood['join_coupon_goods_id'];
  579. $content = [
  580. 'goods_id' => $couponGood['join_coupon_goods_id'],
  581. 'sku_id' => $couponGood['join_coupon_goods_sku_id'],
  582. ];
  583. if (isset($couponGood['goods'])) {
  584. $content['goods_name'] = $couponGood['goods']['name'];
  585. $content['goods_classify'] = $couponGood['goods']['goods_classify'];
  586. $content['goods_cover'] = getenv('STORAGE_DOMAIN') . $couponGood['goods']['goods_cover'];
  587. }
  588. if (isset($couponGood['sku']) && isset($couponGood['sku']['goods_sku_specs_json'])) {
  589. // $skuSpecsJson = json_decode($couponGood['sku']['goods_sku_specs_json'], true);
  590. // $skuName = '';
  591. // foreach ($skuSpecsJson as $item) {
  592. // if (is_array($item)) {
  593. // $item = implode('', $item);
  594. // }
  595. // $skuName .= $item . ',';
  596. // }
  597. // $content['sku_name'] = rtrim($skuName, ',');
  598. $content['goods_sales_price'] = $couponGood['sku']['goods_sku_sales_price'];
  599. }
  600. if (isset($couponGood['skus'])) {
  601. foreach ($couponGood['skus'] as $key => $skus) {
  602. if (!empty($skus['goods_sku_specs_json'])) {
  603. $skuSpecsJson = json_decode($skus['goods_sku_specs_json'], true);
  604. $skuName = '';
  605. foreach ($skuSpecsJson as $item) {
  606. if (is_array($item)) {
  607. $item = implode('', $item);
  608. }
  609. $skuName .= $item . ',';
  610. }
  611. $couponGood['skus'][$key]['sku_name'] = rtrim($skuName, ',');
  612. }
  613. }
  614. $content['skus'] = $couponGood['skus'];
  615. }
  616. $goodsContent[] = $content;
  617. }
  618. // 选中的会员
  619. $memberLists = [];
  620. // 可用门店
  621. $premises = [];
  622. if (!empty($coupon->coupon_json)) {
  623. $couponJson = json_decode($coupon->coupon_json, true);
  624. if (isset($couponJson['member']) && isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  625. $res = Db::table('member')
  626. ->leftjoin('member_cert', 'member.member_id', '=', 'member_cert.join_cert_member_id')
  627. ->leftjoin('member_info', 'member.member_id', '=', 'member_info.join_info_member_id')
  628. ->select('member.member_id', 'member.member_mobile', 'member_cert.member_cert_name', 'member_info.member_info_nickname')
  629. ->where('member_status', 'ACTIVED')
  630. ->whereIn('member_id', $couponJson['member']['list'])
  631. ->get();
  632. $memberLists = [];
  633. foreach ($res as $item) {
  634. $name = '';
  635. if (!empty($item->member_cert_name)) {
  636. $name = $item->member_cert_name;
  637. } else if (!empty($item->member_info_nickname)) {
  638. $name = $item->member_info_nickname;
  639. }
  640. $value = !empty($name) ? $name . '-' : '';
  641. if ($item->member_mobile != '0000') {
  642. $value .= $item->member_mobile;
  643. }
  644. if (empty($value)) {
  645. $value = $item->member_mobile;
  646. }
  647. $value = rtrim($value, '-');
  648. $memberLists[] = [
  649. 'key' => $item->member_id,
  650. 'value' => $value,
  651. ];
  652. }
  653. }
  654. if (isset($couponJson['premises']) && !empty($couponJson['premises'])) {
  655. $premises = SysDept::whereIn('dept_id', $couponJson['premises'])
  656. ->select('dept_id', 'dept_name')
  657. ->get()
  658. ->toArray();
  659. }
  660. }
  661. $data = [
  662. 'goods_ids' => $goodsIds,
  663. 'goods_content' => $goodsContent,
  664. 'member_lists' => $memberLists,
  665. 'premises_list' => $premises
  666. ];
  667. return json_success('', $data);
  668. }
  669. /**
  670. * 删除
  671. * @param Request $request
  672. * @return Response
  673. * @throws BusinessException
  674. */
  675. public function delete(Request $request): Response
  676. {
  677. $ids = $this->deleteInput($request);
  678. Db::beginTransaction();
  679. try {
  680. // 删除优惠券关联的产品
  681. foreach ($ids as $id) {
  682. $couponDetail = CouponDetail::with([
  683. 'coupon' => function ($query) {
  684. $query->select('coupon_id', 'coupon_name');
  685. }
  686. ])->where('join_detail_coupon_id', $id)
  687. ->where('join_coupon_detail_member_id', '<>', '')
  688. ->first();
  689. if (!empty($couponDetail)) {
  690. Db::rollBack();
  691. return json_fail($couponDetail->coupon && $couponDetail->coupon->coupon_name ? $couponDetail->coupon->coupon_name . "已被领取,无法删除,请禁用" : "删除的优惠券中有已被领取的,无法删除,请禁用");
  692. }
  693. CouponGoods::where('join_goods_coupon_id', $id)->delete();
  694. CouponDetail::where('join_detail_coupon_id', $id)->delete();
  695. }
  696. $this->doDelete($ids);
  697. Db::commit();
  698. return json_success('success');
  699. } catch (\Exception $e) {
  700. dump($e->getMessage());
  701. Db::rollBack();
  702. return json_fail('删除失败');
  703. }
  704. }
  705. private function generateCouponDetail($couponId, $couponStatus, $nbr)
  706. {
  707. for ($i = 0; $i < intval($nbr); $i++) {
  708. CouponDetail::insert([
  709. 'coupon_detail_id' => 'CUDT' . date("ymdH") . random_string(6, 'up'),
  710. 'join_detail_coupon_id' => $couponId,
  711. 'coupon_detail_status' => $couponStatus == 'ACTIVED' ? 'PENDING' : 'INIT',
  712. 'coupon_detail_addtimes' => time()
  713. ]);
  714. }
  715. }
  716. }