CouponController.php 38 KB

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