WalletService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. namespace App\Services\Coach;
  3. use App\Enums\WithdrawStatus;
  4. use App\Models\MemberUser;
  5. use App\Models\Wallet;
  6. use App\Models\WalletTransRecord;
  7. use App\Models\WalletWithdrawRecord;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. class WalletService
  11. {
  12. /**
  13. * 获取技师钱包信息
  14. *
  15. * @param int $userId 技师用户ID
  16. */
  17. public function getWallet(int $userId): array
  18. {
  19. try {
  20. // 加载用户和技师信息
  21. $user = MemberUser::with(['coach', 'coach.wallet'])->findOrFail($userId);
  22. abort_if(! $user->coach, 404, '技师信息不存在');
  23. // 获取技师钱包
  24. $wallet = $user->coach->wallet;
  25. // 获取钱包流水统计
  26. $statistics = $this->getWalletStatistics($wallet->id);
  27. return [
  28. 'available_balance' => number_format($wallet->available_balance, 2, '.', ''), // 可用余额
  29. 'frozen_amount' => number_format($wallet->frozen_amount, 2, '.', ''), // 冻结金额
  30. 'total_income' => number_format($statistics['total_income'], 2, '.', ''), // 累计收入
  31. 'total_withdraw' => number_format($statistics['total_withdraw'], 2, '.', ''), // 累计支出
  32. 'today_income' => number_format($statistics['today_income'], 2, '.', ''), // 今日收入
  33. 'month_income' => number_format($statistics['month_income'], 2, '.', ''), // 本月收入
  34. 'last_month_income' => number_format($statistics['last_month_income'], 2, '.', ''), // 上月收入
  35. ];
  36. } catch (\Exception $e) {
  37. Log::error('获取技师钱包信息失败', [
  38. 'user_id' => $userId,
  39. 'error' => $e->getMessage(),
  40. 'file' => $e->getFile(),
  41. 'line' => $e->getLine(),
  42. ]);
  43. throw $e;
  44. }
  45. }
  46. /**
  47. * 获取钱包流水记录
  48. *
  49. * @param int $userId 技师用户ID
  50. * @param array $params 查询参数
  51. */
  52. public function getWalletRecords(int $userId, array $params): array
  53. {
  54. try {
  55. // 加载用户和技师信息(优化关联加载)
  56. $user = MemberUser::with(['coach', 'coach.wallet'])->findOrFail($userId);
  57. abort_if(! $user->coach, 404, '技师信息不存在');
  58. abort_if(! $user->coach->wallet, 404, '钱包信息不存在');
  59. // 构建查询
  60. $query = WalletTransRecord::where('wallet_id', $user->coach->wallet->id)
  61. // 修复参数名称错误
  62. ->when(isset($params['type']), function ($query) use ($params) {
  63. return $query->where('trans_type', $params['type']);
  64. })
  65. // 优化日期查询
  66. ->when(isset($params['start_date']), function ($query) use ($params) {
  67. return $query->whereDate('created_at', '>=', $params['start_date']);
  68. })
  69. ->when(isset($params['end_date']), function ($query) use ($params) {
  70. return $query->whereDate('created_at', '<=', $params['end_date']);
  71. })
  72. // 添加金额范围筛选
  73. ->when(isset($params['min_amount']), function ($query) use ($params) {
  74. return $query->where('amount', '>=', $params['min_amount']);
  75. })
  76. ->when(isset($params['max_amount']), function ($query) use ($params) {
  77. return $query->where('amount', '<=', $params['max_amount']);
  78. })
  79. // 添加交易状态筛选
  80. ->when(isset($params['status']), function ($query) use ($params) {
  81. return $query->where('state', $params['status']);
  82. })
  83. // 添加排序选项
  84. ->when(
  85. isset($params['sort_field']) && isset($params['sort_order']),
  86. function ($query) use ($params) {
  87. return $query->orderBy(
  88. $params['sort_field'],
  89. $params['sort_order'] === 'desc' ? 'desc' : 'asc'
  90. );
  91. },
  92. function ($query) {
  93. return $query->orderBy('created_at', 'desc');
  94. }
  95. );
  96. // 分页获取数据(添加字段选择)
  97. $records = $query->paginate(
  98. $params['per_page'] ?? 10,
  99. [
  100. 'id',
  101. 'trans_no',
  102. 'trans_type',
  103. 'amount',
  104. 'balance',
  105. 'owner_type',
  106. 'owner_id',
  107. 'remark',
  108. 'status',
  109. 'created_at',
  110. ],
  111. 'page',
  112. $params['page'] ?? 1
  113. );
  114. // TODO: 处理格式化数据存在的枚举映射
  115. // 格式化数据
  116. $items = collect($records->items())->map(function ($record) {
  117. return [
  118. 'id' => $record->id,
  119. 'trans_no' => $record->trans_no,
  120. 'trans_type' => $this->formatTransType($record->trans_type),
  121. 'amount' => number_format($record->amount, 2, '.', ''),
  122. 'balance' => number_format($record->balance, 2, '.', ''),
  123. 'owner_type' => $this->formatOwnerType($record->owner_type),
  124. 'owner_id' => $record->owner_id,
  125. 'remark' => $record->remark,
  126. 'state' => $this->formatStatus($record->state),
  127. 'created_at' => $record->created_at->format('Y-m-d H:i:s'),
  128. ];
  129. });
  130. // 添加汇总信息
  131. $summary = [
  132. 'total_income' => $query->where('amount', '>', 0)->sum('amount'),
  133. 'total_expense' => abs($query->where('amount', '<', 0)->sum('amount')),
  134. 'record_count' => $records->total(),
  135. ];
  136. return [
  137. 'items' => $items,
  138. 'total' => $records->total(),
  139. 'summary' => $summary,
  140. ];
  141. } catch (\Exception $e) {
  142. Log::error('获取钱包流水记录失败', [
  143. 'user_id' => $userId,
  144. 'params' => $params,
  145. 'error' => $e->getMessage(),
  146. 'file' => $e->getFile(),
  147. 'line' => $e->getLine(),
  148. ]);
  149. throw $e;
  150. }
  151. }
  152. /**
  153. * 技师钱包提现
  154. *
  155. * @param int $userId 技师用户ID
  156. * @param array $data 提现数据
  157. * @return array
  158. *
  159. * @throws \Exception
  160. */
  161. public function withdraw(int $userId, array $data)
  162. {
  163. return DB::transaction(function () use ($userId, $data) {
  164. try {
  165. // 获取用户和技师信息
  166. $user = MemberUser::with(['coach', 'coach.wallet'])->findOrFail($userId);
  167. abort_if(! $user->coach, 404, '技师信息不存在');
  168. abort_if(! $user->coach->wallet, 404, '钱包信息不存在');
  169. // 锁定钱包记录
  170. $wallet = Wallet::where('id', $user->coach->wallet->id)
  171. ->lockForUpdate()
  172. ->first();
  173. // TODO: 提现金额限制
  174. // 验证提现金额
  175. $amount = $data['amount'];
  176. abort_if($amount <= 100, 422, '提现金额必须大于100元');
  177. abort_if($amount > $wallet->available_balance, 422, '可提现余额不足');
  178. // 生成交易流水号
  179. $transNo = 'W' . date('YmdHis') . mt_rand(1000, 9999);
  180. // 创建提现记录
  181. $withdraw = WalletWithdrawRecord::create([
  182. 'wallet_id' => $wallet->id, // 钱包ID
  183. 'trans_no' => $transNo, // 交易流水号
  184. 'amount' => $amount, // 提现金额
  185. 'withdraw_type' => $data['withdraw_type'], // 提现方式(1:微信 2:支付宝 3:银行卡)
  186. 'withdraw_account' => $data['withdraw_account'], // 提现账号
  187. 'withdraw_account_name' => $data['withdraw_account_name'], // 提现账户名称
  188. 'state' => WithdrawStatus::PROCESSING, // 提现状态
  189. ]);
  190. // TODO: 创建交易记录字段需关联枚举
  191. // 创建交易记录
  192. $record = WalletTransRecord::create([
  193. 'wallet_id' => $wallet->id,
  194. 'trans_no' => $transNo,
  195. 'trans_type' => 2, // 支出
  196. 'amount' => -$amount,
  197. 'before_balance' => $wallet->available_balance,
  198. 'after_balance' => $wallet->available_balance - $amount,
  199. 'owner_type' => WalletWithdrawRecord::class,
  200. 'owner_id' => $withdraw->id,
  201. 'remark' => '提现申请',
  202. 'state' => 2, // 处理中
  203. ]);
  204. // 冻结提现金额
  205. $wallet->decrement('available_balance', $amount);
  206. $wallet->increment('frozen_amount', $amount);
  207. // 记录日志
  208. \Log::info('技师提现申请成功', [
  209. 'user_id' => $userId,
  210. 'coach_id' => $user->coach->id,
  211. 'trans_no' => $transNo,
  212. 'amount' => $amount,
  213. 'wallet_id' => $wallet->id,
  214. ]);
  215. return [
  216. 'message' => '提现申请已提交',
  217. 'trans_no' => $transNo,
  218. 'amount' => number_format($amount, 2, '.', ''),
  219. 'state' => '处理中',
  220. ];
  221. } catch (\Exception $e) {
  222. \Log::error('技师提现申请失败', [
  223. 'user_id' => $userId,
  224. 'data' => $data,
  225. 'error' => $e->getMessage(),
  226. 'file' => $e->getFile(),
  227. 'line' => $e->getLine(),
  228. ]);
  229. throw $e;
  230. }
  231. });
  232. }
  233. /**
  234. * 格式化交易类型
  235. */
  236. private function formatTransType(int $type): string
  237. {
  238. return match ($type) {
  239. 1 => '收入',
  240. 2 => '支出',
  241. default => '未知',
  242. };
  243. }
  244. /**
  245. * 格式化来源类型
  246. */
  247. private function formatOwnerType(string $type): string
  248. {
  249. return match ($type) {
  250. 'order' => '订单',
  251. 'withdraw' => '提现',
  252. 'refund' => '退款',
  253. 'system' => '系统',
  254. default => '其他',
  255. };
  256. }
  257. /**
  258. * 格式化状态
  259. */
  260. private function formatStatus(int $status): string
  261. {
  262. return match ($status) {
  263. 1 => '成功',
  264. 2 => '处理中',
  265. 3 => '失败',
  266. default => '未知',
  267. };
  268. }
  269. /**
  270. * 获取钱包流水统计
  271. *
  272. * @param int $walletId 钱包ID
  273. */
  274. private function getWalletStatistics(int $walletId): array
  275. {
  276. try {
  277. // 计算总收入和总支出
  278. $totals = WalletTransRecord::where('wallet_id', $walletId)
  279. ->selectRaw(expression: '
  280. SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as total_income,
  281. ABS(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END)) as total_withdraw
  282. ')->first();
  283. // 计算今日收入
  284. $todayIncome = WalletTransRecord::where('wallet_id', $walletId)
  285. ->where('amount', '>', 0)
  286. ->whereDate('created_at', operator: today())
  287. ->sum('amount');
  288. // 计算本月收入
  289. $monthIncome = WalletTransRecord::where('wallet_id', $walletId)
  290. ->where('amount', '>', 0)
  291. ->whereYear('created_at', now()->year)
  292. ->whereMonth('created_at', now()->month)
  293. ->sum('amount');
  294. // 计算上月收入
  295. $lastMonthIncome = WalletTransRecord::where('wallet_id', $walletId)
  296. ->where('amount', '>', 0)
  297. ->whereYear('created_at', now()->subMonth()->year)
  298. ->whereMonth('created_at', now()->subMonth()->month)
  299. ->sum('amount');
  300. return [
  301. 'total_income' => $totals->total_income ?? 0,
  302. 'total_withdraw' => $totals->total_withdraw ?? 0,
  303. 'today_income' => $todayIncome,
  304. 'month_income' => $monthIncome,
  305. 'last_month_income' => $lastMonthIncome,
  306. ];
  307. } catch (\Exception $e) {
  308. Log::error('获取钱包统计信息失败', [
  309. 'wallet_id' => $walletId,
  310. 'error' => $e->getMessage(),
  311. ]);
  312. return [
  313. 'total_income' => 0,
  314. 'total_withdraw' => 0,
  315. 'today_income' => 0,
  316. 'month_income' => 0,
  317. 'last_month_income' => 0,
  318. ];
  319. }
  320. }
  321. }