UserBrokerageServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\user;
  12. use app\dao\user\UserBrokerageDao;
  13. use app\services\BaseServices;
  14. use crmeb\exceptions\ApiException;
  15. /**
  16. * 用户佣金
  17. * Class UserBrokerageServices
  18. * @package app\services\user
  19. * @method getUserFrozenPrice(int $uid) 获取某个用户冻结的佣金
  20. */
  21. class UserBrokerageServices extends BaseServices
  22. {
  23. /**
  24. * 用户记录模板
  25. * @var array[]
  26. */
  27. protected $incomeData = [
  28. 'get_self_member_brokerage' => [
  29. 'title' => '获得自购付费会员佣金',
  30. 'type' => 'self_member_brokerage',
  31. 'mark' => '您成功消费{%pay_price%}元,奖励自购佣金{%number%}',
  32. 'status' => 1,
  33. 'pm' => 1
  34. ],
  35. 'get_member_brokerage' => [
  36. 'title' => '获得下级购买付费会员佣金',
  37. 'type' => 'one_member_brokerage',
  38. 'mark' => '{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  39. 'status' => 1,
  40. 'pm' => 1
  41. ],
  42. 'get_two_member_brokerage' => [
  43. 'title' => '获得二级购买付费会员佣金',
  44. 'type' => 'two_member_brokerage',
  45. 'mark' => '二级推广人{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  46. 'status' => 1,
  47. 'pm' => 1
  48. ],
  49. 'get_self_brokerage' => [
  50. 'title' => '获得自购订单佣金',
  51. 'type' => 'self_brokerage',
  52. 'mark' => '您成功消费{%pay_price%}元,奖励自购佣金{%number%}',
  53. 'status' => 1,
  54. 'pm' => 1
  55. ],
  56. 'get_brokerage' => [
  57. 'title' => '获得下级推广订单佣金',
  58. 'type' => 'one_brokerage',
  59. 'mark' => '{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  60. 'status' => 1,
  61. 'pm' => 1
  62. ],
  63. 'get_two_brokerage' => [
  64. 'title' => '获得二级推广订单佣金',
  65. 'type' => 'two_brokerage',
  66. 'mark' => '二级推广人{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  67. 'status' => 1,
  68. 'pm' => 1
  69. ],
  70. 'get_user_brokerage' => [
  71. 'title' => '获得推广用户佣金',
  72. 'type' => 'brokerage_user',
  73. 'mark' => '成功推广用户:{%nickname%},奖励推广佣金{%number%}',
  74. 'status' => 1,
  75. 'pm' => 1
  76. ],
  77. 'extract' => [
  78. 'title' => '佣金提现',
  79. 'type' => 'extract',
  80. 'mark' => '{%mark%}',
  81. 'status' => 1,
  82. 'pm' => 0
  83. ],
  84. 'extract_fail' => [
  85. 'title' => '提现失败',
  86. 'type' => 'extract_fail',
  87. 'mark' => '提现失败,退回佣金{%number%}元',
  88. 'status' => 1,
  89. 'pm' => 1
  90. ],
  91. 'brokerage_to_nowMoney' => [
  92. 'title' => '佣金提现到余额',
  93. 'type' => 'extract_money',
  94. 'mark' => '佣金提现到余额{%number%}元',
  95. 'status' => 1,
  96. 'pm' => 0
  97. ],
  98. 'brokerage_refund' => [
  99. 'title' => '退款退佣金',
  100. 'type' => 'refund',
  101. 'mark' => '订单退款扣除佣金{%number%}元',
  102. 'status' => 1,
  103. 'pm' => 0
  104. ],
  105. 'get_staff_brokerage' => [
  106. 'title' => '获得员工推广订单佣金',
  107. 'type' => 'staff_brokerage',
  108. 'mark' => '{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  109. 'status' => 1,
  110. 'pm' => 1
  111. ],
  112. 'get_agent_brokerage' => [
  113. 'title' => '获得代理推广订单佣金',
  114. 'type' => 'agent_brokerage',
  115. 'mark' => '{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  116. 'status' => 1,
  117. 'pm' => 1
  118. ],
  119. 'get_division_brokerage' => [
  120. 'title' => '获得事业部推广订单佣金',
  121. 'type' => 'division_brokerage',
  122. 'mark' => '{%nickname%}成功消费{%pay_price%}元,奖励推广佣金{%number%}',
  123. 'status' => 1,
  124. 'pm' => 1
  125. ],
  126. 'get_pink_master_brokerage' => [
  127. 'title' => '获得拼团团长佣金',
  128. 'type' => 'pink_master_brokerage',
  129. 'mark' => '开团成功,奖励团长佣金{%number%}',
  130. 'status' => 1,
  131. 'pm' => 1
  132. ],
  133. 'get_direct_referral_brokerage' => [
  134. 'title' => '获得礼包直推奖',
  135. 'type' => 'direct_referral_brokerage',
  136. 'mark' => '{%nickname%}成功消费礼包商品{%pay_price%}元,奖励直推奖{%number%}',
  137. 'status' => 1,
  138. 'pm' => 1
  139. ],
  140. 'get_spot_brokerage' => [
  141. 'title' => '获得礼包见点奖',
  142. 'type' => 'spot_brokerage',
  143. 'mark' => '{%nickname%}成功消费礼包商品{%pay_price%}元,奖励见点奖{%number%}',
  144. 'status' => 1,
  145. 'pm' => 1
  146. ],
  147. 'brokerage_transfer_out' => [
  148. 'title' => '佣金互转转出',
  149. 'type' => 'brokerage_transfer_out',
  150. 'mark' => '佣金互转给{%nickname%},金额{%number%}元',
  151. 'status' => 1,
  152. 'pm' => 0
  153. ],
  154. 'brokerage_transfer_in' => [
  155. 'title' => '佣金互转转入',
  156. 'type' => 'brokerage_transfer_in',
  157. 'mark' => '收到{%nickname%}的佣金互转,金额{%number%}元',
  158. 'status' => 1,
  159. 'pm' => 1
  160. ],
  161. ];
  162. /**
  163. * UserBrokerageServices constructor.
  164. * @param UserBrokerageDao $dao
  165. */
  166. public function __construct(UserBrokerageDao $dao)
  167. {
  168. $this->dao = $dao;
  169. }
  170. /**
  171. * 写入佣金记录
  172. * @param string $type 写入类型
  173. * @param int $uid
  174. * @param int|string|array $number
  175. * @param int|string $balance
  176. * @param $linkId
  177. * @return bool|mixed
  178. */
  179. public function income(string $type, int $uid, $number, $balance, $linkId)
  180. {
  181. $data = $this->incomeData[$type] ?? null;
  182. if (!$data) {
  183. return true;
  184. }
  185. $data['uid'] = $uid;
  186. $data['balance'] = $balance ?? 0;
  187. $data['link_id'] = $linkId;
  188. if (is_array($number)) {
  189. $key = array_keys($number);
  190. $key = array_map(function ($item) {
  191. return '{%' . $item . '%}';
  192. }, $key);
  193. $value = array_values($number);
  194. $data['number'] = $number['number'] ?? 0;
  195. $data['frozen_time'] = $number['frozen_time'] ?? 0;
  196. $data['mark'] = str_replace($key, $value, $data['mark']);
  197. } else {
  198. $data['number'] = $number;
  199. $data['mark'] = str_replace(['{%number%}'], $number, $data['mark']);
  200. }
  201. $data['add_time'] = time();
  202. return $this->dao->save($data);
  203. }
  204. /**
  205. * 某个用户佣金总和
  206. * @param int $uid
  207. * @param array|string[] $type
  208. * @param string $time
  209. * @return float
  210. * @throws \ReflectionException
  211. */
  212. public function getUserBrokerageSum(int $uid, array $type = ['one_brokerage', 'two_brokerage', 'brokerage_user'], $time = '')
  213. {
  214. $where = ['uid' => $uid];
  215. if ($type) $where['type'] = $type;
  216. if ($time) $where['time'] = $time;
  217. return $this->dao->sum($where, 'number', true);
  218. }
  219. /**
  220. * 退佣金
  221. * @param $order
  222. * @return bool
  223. * @throws \think\db\exception\DataNotFoundException
  224. * @throws \think\db\exception\DbException
  225. * @throws \think\db\exception\ModelNotFoundException
  226. */
  227. public function orderRefundBrokerageBack($order)
  228. {
  229. $id = (int)$order['id'];
  230. $where = [
  231. 'uid' => [$order['spread_uid'], $order['spread_two_uid'], $order['staff_id'], $order['agent_id'], $order['division_id']],
  232. 'type' => ['self_brokerage', 'one_brokerage', 'two_brokerage', 'staff_brokerage', 'agent_brokerage', 'division_brokerage', 'pink_master_brokerage'],
  233. 'link_id' => $id,
  234. 'pm' => 1
  235. ];
  236. $brokerageList = $this->dao->getUserBrokerageList($where);
  237. //子订单
  238. if (!$brokerageList && $order['pid']) {
  239. $where['link_id'] = $order['pid'];
  240. $p_brokerageList = $this->dao->getUserBrokerageList($where);
  241. //主订单已分佣 子订单按订单拆分后计算结果回退
  242. if ($p_brokerageList) {
  243. $brokerageList = [
  244. ['uid' => $order['spread_uid'], 'number' => $order['one_brokerage']],
  245. ['uid' => $order['spread_two_uid'], 'number' => $order['two_brokerage']],
  246. ];
  247. }
  248. }
  249. $res = true;
  250. if ($brokerageList) {
  251. /** @var UserServices $userServices */
  252. $userServices = app()->make(UserServices::class);
  253. $brokerages = $userServices->getColumn([['uid', 'in', array_column($brokerageList, 'uid')]], 'brokerage_price', 'uid');
  254. $brokerageData = [];
  255. foreach ($brokerageList as $item) {
  256. if (!$item['uid']) continue;
  257. $usermoney = $brokerages[$item['uid']] ?? 0;
  258. if ($item['number'] > $usermoney) {
  259. $item['number'] = $usermoney;
  260. }
  261. $res = $res && $userServices->bcDec($item['uid'], 'brokerage_price', (string)$item['number'], 'uid');
  262. $brokerageData[] = [
  263. 'title' => '退款退佣金',
  264. 'uid' => $item['uid'],
  265. 'pm' => 0,
  266. 'add_time' => time(),
  267. 'type' => 'refund',
  268. 'number' => $item['number'],
  269. 'link_id' => $id,
  270. 'balance' => bcsub((string)$usermoney, (string)$item['number'], 2),
  271. 'mark' => '订单退款扣除佣金' . floatval($item['number']) . '元'
  272. ];
  273. }
  274. if ($brokerageData) {
  275. $res = $res && $this->dao->saveAll($brokerageData);
  276. }
  277. //修改佣金冻结时间
  278. $this->dao->update($where, ['frozen_time' => 0]);
  279. }
  280. return $res;
  281. }
  282. /**
  283. * 佣金排行
  284. * @param string $time
  285. * @return array
  286. * @throws \think\db\exception\DataNotFoundException
  287. * @throws \think\db\exception\DbException
  288. * @throws \think\db\exception\ModelNotFoundException
  289. */
  290. public function brokerageRankList(string $time = 'week')
  291. {
  292. $where = ['pm' => 1];
  293. if ($time) {
  294. $where['time'] = $time;
  295. }
  296. [$page, $limit] = $this->getPageValue();
  297. $list = $this->dao->brokerageRankList($where, $page, $limit);
  298. foreach ($list as $key => &$item) {
  299. if (!isset($item['user']) || !$item['user'] || $item['brokerage_price'] <= 0) {
  300. unset($list[$key]);
  301. continue;
  302. }
  303. $item['nickname'] = $item['user']['nickname'] ?? '';
  304. $item['avatar'] = $item['user']['avatar'] ?? '';
  305. if ($item['brokerage_price'] == '0.00' || $item['brokerage_price'] == 0 || !$item['brokerage_price']) {
  306. unset($list[$key]);
  307. }
  308. unset($item['user']);
  309. }
  310. return array_merge($list);
  311. }
  312. /**
  313. * 获取用户排名
  314. * @param int $uid
  315. * @param string $time
  316. * @return false|int|string
  317. * @throws \think\db\exception\DataNotFoundException
  318. * @throws \think\db\exception\DbException
  319. * @throws \think\db\exception\ModelNotFoundException
  320. */
  321. public function getUserBrokerageRank(int $uid, string $time = 'week')
  322. {
  323. $where = ['pm' => 1];
  324. if ($time) {
  325. $where['time'] = $time;
  326. }
  327. $list = $this->dao->brokerageRankList($where);
  328. foreach ($list as $key => &$item) {
  329. if (!isset($item['user']) || !$item['user'] || $item['brokerage_price'] <= 0) {
  330. unset($list[$key]);
  331. }
  332. }
  333. $position_tmp_one = array_column($list, 'uid');
  334. $position_tmp_two = array_column($list, 'brokerage_price', 'uid');
  335. if (!in_array($uid, $position_tmp_one)) {
  336. $position = 0;
  337. } else {
  338. if ($position_tmp_two[$uid] == 0.00) {
  339. $position = 0;
  340. } else {
  341. $position = array_search($uid, $position_tmp_one) + 1;
  342. }
  343. }
  344. return $position;
  345. }
  346. /**
  347. * 推广数据 昨天的佣金 累计提现金额 当前佣金
  348. * @param int $uid
  349. * @return mixed
  350. * @throws \think\db\exception\DataNotFoundException
  351. * @throws \think\db\exception\DbException
  352. * @throws \think\db\exception\ModelNotFoundException
  353. */
  354. public function commission(int $uid)
  355. {
  356. /** @var UserServices $userServices */
  357. $userServices = app()->make(UserServices::class);
  358. if (!$userServices->getUserInfo($uid)) {
  359. throw new ApiException(100026);
  360. }
  361. /** @var UserExtractServices $userExtract */
  362. $userExtract = app()->make(UserExtractServices::class);
  363. $data = [];
  364. $data['uid'] = $uid;
  365. $data['pm'] = 1;
  366. $data['commissionSum'] = $this->getUsersBokerageSum($data);
  367. $extract_fail = $this->dao->sum(['uid' => $uid, 'pm' => 1, 'type' => 'extract_fail'], 'number');
  368. $data['commissionSum'] = bcadd($data['commissionSum'], $extract_fail, 2);
  369. $data['pm'] = 0;
  370. $data['commissionRefund'] = $this->getUsersBokerageSum($data);
  371. $data['commissionCount'] = $data['commissionSum'] > $data['commissionRefund'] ? bcsub((string)$data['commissionSum'], (string)$data['commissionRefund'], 2) : 0.00;
  372. $data['lastDayCount'] = $this->getUsersBokerageSum($data, 'yesterday');//昨天的佣金
  373. $data['extractCount'] = $userExtract->getUserExtract($uid);//累计提现金额
  374. return $data;
  375. }
  376. /**
  377. * 计算佣金
  378. * @param array $where
  379. * @param int $time
  380. * @return mixed
  381. * @throws \ReflectionException
  382. */
  383. public function getUsersBokerageSum(array $where, $time = 0)
  384. {
  385. $where_data = [
  386. 'status' => 1,
  387. 'pm' => $where['pm'] ?? '',
  388. 'uid' => $where['uid'] ?? '',
  389. 'time' => $where['time'] ?? 0
  390. ];
  391. if ($time) $where_data['time'] = $time;
  392. return $this->dao->getBrokerageSumColumn($where_data);
  393. }
  394. /**
  395. * 佣金明细
  396. * @param $uid
  397. * @param $type
  398. * @return array
  399. * @throws \ReflectionException
  400. * @throws \think\db\exception\DataNotFoundException
  401. * @throws \think\db\exception\DbException
  402. * @throws \think\db\exception\ModelNotFoundException
  403. */
  404. public function getBrokerageList($uid, $type,$pm)
  405. {
  406. $where = [];
  407. $where['uid'] = $uid;
  408. [$page, $limit] = $this->getPageValue();
  409. if ($type == 4) {
  410. $where['type'] = ['extract', 'extract_money', 'extract_fail'];
  411. }
  412. if ($pm !== '' && $pm !== null) {
  413. $where['pm'] = $pm;
  414. }
  415. /** @var UserExtractServices $userExtractService */
  416. $userExtractService = app()->make(UserExtractServices::class);
  417. $userExtract = $userExtractService->getColumn(['uid' => $uid], 'fail_msg,extract_type,state,wechat_order_id', 'id');
  418. $list = $this->dao->getList($where, '*', $page, $limit);
  419. $count = $this->dao->count($where);
  420. $times = [];
  421. if ($list) {
  422. foreach ($list as &$item) {
  423. $item['time'] = $item['time_key'] = $item['add_time'] ? date('Y-m', (int)$item['add_time']) : '';
  424. $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i', (int)$item['add_time']) : '';
  425. $item['fail_msg'] = $item['type'] == 'extract_fail' ? $userExtract[$item['link_id']]['fail_msg'] : '';
  426. if ($type == 4) {
  427. $extract_type = $userExtract[$item['link_id']]['extract_type'] ?? '';
  428. if ($extract_type == 'alipay') {
  429. $item['extract_type'] = '支付宝';
  430. } elseif ($extract_type == 'weixin') {
  431. $item['extract_type'] = '微信';
  432. } elseif ($extract_type == 'bank') {
  433. $item['extract_type'] = '银行卡';
  434. } else {
  435. $item['extract_type'] = '余额';
  436. }
  437. $item['state'] = $userExtract[$item['link_id']]['state'] ?? '';
  438. $item['wechat_order_id'] = $userExtract[$item['link_id']]['wechat_order_id'] ?? '';
  439. } else {
  440. $item['extract_type'] = '';
  441. }
  442. }
  443. // 生成月份列表
  444. $times = array_merge(array_unique(array_column($list, 'time_key')));
  445. // // type=3时按月份分组
  446. // if ($type == 3) {
  447. // $groupedList = [];
  448. // foreach ($list as $item) {
  449. // $month = $item['time_key'];
  450. // if (!isset($groupedList[$month])) {
  451. // $groupedList[$month] = [];
  452. // }
  453. // $groupedList[$month][] = $item;
  454. // }
  455. // $list = $groupedList;
  456. // }
  457. }
  458. return ['list' => $list, 'time' => $times, 'count' => $count];
  459. }
  460. /**
  461. * 前端佣金排行页面数据
  462. * @param int $uid
  463. * @param $type
  464. * @return array
  465. * @throws \think\db\exception\DataNotFoundException
  466. * @throws \think\db\exception\DbException
  467. * @throws \think\db\exception\ModelNotFoundException
  468. */
  469. public function brokerageRank(int $uid, $type)
  470. {
  471. /** @var UserServices $userService */
  472. $userService = app()->make(UserServices::class);
  473. if (!$userService->getUserInfo($uid)) {
  474. throw new ApiException(100026);
  475. }
  476. return [
  477. 'rank' => $this->brokerageRankList($type),
  478. 'position' => $this->getUserBrokerageRank($uid, $type)
  479. ];
  480. }
  481. /**
  482. * 佣金互转
  483. * @param int $uid 转账用户ID
  484. * @param int $toUid 收款用户ID
  485. * @param string $money 转账金额
  486. * @return array
  487. * @throws ApiException
  488. */
  489. public function transferBrokerage(int $uid, int $toUid, string $money)
  490. {
  491. // 验证参数
  492. if ($uid <= 0) {
  493. throw new ApiException(100026);
  494. }
  495. if ($toUid <= 0) {
  496. throw new ApiException('收款用户不存在');
  497. }
  498. if ($uid == $toUid) {
  499. throw new ApiException('不能转账给自己');
  500. }
  501. if (bccomp($money, '0', 2) <= 0) {
  502. throw new ApiException('转账金额必须大于0');
  503. }
  504. /** @var UserServices $userService */
  505. $userService = app()->make(UserServices::class);
  506. // 获取转账方和收款方信息
  507. $fromUser = $userService->getUserInfo($uid);
  508. if (!$fromUser) {
  509. throw new ApiException(100026);
  510. }
  511. $toUser = $userService->getUserInfo($toUid);
  512. if (!$toUser) {
  513. throw new ApiException('收款用户不存在');
  514. }
  515. // 检查转账方佣金余额
  516. $fromBrokerage = $fromUser['brokerage_price'] ?? 0;
  517. if (bccomp((string)$fromBrokerage, $money, 2) < 0) {
  518. throw new ApiException('佣金余额不足');
  519. }
  520. // 计算手续费
  521. $transferFeeRate = sys_config('transfer_fee', 0);
  522. $transferFee = bcmul((string)$money, bcdiv((string)$transferFeeRate, '100', 4), 2);
  523. $actualAmount = bcsub((string)$money, $transferFee, 2);
  524. // 使用事务处理
  525. return $this->transaction(function () use ($uid, $toUid, $money, $transferFee, $actualAmount, $fromUser, $toUser, $fromBrokerage) {
  526. // 扣除转账方佣金
  527. $newFromBrokerage = bcsub((string)$fromBrokerage, $money, 2);
  528. $userService->update($uid, ['brokerage_price' => $newFromBrokerage], 'uid');
  529. // 增加收款方佣金
  530. $toBrokerage = $toUser['brokerage_price'] ?? 0;
  531. $newToBrokerage = bcadd((string)$toBrokerage, $actualAmount, 2);
  532. $userService->update($toUid, ['brokerage_price' => $newToBrokerage], 'uid');
  533. // 记录转账方扣除记录
  534. $this->income('brokerage_transfer_out', $uid, [
  535. 'mark' => '佣金互转给' . $toUser['nickname'] . ',金额' . $money . '元',
  536. 'number' => $money
  537. ], $newFromBrokerage, 0);
  538. // 记录收款方收入记录
  539. $this->income('brokerage_transfer_in', $toUid, [
  540. 'mark' => '收到' . $fromUser['nickname'] . '的佣金互转,金额' . $actualAmount . '元',
  541. 'number' => $actualAmount
  542. ], $newToBrokerage, 0);
  543. return '转账成功';
  544. });
  545. }
  546. }