CouponDetailService.php 20 KB

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