RewardPointRepository.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. namespace Longyi\RewardPoints\Repositories;
  3. use Webkul\Core\Eloquent\Repository;
  4. use Longyi\RewardPoints\Models\RewardPointHistory;
  5. use Longyi\RewardPoints\Models\RewardPointCustomer;
  6. use Longyi\RewardPoints\Models\RewardActiveRule;
  7. use Carbon\Carbon;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. class RewardPointRepository extends Repository
  11. {
  12. public function model()
  13. {
  14. return RewardPointHistory::class;
  15. }
  16. public function getCustomerPoints($customerId)
  17. {
  18. $customerPoints = RewardPointCustomer::where('customer_id', $customerId)->first();
  19. if (!$customerPoints) {
  20. return 0;
  21. }
  22. return $customerPoints->mw_reward_point;
  23. }
  24. /**
  25. * 添加积分(支持传入规则信息)
  26. */
  27. public function addPoints($customerId, $type, $amount, $orderId = null, $detail = null, $rule = null)
  28. {
  29. try {
  30. return DB::transaction(function () use ($customerId, $type, $amount, $orderId, $detail, $rule) {
  31. // 1. 获取或创建用户积分记录
  32. $customerPoints = RewardPointCustomer::firstOrCreate(
  33. ['customer_id' => $customerId],
  34. [
  35. 'mw_reward_point' => 0,
  36. 'mw_friend_id' => 0,
  37. 'subscribed_balance_update' => 1,
  38. 'subscribed_point_expiration' => 1,
  39. 'last_checkout' => Carbon::now()
  40. ]
  41. );
  42. // 2. 确定积分状态
  43. // 订单类型的积分初始状态为 PENDING,其他类型直接 COMPLETED
  44. $status = ($type === RewardActiveRule::TYPE_ORDER)
  45. ? RewardPointHistory::STATUS_PENDING
  46. : RewardPointHistory::STATUS_COMPLETED;
  47. // 3. 只有 COMPLETED 状态的积分才计入用户总积分
  48. if ($status === RewardPointHistory::STATUS_COMPLETED) {
  49. $customerPoints->increment('mw_reward_point', $amount);
  50. }
  51. // 3. 更新最后检查时间
  52. $customerPoints->last_checkout = Carbon::now();
  53. $customerPoints->save();
  54. // 4. 重新查询获取最新的余额
  55. $customerPoints = RewardPointCustomer::where('customer_id', $customerId)->first();
  56. $newBalance = $customerPoints ? (int) $customerPoints->mw_reward_point : $amount;
  57. /* Log::info('Points added', [
  58. 'customer_id' => $customerId,
  59. 'type' => $type,
  60. 'amount' => $amount,
  61. 'new_balance' => $newBalance
  62. ]);*/
  63. // 5. 获取过期信息(如果没有传入规则,则查询)
  64. if ($rule) {
  65. $expiredDay = $rule->expired_day ?? 0;
  66. $expiredTime = $expiredDay > 0 ? Carbon::now()->addDays($expiredDay) : null;
  67. } else {
  68. $expiredDay = 365;
  69. $expiredTime = $expiredDay > 0 ? Carbon::now()->addDays($expiredDay) : null;
  70. }
  71. // 6. 创建历史记录
  72. $history = $this->create([
  73. 'customer_id' => $customerId,
  74. 'type_of_transaction' => $type,
  75. 'amount' => $amount,
  76. 'balance' => $newBalance,
  77. 'transaction_detail' => $detail,
  78. 'transaction_time' => Carbon::now(),
  79. 'history_order_id' => $orderId ?? 0,
  80. 'expired_day' => $expiredDay,
  81. 'expired_time' => $expiredTime,
  82. 'point_remaining' => $amount,
  83. 'check_time' => 1,
  84. 'status' => $status
  85. ]);
  86. return $history;
  87. });
  88. } catch (\Exception $e) {
  89. Log::error('Error adding points', [
  90. 'customer_id' => $customerId,
  91. 'error' => $e->getMessage(),
  92. 'trace' => $e->getTraceAsString()
  93. ]);
  94. throw $e;
  95. }
  96. }
  97. /**
  98. * 批量添加积分(用于同时多个事件)
  99. * 确保每条历史记录都有正确的余额值
  100. */
  101. public function addPointsBatch($customerId, array $pointsList)
  102. {
  103. try {
  104. return DB::transaction(function () use ($customerId, $pointsList) {
  105. // 1. 获取或创建用户积分记录(不使用 lockForUpdate 避免问题)
  106. $customerPoints = RewardPointCustomer::firstOrCreate(
  107. ['customer_id' => $customerId],
  108. [
  109. 'mw_reward_point' => 0,
  110. 'mw_friend_id' => 0,
  111. 'subscribed_balance_update' => 1,
  112. 'subscribed_point_expiration' => 1,
  113. 'last_checkout' => Carbon::now()
  114. ]
  115. );
  116. // 确保 $customerPoints 存在
  117. if (!$customerPoints) {
  118. throw new \Exception('Failed to create or retrieve customer points record');
  119. }
  120. // 2. 获取当前余额
  121. $currentBalance = (int) $customerPoints->mw_reward_point;
  122. $histories = [];
  123. $totalAmount = 0;
  124. // 3. 逐条创建历史记录(每条记录使用累加后的余额)
  125. foreach ($pointsList as $index => $pointData) {
  126. $amount = (int) $pointData['amount'];
  127. $type = $pointData['type'];
  128. $detail = $pointData['detail'] ?? null;
  129. $orderId = $pointData['order_id'] ?? null;
  130. $rule = $pointData['rule'] ?? null;
  131. // 累加总积分
  132. $totalAmount += $amount;
  133. // 计算当前这条记录后的余额(累加后的余额)
  134. $newBalance = $currentBalance + $totalAmount;
  135. // 获取过期信息
  136. $expiredDay = 0;
  137. $expiredTime = null;
  138. if ($rule) {
  139. $expiredDay = $rule->expired_day ?? 0;
  140. $expiredTime = $expiredDay > 0 ? Carbon::now()->addDays($expiredDay) : null;
  141. }
  142. // 创建历史记录(每条记录独立)
  143. $history = $this->create([
  144. 'customer_id' => $customerId,
  145. 'type_of_transaction' => $type,
  146. 'amount' => $amount,
  147. 'balance' => $newBalance,
  148. 'transaction_detail' => $detail,
  149. 'transaction_time' => Carbon::now(),
  150. 'history_order_id' => $orderId ?? 0,
  151. 'expired_day' => $expiredDay,
  152. 'expired_time' => $expiredTime,
  153. 'point_remaining' => $amount,
  154. 'check_time' => 1,
  155. 'status' => RewardPointHistory::STATUS_COMPLETED
  156. ]);
  157. $histories[] = $history;
  158. }
  159. // 4. 最后一次性更新用户总积分
  160. $updated = DB::table('mw_reward_point_customer')
  161. ->where('customer_id', $customerId)
  162. ->update([
  163. 'mw_reward_point' => DB::raw('mw_reward_point + ' . (float)$totalAmount),
  164. 'last_checkout' => Carbon::now()
  165. ]);
  166. return $histories;
  167. });
  168. } catch (\Exception $e) {
  169. Log::error('Error adding batch points', [
  170. 'customer_id' => $customerId,
  171. 'error' => $e->getMessage(),
  172. 'trace' => $e->getTraceAsString()
  173. ]);
  174. throw $e;
  175. }
  176. }
  177. public function deductPoints($customerId, $amount, $orderId = null, $detail = null)
  178. {
  179. try {
  180. return DB::transaction(function () use ($customerId, $amount, $orderId, $detail) {
  181. $customerPoints = RewardPointCustomer::where('customer_id', $customerId)
  182. ->lockForUpdate()
  183. ->first();
  184. if (!$customerPoints) {
  185. Log::warning('Customer points record not found', ['customer_id' => $customerId]);
  186. return false;
  187. }
  188. if ($customerPoints->mw_reward_point < $amount) {
  189. Log::warning('Insufficient points', [
  190. 'customer_id' => $customerId,
  191. 'current' => $customerPoints->mw_reward_point,
  192. 'required' => $amount
  193. ]);
  194. return false;
  195. }
  196. $currentBalance = (int) $customerPoints->mw_reward_point;
  197. $newBalance = $currentBalance - (int) $amount;
  198. // 更新积分
  199. $customerPoints->mw_reward_point = $newBalance;
  200. $customerPoints->last_checkout = Carbon::now();
  201. $customerPoints->save();
  202. // 创建历史记录
  203. $history = $this->create([
  204. 'customer_id' => $customerId,
  205. 'type_of_transaction' => 0,
  206. 'amount' => -$amount,
  207. 'balance' => $newBalance,
  208. 'transaction_detail' => $detail,
  209. 'transaction_time' => Carbon::now(),
  210. 'history_order_id' => $orderId ?? 0,
  211. 'expired_day' => 0,
  212. 'expired_time' => null,
  213. 'point_remaining' => 0,
  214. 'check_time' => 1,
  215. 'status' => RewardPointHistory::STATUS_COMPLETED
  216. ]);
  217. Log::info('Points deducted successfully', [
  218. 'customer_id' => $customerId,
  219. 'amount' => $amount,
  220. 'new_balance' => $newBalance
  221. ]);
  222. return $history;
  223. });
  224. } catch (\Exception $e) {
  225. Log::error('Error deducting points', [
  226. 'customer_id' => $customerId,
  227. 'amount' => $amount,
  228. 'error' => $e->getMessage()
  229. ]);
  230. return false;
  231. }
  232. }
  233. public function getHistory($customerId, $limit = 20, $page = null)
  234. {
  235. $query = $this->where('customer_id', $customerId)
  236. ->orderBy('transaction_time', 'desc');
  237. if ($page) {
  238. return $query->paginate($limit, ['*'], 'page', $page);
  239. }
  240. return $query->paginate($limit);
  241. }
  242. public function checkExpiredPoints()
  243. {
  244. // 只检查已过期的、状态为 COMPLETED 的、还有剩余积分的记录
  245. // PENDING 状态的积分不会过期(因为订单还未完成)
  246. $expiredHistories = $this->where('expired_time', '<', Carbon::now())
  247. ->where('status', RewardPointHistory::STATUS_COMPLETED)
  248. ->where('point_remaining', '>', 0)
  249. ->get();
  250. foreach ($expiredHistories as $history) {
  251. try {
  252. DB::transaction(function () use ($history) {
  253. $customerPoints = RewardPointCustomer::where('customer_id', $history->customer_id)
  254. ->lockForUpdate()
  255. ->first();
  256. if ($customerPoints && $customerPoints->mw_reward_point >= $history->point_remaining) {
  257. $customerPoints->mw_reward_point -= $history->point_remaining;
  258. $customerPoints->save();
  259. $history->status = RewardPointHistory::STATUS_EXPIRED;
  260. $history->point_remaining = 0;
  261. $history->save();
  262. Log::info('Expired points processed', [
  263. 'history_id' => $history->history_id,
  264. 'customer_id' => $history->customer_id,
  265. 'points_expired' => $history->getOriginal('point_remaining')
  266. ]);
  267. }
  268. });
  269. } catch (\Exception $e) {
  270. Log::error('Error processing expired points', [
  271. 'history_id' => $history->history_id,
  272. 'error' => $e->getMessage()
  273. ]);
  274. }
  275. }
  276. }
  277. /**
  278. * 确认待处理的积分(将 PENDING 状态改为 COMPLETED 并计入用户余额)
  279. */
  280. public function confirmPendingPoints($customerId, $orderId)
  281. {
  282. try {
  283. return DB::transaction(function () use ($customerId, $orderId) {
  284. // 查找所有 PENDING 状态的订单积分记录
  285. $pendingHistories = $this->where('customer_id', $customerId)
  286. ->where('history_order_id', $orderId)
  287. ->where('type_of_transaction', RewardActiveRule::TYPE_ORDER)
  288. ->where('status', RewardPointHistory::STATUS_PENDING)
  289. ->get();
  290. if ($pendingHistories->isEmpty()) {
  291. Log::info('No pending points to confirm', [
  292. 'customer_id' => $customerId,
  293. 'order_id' => $orderId
  294. ]);
  295. return 0;
  296. }
  297. $totalConfirmedPoints = 0;
  298. foreach ($pendingHistories as $history) {
  299. // 增加用户总积分
  300. $customerPoints = RewardPointCustomer::where('customer_id', $customerId)
  301. ->lockForUpdate()
  302. ->first();
  303. if ($customerPoints) {
  304. $pointsToAdd = $history->point_remaining;
  305. // 增加积分
  306. $customerPoints->increment('mw_reward_point', $pointsToAdd);
  307. $customerPoints->refresh(); // 刷新获取最新值
  308. $newBalance = (int) $customerPoints->mw_reward_point;
  309. // 直接更新原记录的状态和余额
  310. $history->status = RewardPointHistory::STATUS_COMPLETED;
  311. $history->balance = $newBalance;
  312. $history->save();
  313. $totalConfirmedPoints += $pointsToAdd;
  314. Log::info('Pending points confirmed', [
  315. 'history_id' => $history->history_id,
  316. 'customer_id' => $customerId,
  317. 'order_id' => $orderId,
  318. 'points' => $pointsToAdd,
  319. 'old_balance' => $history->getOriginal('balance'),
  320. 'new_balance' => $newBalance
  321. ]);
  322. }
  323. }
  324. return $totalConfirmedPoints;
  325. });
  326. } catch (\Exception $e) {
  327. Log::error('Error confirming pending points', [
  328. 'customer_id' => $customerId,
  329. 'order_id' => $orderId,
  330. 'error' => $e->getMessage(),
  331. 'trace' => $e->getTraceAsString()
  332. ]);
  333. throw $e;
  334. }
  335. }
  336. }