FundService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace App\Module\Fund\Services;
  3. use App\Module\Fund\Dto\CirculationDto;
  4. use App\Module\Fund\Dto\FundAccountDto;
  5. use App\Module\Fund\Dto\FundAdminDto;
  6. use App\Module\Fund\Dto\TradeResultDto;
  7. use App\Module\Fund\Dto\TransferResultDto;
  8. use App\Module\Fund\Enums\FUND_TYPE;
  9. use App\Module\Fund\Enums\LOG_TYPE;
  10. use App\Module\Fund\Models\FundAdminModel;
  11. use App\Module\Fund\Models\FundModel;
  12. use App\Module\Fund\Logic\Circulation;
  13. use App\Module\Fund\Logic\Transfer;
  14. use App\Module\Fund\Logic\User;
  15. use Illuminate\Support\Facades\DB;
  16. use UCore\Db\Helper;
  17. use UCore\Helper\Logger;
  18. class FundService
  19. {
  20. private int $userId;
  21. private int $fundId;
  22. private ?FundModel $fundModel;
  23. public function __construct(int $userId, $fundId)
  24. {
  25. $this->userId = $userId;
  26. if (is_int($fundId)) {
  27. $this->fundId = $fundId;
  28. } else {
  29. $this->fundId = $fundId->valueInt();
  30. }
  31. $this->fundModel = FundModel::query()
  32. ->where('user_id', $userId)
  33. ->where('fund_id', $fundId)
  34. ->first();
  35. }
  36. /**
  37. * 资金流转
  38. * (同用户,同币种,不同账户)
  39. *
  40. * @param FUND_TYPE $to_fund_id 目标资金类型
  41. * @param float $amount 金额(小数形式)
  42. * @param int $re_id 关联ID
  43. * @param string $re_type 关联类型
  44. * @param string $remark 备注
  45. * @return CirculationDto|string 成功返回DTO,失败返回错误信息
  46. */
  47. public function circulation(FUND_TYPE $to_fund_id, float $amount, int $re_id, string $re_type, string $remark)
  48. {
  49. # 确认货币种类一致
  50. if (!CurrencyService::check($this->fundId, $to_fund_id->valueInt())) {
  51. return '币种不一致,禁止划转';
  52. }
  53. # 验证金额精度
  54. $currency = CurrencyService::getCurrencyByFundId($this->fundId);
  55. if (!$currency) {
  56. return '无法获取币种信息';
  57. }
  58. # 验证并格式化金额精度
  59. if (!CurrencyService::validateAmountPrecision($amount, $currency->currencyId)) {
  60. return '金额精度超出币种支持范围';
  61. }
  62. $formattedAmount = CurrencyService::formatAmountToPrecision($amount, $currency->currencyId);
  63. if (bccomp($amount, $formattedAmount, 10) != 0) {
  64. return '数值错误,精度丢失';
  65. }
  66. if (bccomp(0, $formattedAmount, 10) == 0) {
  67. return '数值错误,数值丢失';
  68. }
  69. Logger::debug(" jine $amount , $formattedAmount");
  70. # 实例化操作对象
  71. Helper::check_tr();
  72. # 先进行转账记录
  73. $circulation_id = Circulation::handle($this->userId, $this->fundId, $to_fund_id->valueInt(), $formattedAmount, $re_id, $re_type,
  74. $remark);
  75. if (is_string($circulation_id)) {
  76. return $circulation_id;
  77. }
  78. # 进行双方的资金修改
  79. # 先减少自己的
  80. $re46 = User::handle($this->userId, $this->fundId, -$formattedAmount, LOG_TYPE::CIRCULATION, $circulation_id, $remark);
  81. if (is_string($re46)) {
  82. return $re46;
  83. }
  84. # 再增加自己另一个账户
  85. $re51 = User::handle($this->userId, $to_fund_id->valueInt(), $formattedAmount, LOG_TYPE::CIRCULATION, $circulation_id, $remark);
  86. if (is_string($re51)) {
  87. return $re51;
  88. }
  89. // 获取流转记录
  90. $circulationModel = \App\Module\Fund\Models\FundCirculationModel::find($circulation_id);
  91. if (!$circulationModel) {
  92. return '流转记录不存在';
  93. }
  94. // 获取资金类型名称映射
  95. $fundNames = AccountService::getFundsDesc();
  96. // 将模型转换为DTO并返回
  97. return CirculationDto::fromModel($circulationModel, $fundNames);
  98. }
  99. /**
  100. * 获取账户信息
  101. *
  102. * @return FundAccountDto|null 账户DTO,如果账户不存在则返回null
  103. */
  104. public function getAccount(): ?FundAccountDto
  105. {
  106. // 如果账户不存在,返回null
  107. if (!$this->fundModel) {
  108. return null;
  109. }
  110. // 获取资金类型名称映射
  111. $fundNames = AccountService::getFundsDesc();
  112. // 将模型转换为DTO
  113. return FundAccountDto::fromModel($this->fundModel, $fundNames);
  114. }
  115. /**
  116. * 获取余额
  117. *
  118. * @return float 账户余额(小数形式)
  119. */
  120. public function balance(): float
  121. {
  122. // 直接返回数据库中的小数值
  123. return (float)($this->fundModel->balance ?? 0);
  124. }
  125. /**
  126. * 检查余额是否足够
  127. *
  128. * @param $balance
  129. * @return bool
  130. */
  131. public function check($balance): bool
  132. {
  133. $res = bccomp($this->balance(), (string)$balance, 10) >= 0;
  134. if($res){
  135. Logger::debug(" check {$this->userId} - {$this->fundId} : {$this->balance()} ,need $balance");
  136. }else{
  137. Logger::error(" check {$this->userId} - {$this->fundId} : {$this->balance()} ,need $balance");
  138. }
  139. return $res;
  140. }
  141. /**
  142. * 转账
  143. * (不同人,同账户/同币种)
  144. *
  145. * @param int $toUserId 接收用户ID
  146. * @param float $amount 金额(小数形式)
  147. * @param string $remark 备注
  148. * @return TransferResultDto|string 成功返回DTO,失败返回错误信息
  149. */
  150. public function transfer(int $toUserId, float $amount, string $remark)
  151. {
  152. # 验证金额精度
  153. $currency = CurrencyService::getCurrencyByFundId($this->fundId);
  154. if (!$currency) {
  155. return '无法获取币种信息';
  156. }
  157. # 验证并格式化金额精度
  158. if (!CurrencyService::validateAmountPrecision($amount, $currency->currencyId)) {
  159. return '金额精度超出币种支持范围';
  160. }
  161. $formattedAmount = CurrencyService::formatAmountToPrecision($amount, $currency->currencyId);
  162. if (bccomp($amount, $formattedAmount, 10) != 0) {
  163. return '数值错误,精度丢失';
  164. }
  165. if (bccomp(0, $formattedAmount, 10) == 0) {
  166. return '数值错误,数值丢失';
  167. }
  168. # 实例化操作对象
  169. # 开启事务
  170. DB::beginTransaction();
  171. # 先进行转账记录
  172. $transfer_id = Transfer::to_user(
  173. $this->userId,
  174. $this->fundId,
  175. $toUserId,
  176. $formattedAmount,
  177. $remark);
  178. if (is_string($transfer_id)) {
  179. DB::rollBack();
  180. return $transfer_id;
  181. }
  182. # 进行双方的资金修改
  183. # 先减少自己的
  184. $re46 = User::handle($this->userId, $this->fundId, -$formattedAmount, LOG_TYPE::TRANSFER, $transfer_id, $remark);
  185. if (is_string($re46)) {
  186. DB::rollBack();
  187. return $re46;
  188. }
  189. # 再增加别人的
  190. $re51 = User::handle($toUserId, $this->fundId, $formattedAmount, LOG_TYPE::TRANSFER, $transfer_id, $remark);
  191. if (is_string($re51)) {
  192. DB::rollBack();
  193. return $re51;
  194. }
  195. DB::commit();
  196. // 获取转账记录
  197. $transferModel = \App\Module\Fund\Models\FundTransferModel::find($transfer_id);
  198. if (!$transferModel) {
  199. return '转账记录不存在';
  200. }
  201. // 获取资金类型名称映射
  202. $fundNames = AccountService::getFundsDesc();
  203. // 获取用户名称映射
  204. $userNames = [];
  205. $userIds = [ $this->userId, $toUserId ];
  206. $users = \App\Module\User\Models\User::whereIn('id', $userIds)->get();
  207. foreach ($users as $user) {
  208. $userNames[$user->id] = $user->username;
  209. }
  210. // 将模型转换为DTO并返回
  211. return TransferResultDto::fromModel($transferModel, $fundNames, $userNames);
  212. }
  213. /**
  214. * 贸易(业务关联)
  215. * 同账户/同币种,不同用户
  216. *
  217. * @param int $toUserId 接收用户ID
  218. * @param float $amount 金额(小数形式)
  219. * @param string $transfer_type 关联类型
  220. * @param string $transfer_id 关联ID
  221. * @param string $remark 备注
  222. * @return TradeResultDto|string 成功返回DTO,失败返回错误信息
  223. */
  224. public function trade(int $toUserId, float $amount, $transfer_type, $transfer_id, string $remark)
  225. {
  226. # 验证金额精度
  227. $currency = CurrencyService::getCurrency2ByFundId($this->fundId);
  228. if (!$currency) {
  229. return '无法获取币种信息';
  230. }
  231. # 验证并格式化金额精度
  232. if (!CurrencyService::validateAmountPrecision($amount, $currency->value)) {
  233. return '金额精度超出币种支持范围';
  234. }
  235. $formattedAmount = CurrencyService::formatAmountToPrecision($amount, $currency->value);
  236. if (bccomp($amount, $formattedAmount, 10) != 0) {
  237. return '数值错误,精度丢失';
  238. }
  239. if (bccomp(0, $formattedAmount, 10) == 0) {
  240. return '数值错误,数值丢失';
  241. }
  242. # 检查事务开启
  243. Helper::check_tr();
  244. $full_transfer_id = $transfer_type . '-' . $transfer_id;
  245. # 先减少自己的
  246. $re46 = User::handle($this->userId, $this->fundId, -$formattedAmount, LOG_TYPE::TRADE, $full_transfer_id, $remark);
  247. if (is_string($re46)) {
  248. \UCore\Trace::addData('error', $re46);
  249. return $re46;
  250. }
  251. # 再增加别人的
  252. $re51 = User::handle($toUserId, $this->fundId, $formattedAmount, LOG_TYPE::TRANSFER, $full_transfer_id, $remark);
  253. if (is_string($re51)) {
  254. \UCore\Trace::addData('error', $re51);
  255. return $re51;
  256. }
  257. // 获取资金类型名称映射
  258. $fundNames = AccountService::getFundsDesc();
  259. // 获取用户名称映射
  260. $userNames = [];
  261. $userIds = [ $this->userId, $toUserId ];
  262. $users = \App\Module\User\Models\User::whereIn('id', $userIds)->get();
  263. foreach ($users as $user) {
  264. $userNames[$user->id] = $user->username;
  265. }
  266. // 创建DTO并返回(传入原始小数金额)
  267. return TradeResultDto::create(
  268. $this->userId,
  269. $toUserId,
  270. $this->fundId,
  271. $amount,
  272. $transfer_type,
  273. $transfer_id,
  274. $remark,
  275. $fundNames,
  276. $userNames
  277. );
  278. }
  279. /**
  280. * Admin 资金操作
  281. *
  282. * @param int $admin_id
  283. * @param FUND_TYPE $fund_id
  284. * @param float $fund_fee 金额(小数形式)
  285. * @param $remark
  286. * @return FundAdminDto|string 成功返回DTO,失败返回错误信息
  287. */
  288. public function admin_operate(int $admin_id, FUND_TYPE $fund_id, float $fund_fee, $remark)
  289. {
  290. # 验证金额精度
  291. $currency = CurrencyService::getCurrencyByFundId($fund_id->valueInt());
  292. if (!$currency) {
  293. return '无法获取币种信息';
  294. }
  295. # 验证并格式化金额精度
  296. if (!CurrencyService::validateAmountPrecision($fund_fee, $currency->currencyId)) {
  297. return '金额精度超出币种支持范围';
  298. }
  299. $formattedFundFee = CurrencyService::formatAmountToPrecision($fund_fee, $currency->currencyId);
  300. $data = [
  301. 'total_fee' => $formattedFundFee,
  302. 'status' => 1,
  303. 'user_id' => $this->userId,
  304. 'fund_id' => $fund_id->valueInt(),
  305. 'admin_id' => $admin_id,
  306. 'create_time' => time(),
  307. 'remark' => $remark
  308. ];
  309. # 启动事务
  310. DB::beginTransaction();
  311. # 写日志
  312. $fund_admin = new FundAdminModel();
  313. $fund_admin->setData($data);
  314. if ($fund_admin->save() === false) {
  315. DB::rollBack();
  316. return '_Model-error';
  317. }
  318. # 进行资金操作
  319. $re = \App\Module\Fund\Logic\User::handle($this->userId, $fund_id->value, $formattedFundFee,
  320. \App\Module\Fund\Enums\LOG_TYPE::ADMIN, $fund_admin->id, $remark);
  321. if (is_string($re)) {
  322. DB::rollBack();
  323. return $re;
  324. }
  325. DB::commit();
  326. // 获取资金类型名称映射
  327. $fundNames = AccountService::getFundsDesc();
  328. // 将模型转换为DTO并返回
  329. return FundAdminDto::fromModel($fund_admin, $fundNames);
  330. }
  331. }