SharedProsperityTaskRepository.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. namespace app\common\repositories\shared;
  3. use app\common\dao\shared\SharedProsperityBalanceLogDao;
  4. use app\common\dao\shared\SharedProsperityPointLogDao;
  5. use app\common\dao\shared\SharedProsperityRecommendConfigDao;
  6. use app\common\dao\shared\SharedProsperityUserDao;
  7. use app\common\enum\CommonEnum;
  8. use app\common\enum\shared\SharedProsperityRewardRecordEnum;
  9. use app\common\repositories\BaseRepository;
  10. use app\common\repositories\user\UserBillRepository;
  11. use think\facade\Db;
  12. use think\facade\Log;
  13. class SharedProsperityTaskRepository extends BaseRepository
  14. {
  15. const PARTNER_RADIO = 1;
  16. const REWARD_TYPE_PV = SharedProsperityRewardRecordEnum::TYPE['PV']['code'];
  17. /**
  18. * @param $data
  19. * @return void
  20. * @throws \Exception
  21. * @author 史晨
  22. * @date 2026/2/10 10:10
  23. * 合伙人分红(加权分配)
  24. */
  25. public function partner($data)
  26. {
  27. // 获取时间范围内订单
  28. $merId = CommonEnum::DESIGN_MERCHANT_ID['SharedProsperity']['code'];
  29. $start = $data['startTime'];
  30. $end = $data['endTime'];
  31. // 获取pv
  32. /** @var SharedProsperityRewardRecordRepository $rewardRecordRepository */
  33. $rewardRecordRepository = app()->make(SharedProsperityRewardRecordRepository::class);
  34. $orderList = $rewardRecordRepository->getListByTime($start, $end, self::REWARD_TYPE_PV);
  35. if (empty($orderList)) {
  36. throw new \Exception('没有订单');
  37. }
  38. // 计算可分配利润
  39. $totalConPri = array_sum(array_column($orderList, 'number'));
  40. $conPri = floor($totalConPri * self::PARTNER_RADIO * 100) / 100;
  41. // 获取合伙人分配规则
  42. /** @var SharedProsperityRecommendConfigDao $configDao */
  43. $configDao = app()->make(SharedProsperityRecommendConfigDao::class);
  44. $config = $configDao->getConfigList(false);
  45. $config = array_column($config, 'profit_ratio', 'level');
  46. if (empty($config)) {
  47. throw new \Exception('没有合伙人分配规则');
  48. }
  49. // 获取合伙人
  50. /** @var SharedProsperityUserDao $userDao */
  51. $userDao = app()->make(SharedProsperityUserDao::class);
  52. $users = $userDao->getUserGroupByPartnerLevel();
  53. /** @var SharedProsperityBalanceLogDao $balanceDao */
  54. $balanceDao = app()->make(SharedProsperityBalanceLogDao::class);
  55. Db::startTrans();
  56. try {
  57. foreach ($users as $key => $userIds) {
  58. if ($key == 0) {
  59. continue;
  60. }
  61. $radio = $config[$key];
  62. // 该等级总分红
  63. $levelTotal = floor(($conPri * ($radio / 100)) * 100) / 100;
  64. // 获取该等级所有用户的基本信息
  65. $userInfos = $userDao->getSharedProsperityUserEntityListByUserIdList($userIds);
  66. if (empty($userInfos)) {
  67. continue;
  68. }
  69. // 计算每个用户的团队业绩(实时统计)
  70. $teamPvMap = [];
  71. $totalTeamPv = 0;
  72. foreach ($userInfos as $userInfo) {
  73. $teamPv = $userDao->getTeamPvSum($userInfo->getUserId());
  74. $teamPvMap[$userInfo->getUserId()] = $teamPv;
  75. $totalTeamPv += $teamPv;
  76. }
  77. // 如果总团队业绩为0,则平均分配
  78. if ($totalTeamPv == 0) {
  79. $userNum = count($userInfos);
  80. $eachReward = floor(($levelTotal / $userNum) * 100) / 100;
  81. foreach ($userInfos as $userInfo) {
  82. $userReward = $eachReward;
  83. $this->distributeReward($userInfo, $userReward, $radio, $levelTotal, $balanceDao, $userDao);
  84. }
  85. } else {
  86. // 加权分配
  87. foreach ($userInfos as $userInfo) {
  88. $weight = $teamPvMap[$userInfo->getUserId()] / $totalTeamPv;
  89. $userReward = floor($levelTotal * $weight * 100) / 100;
  90. $this->distributeReward($userInfo, $userReward, $radio, $levelTotal, $balanceDao, $userDao);
  91. }
  92. }
  93. }
  94. Db::commit();
  95. } catch (\Exception $e) {
  96. Db::rollback();
  97. throw new \Exception($e->getMessage());
  98. }
  99. }
  100. /**
  101. * 分发奖励(记录日志和更新余额)
  102. * @param $userInfo
  103. * @param $userReward
  104. * @param $radio
  105. * @param $levelTotal
  106. * @param $balanceDao
  107. * @param $userDao
  108. * @return void
  109. */
  110. private function distributeReward($userInfo, $userReward, $radio, $levelTotal, $balanceDao, $userDao)
  111. {
  112. $userId = $userInfo->getUserId();
  113. $balanceDao->create([
  114. 'user_id' => $userId,
  115. 'level' => $userInfo->getPartnerLevel(),
  116. 'radio' => $radio,
  117. 'total_profit' => $levelTotal,
  118. 'old' => $userInfo->getBalance(),
  119. 'number' => $userReward,
  120. 'after' => $userInfo->getBalance() + $userReward
  121. ]);
  122. $bill = [
  123. 'uid' => $userId,
  124. 'link_id' => 0,
  125. 'pm' => 1,
  126. 'title' => '共富体系合伙人分佣(加权)',
  127. 'category' => 'now_money',
  128. 'type' => 'commission',
  129. 'number' => $userReward,
  130. 'balance' => 0,
  131. 'mark' => '共富体系合伙人分佣明细入账(加权)',
  132. 'create_time' => date('Y-m-d H:i:s'),
  133. 'status' => 1,
  134. 'commission_type' => CommonEnum::COMMISSION_TYPE['SHARED_PROSPERITY_PARTNER_COMMISSION']['code'],
  135. 'order_sn' => 0,
  136. 'tripartite' => 0,
  137. 'type_shop' => 0,
  138. 'mer_id' => 0,
  139. 'source' => 0,
  140. 'order_type' => 1,
  141. 'is_red_brokerage' => 0,
  142. 'gzc' => 3,
  143. 'take_time' => time(),
  144. 'district_id' => '',
  145. 'street_id' => '',
  146. 'month' => '',
  147. ];
  148. Db::name('user_bill')->insert($bill);
  149. $userDao->updateByUserId($userId, ['balance' => ['inc', $userReward]]);
  150. }
  151. /**
  152. * @param $data
  153. * @return true
  154. * @throws \think\db\exception\DataNotFoundException
  155. * @throws \think\db\exception\DbException
  156. * @throws \think\db\exception\ModelNotFoundException
  157. * @author 史晨
  158. * @date 2026/2/10 15:22
  159. * 感恩奖
  160. */
  161. public function thank($data)
  162. {
  163. // 获取时间范围内订单
  164. $start = $data['startTime'];
  165. $end = $data['endTime'];
  166. // 获取收入
  167. /** @var UserBillRepository $userBillRepository */
  168. $userBillRepository = app()->make(UserBillRepository::class);
  169. $billList = $userBillRepository->getListForSharedProsperityThank($start, $end);
  170. if (empty($billList)) {
  171. throw new \Exception('没有佣金记录,无需处理');
  172. }
  173. // /** @var SharedProsperityRewardRecordRepository $rewardRecordRepository */
  174. // $rewardRecordRepository = app()->make(SharedProsperityRewardRecordRepository::class);
  175. // $rewardList = $rewardRecordRepository->getListByTime($start, $end, self::REWARD_TYPE_PV);
  176. // if (empty($rewardList)) {
  177. // throw new \Exception('没有订单');
  178. // }
  179. // user_id分区求和 [id]=>[number]
  180. $groupedResult = array_reduce($billList, function ($carry, $item) {
  181. $userId = $item['uid'];
  182. $number = floatval($item['number']);
  183. if (!isset($carry[$userId])) {
  184. $carry[$userId] = 0;
  185. }
  186. $carry[$userId] += $number;
  187. return $carry;
  188. }, []);
  189. if (empty($groupedResult)) {
  190. throw new \Exception('分组求和错误');
  191. }
  192. /** @var SharedProsperityUserRepository $userRepository */
  193. $userRepository = app()->make(SharedProsperityUserRepository::class);
  194. /** @var SharedProsperityPointLogDao $balanceDao */
  195. $logDao = app()->make(SharedProsperityPointLogDao::class);
  196. DB::startTrans();
  197. try {
  198. foreach ($groupedResult as $key => $value) {
  199. // 获取感恩奖比例
  200. $radio = CommonEnum::ORDER_EARNING_ALLOCATION['SharedProsperity']['Thank']['code'];
  201. // 计算积分
  202. $points = floor($value * $radio * 100) / 100;
  203. // 获取上级
  204. $userData = $userRepository->getSharedProsperityUserEntityByUserId($key);
  205. if (empty($userData->getUserId())) {
  206. Log::info('共富感恩奖发放:' . $key . '不是共富会员,不发放感恩奖');
  207. continue;
  208. }
  209. $parentId = $userData->getParentId();
  210. if ($parentId == 0) {
  211. Log::info('共富感恩奖发放:' . $key . '的上级是0,不发放感恩奖');
  212. continue;
  213. }
  214. // 给上级发积分,记录日志
  215. if ($parentId > 0) {
  216. if ($points <= 0) {
  217. Log::info('共富感恩奖发放:' . $key . '的收入是' . $value . ',奖励占比是' . $radio . ',积分是' . $value * $radio . '所以' . $parentId . '发放感恩奖');
  218. continue;
  219. }
  220. $parentData = $userRepository->getSharedProsperityUserEntityByUserId($parentId);
  221. // 记录日志
  222. $logDao->create([
  223. 'user_id' => $parentId,
  224. 'total' => $value,
  225. 'radio' => $radio,
  226. 'old' => $parentData->getPoints(),
  227. 'number' => $points,
  228. 'after' => $parentData->getPoints() + $points
  229. ]);
  230. // 发放积分
  231. $userRepository->updateByUserId($parentId, ['points' => ['inc', $points]]);
  232. }
  233. }
  234. Db::commit();
  235. return true;
  236. } catch (\Exception $e) {
  237. DB::rollback();
  238. throw new \Exception($e->getMessage());
  239. }
  240. }
  241. }