WalletService.php 16 KB

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