CouponDetailService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. namespace app\admin\service\coupon;
  3. use app\model\Coupon;
  4. use app\model\CouponDetail;
  5. use app\model\Member;
  6. use app\model\SysSerial;
  7. use support\Db;
  8. use support\exception\BusinessException;
  9. use support\Log;
  10. class CouponDetailService
  11. {
  12. /**
  13. * @Desc 手动发券
  14. * @Author Gorden
  15. * @Date 2024/8/27 9:57
  16. *
  17. * @param $params
  18. * @return void
  19. * @throws BusinessException
  20. */
  21. public static function customSendCoupon($params)
  22. {
  23. $gettype = 'SEND';
  24. if (!empty($params['gettype'])) {
  25. $gettype = $params['gettype'];
  26. }
  27. try {
  28. CouponDetail::insert([
  29. 'coupon_detail_id' => 'CUDT' . date("ymdHi") . random_string(4, 'up'),
  30. 'join_detail_coupon_id' => $params['coupon_id'],
  31. 'join_coupon_detail_member_id' => $params['member_id'],
  32. 'coupon_detail_status' => 'ACTIVED',
  33. 'coupon_detail_gain_datetime' => $params['coupon_detail_gain_datetime'],
  34. 'coupon_detail_deadline_datetime' => $params['coupon_detail_deadline_datetime'],
  35. 'coupon_detail_period_num' => $params['coupon_detail_period_num'] ?? 0,
  36. 'coupon_detail_extend_json' => json_encode(['gettype' => $gettype, 'order_id' => $params['order_id'] ?? '']),
  37. 'coupon_detail_addtimes' => time(),
  38. ]);
  39. } catch (\Exception $e) {
  40. Log::error('写入优惠券失败',['msg'=>$e->getMessage()]);
  41. throw new BusinessException('写入优惠券失败');
  42. }
  43. }
  44. public static function customSendCouponHave($params)
  45. {
  46. $gettype = 'SEND';
  47. if (!empty($params['gettype'])) {
  48. $gettype = $params['gettype'];
  49. }
  50. try {
  51. CouponDetail::where('join_detail_coupon_id', $params['coupon_id'])
  52. ->whereIn('coupon_detail_status', ['INIT', 'PENDING'])
  53. ->limit($params['chooseCouponNbr'])
  54. ->update([
  55. 'join_coupon_detail_member_id' => $params['member_id'],
  56. 'coupon_detail_gain_datetime' => $params['coupon_detail_gain_datetime'],
  57. 'coupon_detail_deadline_datetime' => $params['coupon_detail_deadline_datetime'],
  58. 'coupon_detail_extend_json' => json_encode(['gettype' => $gettype, 'order_id' => $params['order_id'] ?? '']),
  59. 'coupon_detail_period_num' => $params['coupon_detail_period_num'] ?? 0,
  60. 'coupon_detail_status' => 'ACTIVED',
  61. 'coupon_detail_addtimes' => time()
  62. ]);
  63. } catch (\Exception $e) {
  64. Log::error("写入优惠券失败", ['msg' => $e->getMessage()]);
  65. throw new BusinessException('写入优惠券失败');
  66. }
  67. }
  68. /**
  69. * @Desc 发周期优惠券 - 没有发行数量
  70. * @Author Gorden
  71. * @Date 2024/9/27 13:44
  72. *
  73. * @param $params
  74. * @return void
  75. */
  76. public static function sendPeriodCoupon($params)
  77. {
  78. Db::beginTransaction();
  79. try {
  80. $coupon = Coupon::where('coupon_id', $params['coupon_id'])->first();
  81. if ($coupon->coupon_is_period != 'Y') {
  82. return;
  83. }
  84. $detailCount = -1;
  85. if ($coupon->coupon_number > 0) {
  86. $detailCount = CouponDetail::where('join_detail_coupon_id', $params['coupon_id'])->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->count();
  87. }
  88. $periodJson = json_decode($coupon->coupon_period_json, true);
  89. if ($detailCount != -1 && $detailCount - $periodJson['nbr'] < 0) {
  90. throw new BusinessException("优惠券余量不足");
  91. }
  92. $periodJson['now_nbr'] = 1;
  93. // 手动发券会传来时间
  94. $periodJson['gain_datetime'] = $params['coupon_detail_gain_datetime'] ?? date('Y-m-d H:i:s');
  95. if (!empty($periodJson['nbr'])) {
  96. for ($i = 0; $i < $periodJson['nbr']; $i++) {
  97. $periodParams = self::generatePeriod($periodJson);
  98. $periodParams['gettype'] = $params['gettype'] ?? '';
  99. $periodParams['order_id'] = $params['order_id'] ?? '';
  100. $periodParams['coupon_id'] = $params['coupon_id'];
  101. $periodParams['member_id'] = $params['member_id'];
  102. $periodParams['coupon_detail_period_num'] = $periodJson['now_nbr'];
  103. if ($detailCount > 0) {
  104. $periodParams['chooseCouponNbr'] = 1;
  105. self::sendPeriodCouponHave($periodParams);
  106. } else {
  107. self::sendPeriodCouponNoLimit($periodParams);
  108. }
  109. $periodJson['now_nbr'] += 1;
  110. }
  111. }
  112. Db::commit();
  113. } catch (BusinessException $e) {
  114. Db::rollBack();
  115. Log::error("周期券发券失败:" . $e->getMessage());
  116. throw new BusinessException($e->getMessage());
  117. } catch (\Exception $e) {
  118. Db::rollBack();
  119. Log::error("周期券发券失败:" . $e->getMessage());
  120. throw new BusinessException("优惠券发放失败");
  121. }
  122. }
  123. /**
  124. * @Desc 有发行数量
  125. * @Author Gorden
  126. * @Date 2024/9/27 13:45
  127. *
  128. * @param $params
  129. * @return void
  130. */
  131. public static function sendPeriodCouponHave($params)
  132. {
  133. $gettype = 'SEND';
  134. if (!empty($params['gettype'])) {
  135. $gettype = $params['gettype'];
  136. }
  137. try {
  138. CouponDetail::where('join_detail_coupon_id', $params['coupon_id'])
  139. ->whereIn('coupon_detail_status', ['INIT', 'PENDING'])
  140. ->limit($params['chooseCouponNbr'])
  141. ->update([
  142. 'join_coupon_detail_member_id' => $params['member_id'],
  143. 'coupon_detail_gain_datetime' => $params['coupon_detail_gain_datetime'],
  144. 'coupon_detail_deadline_datetime' => $params['coupon_detail_deadline_datetime'],
  145. 'coupon_detail_extend_json' => json_encode(['gettype' => $gettype, 'order_id' => $params['order_id'] ?? '']),
  146. 'coupon_detail_period_num' => $params['coupon_detail_period_num'] ?? 0,
  147. 'coupon_detail_status' => 'ACTIVED',
  148. 'coupon_detail_addtimes' => time()
  149. ]);
  150. } catch (\Exception $e) {
  151. dump($e->getMessage());
  152. throw new BusinessException('写入优惠券失败');
  153. }
  154. }
  155. /**
  156. * @Desc 发行量不限
  157. * @Author Gorden
  158. * @Date 2024/9/27 16:19
  159. *
  160. * @param $params
  161. * @return void
  162. * @throws BusinessException
  163. */
  164. public static function sendPeriodCouponNoLimit($params)
  165. {
  166. $gettype = 'SEND';
  167. if (!empty($params['gettype'])) {
  168. $gettype = $params['gettype'];
  169. }
  170. try {
  171. CouponDetail::insert([
  172. 'coupon_detail_id' => 'CUDT' . date("ymdHi") . random_string(4, 'up'),
  173. 'join_detail_coupon_id' => $params['coupon_id'],
  174. 'join_coupon_detail_member_id' => $params['member_id'],
  175. 'coupon_detail_status' => 'ACTIVED',
  176. 'coupon_detail_gain_datetime' => $params['coupon_detail_gain_datetime'],
  177. 'coupon_detail_deadline_datetime' => $params['coupon_detail_deadline_datetime'],
  178. 'coupon_detail_period_num' => $params['coupon_detail_period_num'] ?? 0,
  179. 'coupon_detail_extend_json' => json_encode(['gettype' => $gettype, 'order_id' => $params['order_id'] ?? '']),
  180. 'coupon_detail_addtimes' => time(),
  181. ]);
  182. } catch (\Exception $e) {
  183. throw new BusinessException('写入优惠券失败');
  184. }
  185. }
  186. /**
  187. * @Desc
  188. * @Author Gorden
  189. * @Date 2024/9/27 13:54
  190. *
  191. * @param $periodJson
  192. * @return array
  193. */
  194. public static function generatePeriod($periodJson)
  195. {
  196. // 当前第几期
  197. $now_nbr = $periodJson['now_nbr'];
  198. $params = [];
  199. if ($periodJson['unit'] == 'day') {
  200. $val = $periodJson['val'] - 1;
  201. if ($val < 1) {
  202. if ($now_nbr == 1) {
  203. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime($periodJson['gain_datetime']));
  204. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime($periodJson['gain_datetime']));
  205. } else {
  206. $now_nbr -= 1;
  207. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime($periodJson['gain_datetime'] . "+" . $now_nbr . ' day'));
  208. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime($periodJson['gain_datetime'] . "+" . $now_nbr . ' day'));
  209. }
  210. } else {
  211. if ($now_nbr == 1) {
  212. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime($periodJson['gain_datetime']));
  213. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime($periodJson['gain_datetime'] . "+" . $val . ' day'));
  214. } else {
  215. $now_nbr -= 1;
  216. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime($periodJson['gain_datetime'] . "+" . ((($val + 1) * $now_nbr)) . " day"));
  217. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime($periodJson['gain_datetime'] . "+" . ((($val + 1) * $now_nbr) + $val) . " day"));
  218. }
  219. }
  220. } elseif ($periodJson['unit'] == 'week') {
  221. $val = $periodJson['val'] - 1;
  222. // 选的日期的周一距离今周周一是几个周
  223. $timestamp = strtotime($periodJson['gain_datetime']);
  224. $gainWeekDay = date("w", $timestamp);
  225. $gainWeekAdd = date("w", $gainWeekDay) == 1 ? 0 : 1 - $gainWeekDay;
  226. $gainMonday = date("Y-m-d 00:00:00", strtotime("$gainWeekAdd days", $timestamp));
  227. $nowMonday = date('Y-m-d 00:00:00', strtotime('this week Monday'));
  228. $interval = (new \DateTime(date($gainMonday)))->diff(new \DateTime($nowMonday));
  229. $weekCut = $interval->days / 7;
  230. if (strtotime($periodJson['gain_datetime']) < time() && $weekCut > 0) {
  231. $weekCut = -$weekCut;
  232. }
  233. if ($val < 1) {
  234. if ($now_nbr == 1) {
  235. $params['coupon_detail_gain_datetime'] = $gainMonday;
  236. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime($gainMonday . "+6 days"));
  237. } else {
  238. $now_nbr -= 1;
  239. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d 00:00:00', strtotime('this week Monday')) . "+" . ($now_nbr + $weekCut) . ' week'));
  240. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d 23:59:59', strtotime('this week Sunday')) . "+" . ($now_nbr + $weekCut) . ' week'));
  241. }
  242. } else {
  243. if ($now_nbr == 1) {
  244. $params['coupon_detail_gain_datetime'] = $gainMonday;
  245. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d 23:59:59', strtotime('this week Sunday')) . "+" . ($val + $weekCut) . ' week'));
  246. } else {
  247. $now_nbr -= 1;
  248. $params['coupon_detail_gain_datetime'] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d 00:00:00', strtotime('this week Monday')) . "+" . ((($val + 1) * $now_nbr) + $weekCut) . ' week'));
  249. $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d 23:59:59', strtotime('this week Sunday')) . "+" . ((($val + 1) * $now_nbr) + $val + $weekCut) . ' week'));
  250. }
  251. }
  252. } elseif ($periodJson['unit'] == 'month') {
  253. $val = $periodJson['val'] - 1;
  254. // 选的日期的1号距离今月1号是几个月
  255. $interval = (new \DateTime(date('Y-m-02 00:00:00', strtotime($periodJson['gain_datetime']))))->diff(new \DateTime(date('Y-m-02 00:00:00')));
  256. $monthCut = $interval->m + ($interval->y * 12);
  257. if (strtotime($periodJson['gain_datetime']) < time() && $monthCut > 0) {
  258. $monthCut = -$monthCut;
  259. }
  260. if ($val < 1) {
  261. if ($now_nbr == 1) {
  262. $params['coupon_detail_gain_datetime'] = date('Y-m-01 00:00:00', strtotime($periodJson['gain_datetime']));
  263. $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime($periodJson['gain_datetime']));
  264. } else {
  265. $now_nbr -= 1;
  266. $params['coupon_detail_gain_datetime'] = date('Y-m-01 00:00:00', strtotime(date('Y-m-01 00:00:00') . "+" . ($now_nbr + $monthCut) . ' month'));
  267. $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime(date('Y-m-01 00:00:00') . "+" . ($now_nbr + $monthCut) . ' month'));
  268. }
  269. } else {
  270. if ($now_nbr == 1) {
  271. $params['coupon_detail_gain_datetime'] = date('Y-m-01 00:00:00', strtotime($periodJson['gain_datetime']));
  272. $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime(date('Y-m-01 00:00:00') . "+" . ($val + $monthCut) . ' month'));
  273. } else {
  274. $now_nbr -= 1;
  275. $params['coupon_detail_gain_datetime'] = date('Y-m-01 00:00:00', strtotime(date('Y-m-01 00:00:00') . "+" . ((($val + 1) * $now_nbr) + $monthCut) . ' month'));
  276. $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime(date('Y-m-01 00:00:00') . "+" . ((($val + 1) * $now_nbr) + $val + $monthCut) . ' month'));
  277. }
  278. }
  279. }
  280. return $params;
  281. }
  282. public static function customSendService($chooseCoupons, $couponUseMember, $memberList, $condition)
  283. {
  284. if ($couponUseMember == 'condition') {
  285. if ($condition == 'is_employ') {
  286. $memberList = Member::where('member_classify', 'EMPLOY')->pluck('member_id')->toArray();
  287. } elseif ($condition == 'is_member') {
  288. $memberList = Member::where('member_classify', 'MEMBER')->pluck('member_id')->toArray();
  289. } elseif ($condition == 'is_vip') {
  290. $memberList = Member::where('member_is_vip', 'Y')->pluck('member_id')->toArray();
  291. }
  292. }
  293. $couponNbr = [];
  294. Db::beginTransaction();
  295. try {
  296. $couponIds = array_column($chooseCoupons, 'id');
  297. $coupons = Coupon::whereIn('coupon_id', $couponIds)->get()->toArray();
  298. foreach ($coupons as $coupon) {
  299. foreach ($chooseCoupons as $chooseCoupon) {
  300. if ($chooseCoupon['id'] == $coupon['coupon_id']) {
  301. if (empty($chooseCoupon['gain_datetime'])) {
  302. $chooseCoupon['gain_datetime'] = date('Y-m-d H:i:s');
  303. }
  304. $params['coupon_id'] = $coupon['coupon_id'];
  305. $params['coupon_detail_gain_datetime'] = date('Y-m-d H:i:s', strtotime($chooseCoupon['gain_datetime']));
  306. if (($coupon['coupon_validdate_day'] == 0 || $coupon['coupon_validdate_day'] == '') && !empty($coupon['coupon_validdate_end'])) {
  307. $params['coupon_detail_deadline_datetime'] = $coupon['coupon_validdate_end'];
  308. } elseif ($coupon['coupon_validdate_day'] > 0) {
  309. $endUnix = strtotime($chooseCoupon['gain_datetime']);
  310. $params['coupon_detail_deadline_datetime'] = date('Y-m-d H:i:s', $endUnix + ($coupon['coupon_validdate_day'] * 24 * 3600) - 1);
  311. }
  312. foreach ($memberList as $item) {
  313. $params['member_id'] = $item;
  314. if ($coupon['coupon_is_period'] == 'Y') {
  315. // if (CouponDetail::where('join_coupon_detail_member_id', $item)->where('join_detail_coupon_id', $coupon['coupon_id'])->exists()) {
  316. // throw new BusinessException("请勿重复发放周期券");
  317. // }
  318. $params['coupon_detail_period_num'] = 1;
  319. $periodJson = json_decode($coupon['coupon_period_json'], true);
  320. // for ($i=0;$i<$periodJson['nbr'];$i++){
  321. CouponDetailService::sendPeriodCoupon($params);
  322. // }
  323. continue;
  324. }
  325. if ($chooseCoupon['nbr'] > 0) {
  326. // 有发行数量
  327. if ($coupon['coupon_number'] != 0) {
  328. // 查询还有多少张没领的
  329. $count = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
  330. ->whereIn('coupon_detail_status', ['INIT', 'PENDING'])
  331. ->count();
  332. if (!isset($couponNbr[$coupon['coupon_id']])) {
  333. $couponNbr[$coupon['coupon_id']] = $count;
  334. }
  335. if ($couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'] < 0) {
  336. throw new BusinessException($coupon['coupon_name'] . "超出发行数量");
  337. }
  338. $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] - $chooseCoupon['nbr'];
  339. $params['chooseCouponNbr'] = $chooseCoupon['nbr'];
  340. // 匹配已发行的优惠券
  341. CouponDetailService::customSendCouponHave($params);
  342. } else {
  343. for ($i = 0; $i < $chooseCoupon['nbr']; $i++) {
  344. CouponDetailService::customSendCoupon($params);
  345. }
  346. }
  347. }
  348. }
  349. }
  350. }
  351. }
  352. Db::commit();
  353. } catch (BusinessException $e) {
  354. Db::rollBack();
  355. Log::error('优惠券发放失败', ['msg' => $e->getMessage()]);
  356. throw new BusinessException($e->getMessage());
  357. } catch (\Exception $e) {
  358. Db::rollBack();
  359. Log::error('优惠券发放失败', ['msg' => $e->getMessage()]);
  360. throw new BusinessException('优惠券发放失败');
  361. }
  362. }
  363. /**
  364. * @Desc 把指定账户的优惠券加到另一个账户
  365. * @Author Gorden
  366. * @Date 2024/11/7 16:33
  367. *
  368. * @param $originMemberId
  369. * @param $memberId
  370. * @return void
  371. */
  372. public static function transCoupon($originMemberId, $memberId)
  373. {
  374. $details = CouponDetail::where('join_coupon_detail_member_id', $originMemberId)
  375. ->where('coupon_detail_status', 'ACTIVED')
  376. ->get()
  377. ->toArray();
  378. foreach ($details as $detail) {
  379. $detailModel = new CouponDetail();
  380. $detailModel->coupon_detail_id = 'CUDT' . date('ymdHi') . random_string(4, 'up');
  381. $detailModel->join_detail_coupon_id = $detail['join_detail_coupon_id'];
  382. $detailModel->join_coupon_detail_member_id = $memberId;
  383. $detailModel->coupon_detail_status = $detail['coupon_detail_status'];
  384. $detailModel->coupon_detail_deadline_datetime = $detail['coupon_detail_deadline_datetime'];
  385. $detailModel->coupon_detail_gain_datetime = date('Y-m-d H:i:s');
  386. $detailModel->coupon_detail_extend_json = $detail['coupon_detail_extend_json'];
  387. $detailModel->coupon_detail_addtimes = time();
  388. $detailModel->save();
  389. }
  390. }
  391. }