WalletService.php 13 KB

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