CouponController.php 39 KB

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