CouponController.php 29 KB

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