CouponController.php 34 KB

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