CouponController.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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("周期数据异常");
  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'])->count();
  404. if (!isset($couponNbr[$coupon['coupon_id']])) {
  405. $couponNbr[$coupon['coupon_id']] = $count;
  406. }
  407. if ($couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'] > $coupon['coupon_number']) {
  408. throw new BusinessException($coupon['coupon_name'] . "超出发行数量");
  409. }
  410. $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'];
  411. }
  412. for ($i = 0; $i < $chooseCoupon['nbr']; $i++) {
  413. CouponDetailService::customSendCoupon($params);
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. Db::commit();
  421. return json_success("发放成功");
  422. } catch (BusinessException $e) {
  423. Db::rollBack();
  424. return json_fail($e->getMessage());
  425. } catch (\Exception $e) {
  426. Db::rollBack();
  427. return json_fail('优惠券发放失败');
  428. }
  429. }
  430. /**
  431. * @Desc 修改优惠券
  432. * @Author Gorden
  433. * @Date 2024/8/14 15:48
  434. *
  435. * @param Request $request
  436. * @return Response
  437. */
  438. public function update(Request $request): Response
  439. {
  440. if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
  441. return json_fail($this->validateClass->getError());
  442. }
  443. $params = $request->post();
  444. Db::beginTransaction();
  445. try {
  446. [$id, $data] = $this->updateInput($request);
  447. $originCouponNumber = $data['origin_coupon_number'];
  448. $originCouponValiddateDay = $data['origin_coupon_validdate_day'];
  449. $originCouponValiddateEnd = $data['origin_coupon_validdate_end'];
  450. unset($data['origin_coupon_number'], $data['origin_coupon_validdate_day'], $data['origin_coupon_validdate_end']);
  451. $this->updateCouponGoods($request->post('goodsContentList'), $id);
  452. if ($originCouponNumber == 0 && $data['coupon_number'] != 0) {
  453. // 查已领取多少了
  454. $detailCount = CouponDetail::where('join_detail_coupon_id', $id)->count();
  455. if ($detailCount < $data['coupon_number']) {
  456. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $detailCount);
  457. }
  458. } else if ($originCouponNumber < $data['coupon_number']) {
  459. $this->generateCouponDetail($id, $data['coupon_status'], $data['coupon_number'] - $originCouponNumber);
  460. } else if ($originCouponNumber > $data['coupon_number']) {
  461. CouponDetail::where('join_detail_coupon_id', $id)
  462. ->where('join_coupon_detail_member_id', '')
  463. ->limit($originCouponNumber - $data['coupon_number'])
  464. ->delete();
  465. }
  466. // 修改时间了
  467. if ($params['coupon_use_time'] == 'day' && $originCouponValiddateDay != $data['coupon_validdate_day']) {
  468. $this->updateDetailTimeForDay($id, $data['coupon_validdate_day']);
  469. } elseif ($params['coupon_use_time'] == 'date' && $originCouponValiddateEnd != $data['coupon_validdate_end']) {
  470. $this->updateDetailTimeForDate($id, $data['coupon_validdate_end']);
  471. }
  472. // 激活状态,初始改为待领取
  473. if ($data['coupon_status'] == 'ACTIVED') {
  474. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', 'INIT')->update(['coupon_detail_status' => 'PENDING']);
  475. } elseif ($data['coupon_status'] == 'DISABLED') { // 禁用状态,未领取未使用的都是禁用
  476. CouponDetail::where('join_detail_coupon_id', $id)->where('coupon_detail_status', '<>', 'USED')->update(['coupon_detail_status' => 'DISABLED']);
  477. }
  478. $this->doUpdate($id, $data);
  479. Db::commit();
  480. return json_success('success');
  481. } catch (BusinessException $e) {
  482. Db::rollBack();
  483. return json_fail($e->getMessage());
  484. } catch (\Exception $e) {
  485. Db::rollBack();
  486. dump($e->getMessage());
  487. return json_fail('数据更新失败');
  488. }
  489. }
  490. public function updateDetailTimeForDay($couponId, $day)
  491. {
  492. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  493. ->where('coupon_detail_status', '<>', 'USED')
  494. ->where('coupon_detail_deadline_datetime', '<>', '')
  495. ->get()
  496. ->toArray();
  497. try {
  498. foreach ($details as $detail) {
  499. $couponDetailGainDatetime = strtotime($detail['coupon_detail_gain_datetime']);
  500. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  501. ->update([
  502. 'coupon_detail_deadline_datetime' => date('Y-m-d H:i:s', $couponDetailGainDatetime + ($day * 24 * 3600))
  503. ]);
  504. }
  505. } catch (\Exception $e) {
  506. dump($e->getMessage());
  507. throw new BusinessException("优惠券更新失败");
  508. }
  509. }
  510. public function updateDetailTimeForDate($couponId, $endDate)
  511. {
  512. $details = CouponDetail::where('join_detail_coupon_id', $couponId)
  513. ->where('coupon_detail_status', '<>', 'USED')
  514. ->where('coupon_detail_deadline_datetime', '<>', '')
  515. ->get()
  516. ->toArray();
  517. try {
  518. foreach ($details as $detail) {
  519. CouponDetail::where('coupon_detail_id', $detail['coupon_detail_id'])
  520. ->update([
  521. 'coupon_detail_deadline_datetime' => $endDate
  522. ]);
  523. }
  524. } catch (\Exception $e) {
  525. dump($e->getMessage());
  526. throw new BusinessException("优惠券更新失败");
  527. }
  528. }
  529. public function updateCouponGoods($goods, $couponId)
  530. {
  531. try {
  532. $couponGoodsIds = CouponGoods::where('join_goods_coupon_id', $couponId)->pluck('join_coupon_goods_id')->toArray();
  533. $goodsIds = array_column($goods, 'goods_id');
  534. // 新的差集
  535. $goodsDiff = array_diff($goodsIds, $couponGoodsIds);
  536. // 旧的差集
  537. $couponDiff = array_diff($couponGoodsIds, $goodsIds);
  538. foreach ($goods as $good) {
  539. // 更新两个中都有的
  540. if (in_array($good['goods_id'], $couponGoodsIds)) {
  541. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $good['goods_id'])->update(['join_coupon_goods_sku_id' => $good['sku_id']]);
  542. } elseif (in_array($good['goods_id'], $goodsDiff)) { // 新加的
  543. CouponGoods::insert([
  544. 'join_goods_coupon_id' => $couponId,
  545. 'join_coupon_goods_id' => $good['goods_id'],
  546. 'join_coupon_goods_sku_id' => $good['sku_id'],
  547. 'coupon_goods_json' => '[]',
  548. 'coupon_goods_extend_json' => '[]',
  549. 'coupon_goods_addtimes' => time()
  550. ]);
  551. }
  552. }
  553. if (!empty($couponDiff)) { // 去掉的
  554. foreach ($couponDiff as $item) {
  555. CouponGoods::where('join_goods_coupon_id', $couponId)->where('join_coupon_goods_id', $item)->delete();
  556. }
  557. }
  558. } catch (\Exception $e) {
  559. throw new BusinessException('关联产品更新失败');
  560. }
  561. }
  562. protected function updateInput(Request $request): array
  563. {
  564. $params = $request->post();
  565. $primary_key = $this->model->getKeyName();
  566. $id = $request->post($primary_key);
  567. $data = $this->inputFilter($params);
  568. if (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'date') {
  569. $data['coupon_validdate_day'] = 0;
  570. $data['coupon_validdate_begin'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_begin']));
  571. $data['coupon_validdate_end'] = date("Y-m-d H:i:s", strtotime($data['coupon_validdate_end']));
  572. } elseif (!empty($params['coupon_use_time']) && $params['coupon_use_time'] == 'day') {
  573. $data['coupon_validdate_begin'] = '';
  574. $data['coupon_validdate_end'] = '';
  575. }
  576. $model = $this->model->find($id);
  577. // 原数量
  578. $data['origin_coupon_number'] = $model->coupon_number;
  579. // 原优惠天数
  580. $data['origin_coupon_validdate_day'] = $model->coupon_validdate_day;
  581. // 原结束时间
  582. $data['origin_coupon_validdate_end'] = $model->coupon_validdate_end;
  583. if (!$model) {
  584. throw new BusinessException('记录不存在', 2);
  585. }
  586. $couponJson = [];
  587. if (!empty($model->coupon_json)) {
  588. $couponJson = json_decode($model->coupon_json, true);
  589. }
  590. if ($params['coupon_use_member'] == 'member' && isset($params['member_list'])) {
  591. $couponJson['member']['list'] = $params['member_list'];
  592. // if (isset($couponJson['member']['range'])) {
  593. $couponJson['member']['range'] = '';
  594. // }
  595. // if (isset($couponJson['member']['where'])) {
  596. $couponJson['member']['where'] = '';
  597. // }
  598. } else if ($params['coupon_use_member'] == 'condition') {
  599. if (isset($params['condition']) && $params['condition'] == 'is_vip') {
  600. $couponJson['member']['range'] = 'VIP会员';
  601. $couponJson['member']['where'] = urlencode(" `member_is_vip` = 'Y'");
  602. } elseif (isset($params['condition']) && $params['condition'] == 'is_employ') {
  603. $couponJson['member']['range'] = '公司员工';
  604. $couponJson['member']['where'] = urlencode(" `member_classify` = 'EMPLOY'");
  605. } elseif (isset($params['condition']) && $params['condition'] == 'is_member') {
  606. $couponJson['member']['range'] = '会员';
  607. $couponJson['member']['where'] = urlencode(" `member_classify` = 'MEMBER'");
  608. }
  609. // if (isset($couponJson['member']['list'])) {
  610. $couponJson['member']['list'] = [];
  611. // }
  612. } else if ($params['coupon_use_member'] == 'all') {
  613. $couponJson['member']['list'] = [];
  614. $couponJson['member']['range'] = '全部会员';
  615. $couponJson['member']['where'] = '';
  616. if (isset($couponJson['member']['list'])) {
  617. $couponJson['member']['list'] = [];
  618. }
  619. }
  620. if (!empty($params['premises_range']) && $params['premises_range'] == 'all') {
  621. $couponJson['premises_range'] = '所有门店可用';
  622. unset($couponJson['premises']);
  623. } elseif (!empty($params['premises_range']) && $params['premises_range'] == 'part') {
  624. $couponJson['premises'] = $params['premises'];
  625. $couponJson['premises_range'] = '部分门店可用';
  626. }
  627. if (empty($data['coupon_validdate_day'])) {
  628. $data['coupon_validdate_day'] = 0;
  629. }
  630. $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
  631. $data['coupon_period_json'] = '[]';
  632. // 处理周期优惠券
  633. if ($params['coupon_is_period'] != 'N') {
  634. $this->disposePeriod($params);
  635. $data['coupon_period_json'] = json_encode([
  636. 'length' => $params['period'],
  637. 'unit' => $params['period_unit'],
  638. 'val' => $params['period_unit_num'],
  639. 'nbr' => $params['period_nbr']
  640. ]);
  641. }
  642. unset($data[$primary_key]);
  643. return [$id, $data];
  644. }
  645. /**
  646. * 优惠券详情
  647. */
  648. public function info(Request $request): Response
  649. {
  650. $couponId = $request->get('coupon_id', '');
  651. if (!$couponId) {
  652. return json_fail('参数异常');
  653. }
  654. $coupon = Coupon::where('coupon_id', $couponId)->first();
  655. if (!$coupon) {
  656. return json_fail('数据异常');
  657. }
  658. // 拼选择的商品
  659. $couponGoods = CouponGoods::with([
  660. 'goods' => function ($query) {
  661. $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');
  662. },
  663. 'skus',
  664. 'sku'
  665. ])->where('join_goods_coupon_id', $couponId)
  666. ->get()
  667. ->toArray();
  668. $goodsIds = [];
  669. $goodsContent = [];
  670. foreach ($couponGoods as $couponGood) {
  671. $goodsIds[] = $couponGood['join_coupon_goods_id'];
  672. $content = [
  673. 'goods_id' => $couponGood['join_coupon_goods_id'],
  674. 'sku_id' => $couponGood['join_coupon_goods_sku_id'],
  675. ];
  676. if (isset($couponGood['goods'])) {
  677. $content['goods_name'] = $couponGood['goods']['name'];
  678. $content['goods_classify'] = $couponGood['goods']['goods_classify'];
  679. $content['goods_cover'] = getenv('STORAGE_DOMAIN') . $couponGood['goods']['goods_cover'];
  680. }
  681. if (isset($couponGood['sku']) && isset($couponGood['sku']['goods_sku_specs_json'])) {
  682. // $skuSpecsJson = json_decode($couponGood['sku']['goods_sku_specs_json'], true);
  683. // $skuName = '';
  684. // foreach ($skuSpecsJson as $item) {
  685. // if (is_array($item)) {
  686. // $item = implode('', $item);
  687. // }
  688. // $skuName .= $item . ',';
  689. // }
  690. // $content['sku_name'] = rtrim($skuName, ',');
  691. $content['goods_sales_price'] = $couponGood['sku']['goods_sku_sales_price'];
  692. }
  693. if (isset($couponGood['skus'])) {
  694. foreach ($couponGood['skus'] as $key => $skus) {
  695. if (!empty($skus['goods_sku_specs_json'])) {
  696. $skuSpecsJson = json_decode($skus['goods_sku_specs_json'], true);
  697. $skuName = '';
  698. foreach ($skuSpecsJson as $item) {
  699. if (is_array($item)) {
  700. $item = implode('', $item);
  701. }
  702. $skuName .= $item . ',';
  703. }
  704. $couponGood['skus'][$key]['sku_name'] = rtrim($skuName, ',');
  705. }
  706. }
  707. $content['skus'] = $couponGood['skus'];
  708. }
  709. $goodsContent[] = $content;
  710. }
  711. // 选中的会员
  712. $memberLists = [];
  713. // 可用门店
  714. $premises = [];
  715. if (!empty($coupon->coupon_json)) {
  716. $couponJson = json_decode($coupon->coupon_json, true);
  717. if (isset($couponJson['member']) && isset($couponJson['member']['list']) && !empty($couponJson['member']['list'])) {
  718. $res = Db::table('member')
  719. ->leftjoin('member_cert', 'member.member_id', '=', 'member_cert.join_cert_member_id')
  720. ->leftjoin('member_info', 'member.member_id', '=', 'member_info.join_info_member_id')
  721. ->select('member.member_id', 'member.member_mobile', 'member_cert.member_cert_name', 'member_info.member_info_nickname')
  722. ->where('member_status', 'ACTIVED')
  723. ->whereIn('member_id', $couponJson['member']['list'])
  724. ->get();
  725. $memberLists = [];
  726. foreach ($res as $item) {
  727. $name = '';
  728. if (!empty($item->member_cert_name)) {
  729. $name = $item->member_cert_name;
  730. } else if (!empty($item->member_info_nickname)) {
  731. $name = $item->member_info_nickname;
  732. }
  733. $value = !empty($name) ? $name . '-' : '';
  734. if ($item->member_mobile != '0000') {
  735. $value .= $item->member_mobile;
  736. }
  737. if (empty($value)) {
  738. $value = $item->member_mobile;
  739. }
  740. $value = rtrim($value, '-');
  741. $memberLists[] = [
  742. 'key' => $item->member_id,
  743. 'value' => $value,
  744. ];
  745. }
  746. }
  747. if (isset($couponJson['premises']) && !empty($couponJson['premises'])) {
  748. $premises = SysDept::whereIn('dept_id', $couponJson['premises'])
  749. ->select('dept_id', 'dept_name')
  750. ->get()
  751. ->toArray();
  752. }
  753. }
  754. $data = [
  755. 'goods_ids' => $goodsIds,
  756. 'goods_content' => $goodsContent,
  757. 'member_lists' => $memberLists,
  758. 'premises_list' => $premises
  759. ];
  760. return json_success('', $data);
  761. }
  762. /**
  763. * 删除
  764. * @param Request $request
  765. * @return Response
  766. * @throws BusinessException
  767. */
  768. public function delete(Request $request): Response
  769. {
  770. $ids = $this->deleteInput($request);
  771. Db::beginTransaction();
  772. try {
  773. // 删除优惠券关联的产品
  774. foreach ($ids as $id) {
  775. $couponDetail = CouponDetail::with([
  776. 'coupon' => function ($query) {
  777. $query->select('coupon_id', 'coupon_name');
  778. }
  779. ])->where('join_detail_coupon_id', $id)
  780. ->where('join_coupon_detail_member_id', '<>', '')
  781. ->first();
  782. if (!empty($couponDetail)) {
  783. Db::rollBack();
  784. return json_fail($couponDetail->coupon && $couponDetail->coupon->coupon_name ? $couponDetail->coupon->coupon_name . "已被领取,无法删除,请禁用" : "删除的优惠券中有已被领取的,无法删除,请禁用");
  785. }
  786. CouponGoods::where('join_goods_coupon_id', $id)->delete();
  787. CouponDetail::where('join_detail_coupon_id', $id)->delete();
  788. }
  789. $this->doDelete($ids);
  790. Db::commit();
  791. return json_success('success');
  792. } catch (\Exception $e) {
  793. dump($e->getMessage());
  794. Db::rollBack();
  795. return json_fail('删除失败');
  796. }
  797. }
  798. private function generateCouponDetail($couponId, $couponStatus, $nbr)
  799. {
  800. for ($i = 0; $i < intval($nbr); $i++) {
  801. CouponDetail::insert([
  802. 'coupon_detail_id' => 'CUDT' . date("ymdHi") . random_string(4, 'up'),
  803. 'join_detail_coupon_id' => $couponId,
  804. 'coupon_detail_status' => $couponStatus == 'ACTIVED' ? 'PENDING' : 'INIT',
  805. 'coupon_detail_addtimes' => time()
  806. ]);
  807. }
  808. }
  809. }