CouponController.php 33 KB

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