StoreOrderSuccessServices.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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\order;
  12. use app\dao\order\StoreOrderDao;
  13. use app\services\activity\lottery\LuckLotteryServices;
  14. use app\services\activity\combination\StorePinkServices;
  15. use app\services\BaseServices;
  16. use app\services\pay\PayServices;
  17. use app\services\user\UserServices;
  18. use app\services\product\product\StoreProductGiftGroupService;
  19. use app\services\user\UserBrokerageServices;
  20. use crmeb\exceptions\ApiException;
  21. /**
  22. * Class StoreOrderSuccessServices
  23. * @package app\services\order
  24. * @method getOne(array $where, ?string $field = '*', array $with = []) 获取去一条数据
  25. */
  26. class StoreOrderSuccessServices extends BaseServices
  27. {
  28. /**
  29. *
  30. * StoreOrderSuccessServices constructor.
  31. * @param StoreOrderDao $dao
  32. */
  33. public function __construct(StoreOrderDao $dao)
  34. {
  35. $this->dao = $dao;
  36. }
  37. /**
  38. * 0元支付
  39. * @param array $orderInfo
  40. * @param int $uid
  41. * @return bool
  42. * @throws \think\Exception
  43. * @throws \think\db\exception\DataNotFoundException
  44. * @throws \think\db\exception\ModelNotFoundException
  45. * @throws \think\exception\DbException
  46. */
  47. public function zeroYuanPayment(array $orderInfo, int $uid, string $payType = PayServices::YUE_PAY)
  48. {
  49. if ($orderInfo['paid']) {
  50. throw new ApiException(410265);
  51. }
  52. return $this->paySuccess($orderInfo, $payType);//余额支付成功
  53. }
  54. /**
  55. * 支付成功
  56. * @param array $orderInfo
  57. * @param string $paytype
  58. * @param array $other
  59. * @return bool
  60. * @throws \Psr\SimpleCache\InvalidArgumentException
  61. * @throws \think\db\exception\DataNotFoundException
  62. * @throws \think\db\exception\DbException
  63. * @throws \think\db\exception\ModelNotFoundException
  64. */
  65. public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
  66. {
  67. $updata = ['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()];
  68. $orderInfo['pay_time'] = $updata['pay_time'];
  69. $orderInfo['pay_type'] = $paytype;
  70. if ($other && isset($other['trade_no'])) {
  71. $updata['trade_no'] = $other['trade_no'];
  72. }
  73. /** @var StoreOrderCartInfoServices $orderInfoServices */
  74. $orderInfoServices = app()->make(StoreOrderCartInfoServices::class);
  75. $orderInfo['storeName'] = $orderInfoServices->getCarIdByProductTitle((int)$orderInfo['id']);
  76. $res1 = $this->dao->update($orderInfo['id'], $updata);
  77. $resPink = true;
  78. if ($orderInfo['combination_id'] && $res1 && !$orderInfo['refund_status']) {
  79. /** @var StorePinkServices $pinkServices */
  80. $pinkServices = app()->make(StorePinkServices::class);
  81. /** @var StoreOrderServices $orderServices */
  82. $orderServices = app()->make(StoreOrderServices::class);
  83. $resPink = $pinkServices->createPink($orderServices->tidyOrder($orderInfo, true));//创建拼团
  84. }
  85. //缓存抽奖次数 除过线下支付
  86. if (isset($orderInfo['pay_type']) && $orderInfo['pay_type'] != 'offline') {
  87. /** @var LuckLotteryServices $luckLotteryServices */
  88. $luckLotteryServices = app()->make(LuckLotteryServices::class);
  89. $luckLotteryServices->setCacheLotteryNum((int)$orderInfo['uid'], 'order');
  90. }
  91. $orderInfo['send_name'] = $orderInfo['real_name'];
  92. //订单支付成功后置事件
  93. event('OrderPaySuccessListener', [$orderInfo]);
  94. //用户推送消息事件
  95. event('NoticeListener', [$orderInfo, 'order_pay_success']);
  96. //支付成功给客服发送消息
  97. event('NoticeListener', [$orderInfo, 'admin_pay_success_code']);
  98. // 推送订单
  99. event('OutPushListener', ['order_pay_push', ['order_id' => (int)$orderInfo['id']]]);
  100. //自定义消息-订单支付成功
  101. $orderInfo['time'] = date('Y-m-d H:i:s');
  102. $orderInfo['phone'] = $orderInfo['user_phone'];
  103. event('CustomNoticeListener', [$orderInfo['uid'], $orderInfo, 'order_pay_success']);
  104. //自定义事件-订单支付
  105. event('CustomEventListener', ['order_pay', [
  106. 'uid' => $orderInfo['uid'],
  107. 'id' => (int)$orderInfo['id'],
  108. 'order_id' => $orderInfo['order_id'],
  109. 'real_name' => $orderInfo['real_name'],
  110. 'user_phone' => $orderInfo['user_phone'],
  111. 'user_address' => $orderInfo['user_address'],
  112. 'total_num' => $orderInfo['total_num'],
  113. 'pay_price' => $orderInfo['pay_price'],
  114. 'pay_postage' => $orderInfo['pay_postage'],
  115. 'deduction_price' => $orderInfo['deduction_price'],
  116. 'coupon_price' => $orderInfo['coupon_price'],
  117. 'store_name' => $orderInfo['storeName'],
  118. 'add_time' => date('Y-m-d H:i:s', $orderInfo['add_time']),
  119. ]]);
  120. // 获取购物车信息
  121. $orderCartInfo = $orderInfoServices->getCartColunm(
  122. ['oid' => $orderInfo['id']],
  123. 'cart_info',
  124. 'unique'
  125. );
  126. $orderInfo['cart_info'] = [];
  127. foreach ($orderCartInfo as $k => $v) {
  128. $cart_info = is_string($v) ? json_decode($v, true) : $v;
  129. $orderInfo['cart_info'][] = $cart_info;
  130. }
  131. if ($orderInfo['is_lb'] == 1) { //建立礼包推荐关系
  132. @file_put_contents('quanju.txt', $orderInfo['lb_spread_uid'] . "-礼包推荐人2\r\n", 8);
  133. self::createGiftRecommendationRelationship($orderInfo);
  134. self::giftRecommendationBonus($orderInfo);
  135. }
  136. // if ($orderInfo['is_lb'] == 1) { //赠送礼包推荐奖金
  137. // @file_put_contents('quanju.txt', $orderInfo['is_lb'] . "-礼包订单2\r\n", 8);
  138. //
  139. // }
  140. $res = $res1 && $resPink;
  141. return false !== $res;
  142. }
  143. // 创建礼包推荐关系
  144. public function createGiftRecommendationRelationship($order)
  145. {
  146. // @file_put_contents('quanju.txt', json_encode($order) . "-创建礼包推荐关系\r\n", 8);
  147. try {
  148. // 获取用户信息
  149. $userServices = app()->make(UserServices::class);
  150. $user = $userServices->getUserInfo($order['uid']);
  151. @file_put_contents('quanju.txt', $user['spread_uid'] . "-创建礼包推荐关系\r\n", 8);
  152. if ($user['spread_uid'] > 0) {
  153. // 如果用户有推广人,说明是通过推广链接支付的,需要创建礼包推荐关系,关系表是store_product_gift_group,需要保存product_id,uid,group_pid(小组上级),pid(真直推上级),fake_pid(假直推上级(直推上级的下级小组满人下放下来的人)),一个商品加一个pid推荐上级会形成一个小组,第一个加进小组的会是第二个加入的小组上级(group_pid),当一个小组满10人后,就会让第十人作为fake_pid直推上级建立新的10人小组,但pid还是真正的直推上级
  154. // 获取商品ID
  155. $product_id = $order['cart_info'][0]['product_id'] ?? 0;
  156. if (!$product_id) return false;
  157. // 获取推广人UID
  158. $spread_uid = $user['spread_uid'];
  159. // 获取礼包服务
  160. $giftGroupService = app()->make(StoreProductGiftGroupService::class);
  161. // 检查是否已有该商品的推荐关系
  162. $existRelation = $giftGroupService->getOne([
  163. 'product_id' => $product_id,
  164. 'uid' => $order['uid']
  165. ]);
  166. if ($existRelation) return true;
  167. // 检查推广人是否是自己的下级团队成员(防止循环推荐)
  168. if ($this->isSubordinate($order['uid'], $spread_uid, $product_id, $giftGroupService)) {
  169. return false;
  170. }
  171. // 获取直推上级的推荐关系
  172. $parentRelation = $giftGroupService->getOne([
  173. 'product_id' => $product_id,
  174. 'uid' => $spread_uid
  175. ]);
  176. // 设置关系数据
  177. $data = [
  178. 'product_id' => $product_id,
  179. 'uid' => $order['uid'],
  180. 'pid' => $spread_uid, // 真直推上级
  181. 'create_time' => time()
  182. ];
  183. // 处理小组关系
  184. // 获取小组人数上限配置
  185. $groupMaxNum = sys_config('gift_group_num', 10);
  186. // 判断直推上级在该商品下是否有下级
  187. $hasSubordinate = $giftGroupService->getOne([
  188. 'product_id' => $product_id,
  189. 'pid' => $spread_uid
  190. ]);
  191. if ($hasSubordinate) {
  192. // 直推上级已有下级,获取所有下级
  193. $allSubordinates = $giftGroupService->getList([
  194. 'product_id' => $product_id,
  195. 'pid' => $spread_uid
  196. ], '*', 0, 0, 'create_time ASC');
  197. // 获取最后一个下级的group_pid来判断小组是否满人
  198. $lastMember = $allSubordinates[count($allSubordinates) - 1];
  199. $lastGroupPid = $lastMember['group_pid'];
  200. // 统计小组人数:从最后一个成员开始,沿group_pid向上追溯到根节点
  201. // 然后统计所有pid=spread_uid且group_pid在链条上的成员
  202. $groupChain = [];
  203. $currentGroupPid = $lastGroupPid;
  204. // 追溯group_pid链条
  205. while ($currentGroupPid > 0) {
  206. $groupChain[] = $currentGroupPid;
  207. @file_put_contents('quanju4.txt', $currentGroupPid . "-group_pid链条节点\r\n", 8);
  208. // 查找这个group_pid对应的成员
  209. $chainMember = $giftGroupService->getOne([
  210. 'product_id' => $product_id,
  211. 'uid' => $currentGroupPid
  212. ]);
  213. if ($chainMember) {
  214. $currentGroupPid = $chainMember['group_pid'];
  215. @file_put_contents('quanju4.txt', $chainMember['group_pid'] . "-下一节点group_pid\r\n", 8);
  216. } else {
  217. break;
  218. }
  219. }
  220. // 统计小组人数:pid=spread_uid 且 group_pid 在链条中或为0
  221. $groupCount = 0;
  222. foreach ($allSubordinates as $sub) {
  223. if (in_array($sub['group_pid'], $groupChain) || $sub['group_pid'] == 0) {
  224. $groupCount++;
  225. }
  226. }
  227. $isGroupFull = $groupCount >= $groupMaxNum;
  228. @file_put_contents('quanju4.txt', $groupCount . "-小组人数\r\n", 8);
  229. @file_put_contents('quanju4.txt', $groupMaxNum . "-系统设置人数\r\n", 8);
  230. @file_put_contents('quanju4.txt', $lastGroupPid . "-最后一个人的group_pid\r\n", 8);
  231. @file_put_contents('quanju4.txt', json_encode($groupChain) . "-group_pid链条\r\n", 8);
  232. @file_put_contents('quanju4.txt', ($isGroupFull ? '小组已满' : '小组未满') . "-小组状态\r\n", 8);
  233. @file_put_contents('quanju4.txt', end($groupChain) . "-小组最后一人uid(end groupChain)\r\n", 8);
  234. // 判断小组是否满人
  235. if ($isGroupFull) {
  236. // 小组满人,需要滑落到小组最后一人的直推下级小组
  237. // 小组最后一人应该是按create_time排序的最后一人,而不是group_pid链条的最后一人
  238. $lastGroupMemberUid = end($allSubordinates)['uid'];
  239. @file_put_contents('quanju4.txt', $lastGroupMemberUid . "-小组最后一人的uid(按create_time排序)\r\n", 8);
  240. // 查找小组最后一人的直推下级小组(group_pid等于最后一人的uid)
  241. $lastGroupSubordinates = $giftGroupService->getList([
  242. 'product_id' => $product_id,
  243. 'group_pid' => $lastGroupMemberUid
  244. ], '*', 0, 0, 'create_time ASC');
  245. @file_put_contents('quanju4.txt', count($lastGroupSubordinates) . "-最后一人的直推下级小组人数\r\n", 8);
  246. if (count($lastGroupSubordinates) < $groupMaxNum) {
  247. // 最后一人的直推下级小组未满,新成员加入该小组
  248. if (count($lastGroupSubordinates) > 0) {
  249. // 该小组已有成员,新成员的group_pid是该小组的最后一人
  250. $lastSubGroupMember = end($lastGroupSubordinates);
  251. $data['group_pid'] = $lastSubGroupMember['uid'];
  252. // 新成员的fake_pid保持为最后一人的uid
  253. $data['fake_pid'] = $lastGroupMemberUid;
  254. @file_put_contents('quanju4.txt', $lastSubGroupMember['uid'] . "-小组的最后一人(新成员group_pid)\r\n", 8);
  255. } else {
  256. // 该小组没有成员,新成员成为第一人
  257. $data['group_pid'] = 0;
  258. $data['fake_pid'] = $lastGroupMemberUid;
  259. @file_put_contents('quanju4.txt', '最后一人的直推下级小组没有成员,新成员成为第一人\r\n', 8);
  260. }
  261. } else {
  262. // 最后一人的直推下级小组也满了,新成员需要新建小组
  263. $data['group_pid'] = 0;
  264. $data['fake_pid'] = $lastGroupMemberUid;
  265. @file_put_contents('quanju4.txt', '最后一人的直推下级小组已满,新成员新建小组\r\n', 8);
  266. }
  267. } else {
  268. // 小组未满,新成员应该加入当前小组
  269. // 新成员的group_pid是最后一个下级的uid(成为小组长)
  270. $data['group_pid'] = $lastMember['uid'];
  271. $data['fake_pid'] = $spread_uid;
  272. }
  273. } else {
  274. // 直推上级没有下级,这是该推广人的第一个下级,建立新小组
  275. $data['group_pid'] = 0;
  276. $data['fake_pid'] = $spread_uid;
  277. }
  278. // 保存推荐关系
  279. return $giftGroupService->save($data);
  280. }
  281. return false;
  282. } catch (\Exception $e) {
  283. @file_put_contents('quanju4.txt', $e->getMessage() . "-创建订单报错内容\r\n", 8);
  284. @file_put_contents('quanju4.txt', $e->getFile() . "-文件\r\n", 8);
  285. @file_put_contents('quanju4.txt', $e->getLine() . "-位置\r\n", 8);
  286. @file_put_contents('quanju4.txt', $e->getTraceAsString() . "-堆栈\r\n", 8);
  287. }
  288. }
  289. // 礼包上级分红
  290. public function giftRecommendationBonus($order)
  291. {
  292. try {
  293. @file_put_contents('quanju.txt', json_encode($order) . "-礼包上级分红\r\n", 8);
  294. // 获取礼包服务
  295. $giftGroupService = app()->make(StoreProductGiftGroupService::class);
  296. $userServices = app()->make(UserServices::class);
  297. // 检查 cart_info 是否存在且非空
  298. @file_put_contents('quanju4.txt', '开始检查cart_info' . "\r\n", 8);
  299. if (!isset($order['cart_info']) || empty($order['cart_info'])) {
  300. @file_put_contents('quanju4.txt', 'cart_info不存在或为空' . "\r\n", 8);
  301. return false;
  302. }
  303. // 获取商品ID和商品价格作为佣金计算基数
  304. $product_id = $order['cart_info'][0]['product_id'] ?? 0;
  305. $brokerage_price = $order['cart_info'][0]['truePrice'] ?? 0;
  306. @file_put_contents('quanju4.txt', 'product_id=' . $product_id . ', brokerage_price=' . $brokerage_price . "\r\n", 8);
  307. if (!$product_id || !$brokerage_price) {
  308. @file_put_contents('quanju4.txt', 'product_id或brokerage_price为0,返回false' . "\r\n", 8);
  309. return false;
  310. }
  311. @file_put_contents('quanju4.txt', $product_id . "-商品id\r\n", 8);
  312. // 获取用户的推荐关系
  313. $userRelation = $giftGroupService->getOne([
  314. 'product_id' => $product_id,
  315. 'uid' => $order['uid']
  316. ]);
  317. if (!$userRelation) return false;
  318. $userInfo = $userServices->getOne(['uid' => $order['uid']]);
  319. // 获取佣金服务(一次性创建,复用)
  320. /** @var UserBrokerageServices $userBrokerageServices */
  321. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  322. //冻结时间
  323. $frozenTime = time() + intval(sys_config('extract_time')) * 86400;
  324. // 直推上级分成(全部给真直推上级)
  325. $directBrokerage = $brokerage_price * (sys_config('gift_direct_referral', 10) / 100);
  326. @file_put_contents('quanju4.txt', json_encode($userRelation) . "-礼包推荐关系表\r\n", 8);
  327. // 直推奖全部给真直推上级
  328. $pid_brokerage = $userServices->getOne(['uid' => $userRelation['pid']]);
  329. $userServices->bcInc($userRelation['pid'], 'brokerage_price', $directBrokerage, 'uid');
  330. @file_put_contents('quanju4.txt', $directBrokerage . "-直推奖励\r\n", 8);
  331. $balance = bcadd($pid_brokerage['brokerage_price'], $directBrokerage, 2);
  332. $userBrokerageServices->income('get_direct_referral_brokerage', $userRelation['pid'], [
  333. 'nickname' => $userInfo['nickname'],
  334. 'pay_price' => floatval($order['pay_price']),
  335. 'number' => $directBrokerage,
  336. 'frozen_time' => $frozenTime
  337. ], $balance, $order['id']);
  338. // 见点奖处理
  339. $spotBrokerage = $brokerage_price * (sys_config('gift_spot_bonus', 2.5) / 100);
  340. // 1. 向上查找:先找小组上级,没有就找假直推上级
  341. $spotUpLimit = sys_config('gift_spot_bonus_up', 15);
  342. $currentUid = $order['uid']; // 从当前用户开始
  343. $currentRelation = $userRelation; // 当前用户的推荐关系
  344. $originalPid = $userRelation['pid']; // 记录原始用户的真直推上级
  345. $splitRatio = sys_config('gift_fake_pid_split_ratio', 50); // 假直推上级分成比例(给真直推上级的比例)
  346. for ($i = 0; $i < $spotUpLimit; $i++) {
  347. $nextUid = null;
  348. // 优先查找小组上级
  349. if (!empty($currentRelation['group_pid'])) {
  350. $nextUid = $currentRelation['group_pid'];
  351. } else if (!empty($currentRelation['fake_pid'])) {
  352. // 没有小组上级,查找假直推上级
  353. $nextUid = $currentRelation['fake_pid'];
  354. }
  355. // 找不到上级,退出循环
  356. if (!$nextUid) break;
  357. // 判断是否需要分成(如果上级是fake_pid且不等于原始用户的pid)
  358. $needSplit = false;
  359. if (!empty($currentRelation['fake_pid']) && $nextUid == $currentRelation['fake_pid'] && $currentRelation['fake_pid'] != $originalPid) {
  360. $needSplit = true;
  361. }
  362. if ($needSplit) {
  363. // 需要分成:给真直推上级和假直推上级分别发放
  364. $splitAmount = $spotBrokerage * ($splitRatio / 100); // 给真直推上级的份额
  365. $remainderAmount = $spotBrokerage - $splitAmount; // 给假直推上级的份额
  366. // 给真直推上级发放
  367. $pidBrokerage = $userServices->getOne(['uid' => $originalPid]);
  368. $userServices->bcInc($originalPid, 'brokerage_price', $splitAmount, 'uid');
  369. $balance = bcadd($pidBrokerage['brokerage_price'], $splitAmount, 2);
  370. $userBrokerageServices->income('get_spot_brokerage', $originalPid, [
  371. 'nickname' => $userInfo['nickname'],
  372. 'pay_price' => floatval($order['pay_price']),
  373. 'number' => $splitAmount,
  374. 'frozen_time' => $frozenTime
  375. ], $balance, $order['id']);
  376. @file_put_contents('quanju4.txt', '向上发放见点奖给真直推上级: uid=' . $originalPid . ', 金额=' . $splitAmount . "\r\n", 8);
  377. // 给假直推上级发放
  378. $currentBrokerage = $userServices->getOne(['uid' => $nextUid]);
  379. $userServices->bcInc($nextUid, 'brokerage_price', $remainderAmount, 'uid');
  380. $balance = bcadd($currentBrokerage['brokerage_price'], $remainderAmount, 2);
  381. $userBrokerageServices->income('get_spot_brokerage', $nextUid, [
  382. 'nickname' => $userInfo['nickname'],
  383. 'pay_price' => floatval($order['pay_price']),
  384. 'number' => $remainderAmount,
  385. 'frozen_time' => $frozenTime
  386. ], $balance, $order['id']);
  387. @file_put_contents('quanju4.txt', '向上发放见点奖给假直推上级: uid=' . $nextUid . ', 金额=' . $remainderAmount . "\r\n", 8);
  388. } else {
  389. // 不需要分成:全部给上级
  390. $currentBrokerage = $userServices->getOne(['uid' => $nextUid]);
  391. $userServices->bcInc($nextUid, 'brokerage_price', $spotBrokerage, 'uid');
  392. $balance = bcadd($currentBrokerage['brokerage_price'], $spotBrokerage);
  393. $userBrokerageServices->income('get_spot_brokerage', $nextUid, [
  394. 'nickname' => $userInfo['nickname'],
  395. 'pay_price' => floatval($order['pay_price']),
  396. 'number' => $spotBrokerage,
  397. 'frozen_time' => $frozenTime
  398. ], $balance, $order['id']);
  399. @file_put_contents('quanju4.txt', '向上发放见点奖: uid=' . $nextUid . ', 金额=' . $spotBrokerage . "\r\n", 8);
  400. }
  401. // 查找下一个上级的推荐关系
  402. $currentRelation = $giftGroupService->getOne([
  403. 'product_id' => $product_id,
  404. 'uid' => $nextUid
  405. ]);
  406. // 如果找不到推荐关系,退出循环
  407. if (!$currentRelation) break;
  408. }
  409. // 2. 向下查找:先找直推下级,不够再找同组下级
  410. $spotDownLimit = sys_config('gift_spot_bonus_down', 15);
  411. $totalDownSpots = 0;
  412. // 2.1 先找直推下级
  413. $directSubordinates = $giftGroupService->getList([
  414. 'product_id' => $product_id,
  415. 'pid' => $order['uid']
  416. ], '*', 0, $spotDownLimit, 'create_time asc');
  417. foreach ($directSubordinates as $subordinate) {
  418. $subBrokerage = $userServices->getOne(['uid' => $subordinate['uid']]);
  419. $userServices->bcInc($subordinate['uid'], 'brokerage_price', $spotBrokerage, 'uid');
  420. $balance = bcadd($subBrokerage['brokerage_price'], $spotBrokerage);
  421. $userBrokerageServices->income('get_spot_brokerage', $subordinate['uid'], [
  422. 'nickname' => $userInfo['nickname'],
  423. 'pay_price' => floatval($order['pay_price']),
  424. 'number' => $spotBrokerage,
  425. 'frozen_time' => $frozenTime
  426. ], $balance, $order['id']);
  427. @file_put_contents('quanju4.txt', '向下发放见点奖给直推下级: uid=' . $subordinate['uid'] . ', 金额=' . $spotBrokerage . "\r\n", 8);
  428. $totalDownSpots++;
  429. }
  430. // 2.2 如果直推下级不够,找同组下级
  431. if ($totalDownSpots < $spotDownLimit) {
  432. // 获取所有pid与当前用户pid相同的同级用户
  433. $samePidMembers = $giftGroupService->getList([
  434. 'product_id' => $product_id,
  435. 'pid' => $userRelation['pid']
  436. ], '*', 0, 0, 'create_time asc');
  437. // 找到当前用户在同级用户中的位置
  438. $currentIndex = null;
  439. foreach ($samePidMembers as $index => $member) {
  440. if ($member['uid'] == $order['uid']) {
  441. $currentIndex = $index;
  442. break;
  443. }
  444. }
  445. // 从当前用户之后的同级用户开始,查找同组下级
  446. if ($currentIndex !== null) {
  447. for ($i = $currentIndex + 1; $i < count($samePidMembers) && $totalDownSpots < $spotDownLimit; $i++) {
  448. $member = $samePidMembers[$i];
  449. // 检查这个同级用户的group_pid层级是否在当前用户或其下级中
  450. $isGroupSubordinate = $this->isGroupSubordinate($order['uid'], $member['group_pid'], $product_id, $giftGroupService);
  451. if ($isGroupSubordinate) {
  452. $memberBrokerage = $userServices->getOne(['uid' => $member['uid']]);
  453. $userServices->bcInc($member['uid'], 'brokerage_price', $spotBrokerage, 'uid');
  454. $balance = bcadd($memberBrokerage['brokerage_price'], $spotBrokerage);
  455. $userBrokerageServices->income('get_spot_brokerage', $member['uid'], [
  456. 'nickname' => $userInfo['nickname'],
  457. 'pay_price' => floatval($order['pay_price']),
  458. 'number' => $spotBrokerage,
  459. 'frozen_time' => $frozenTime
  460. ], $balance, $order['id']);
  461. @file_put_contents('quanju4.txt', '向下发放见点奖给同组下级: uid=' . $member['uid'] . ', 金额=' . $spotBrokerage . "\r\n", 8);
  462. $totalDownSpots++;
  463. }
  464. }
  465. }
  466. }
  467. return true;
  468. } catch (\Exception $e) {
  469. @file_put_contents('quanju4.txt', $e->getMessage() . "-上级分红报错内容\r\n", 8);
  470. @file_put_contents('quanju4.txt', $e->getFile() . "-文件\r\n", 8);
  471. @file_put_contents('quanju4.txt', $e->getLine() . "-位置\r\n", 8);
  472. @file_put_contents('quanju4.txt', $e->getTraceAsString() . "-堆栈\r\n", 8);
  473. }
  474. }
  475. /**
  476. * 检查某个用户是否是另一个用户的小组下级(通过group_pid层级关系)
  477. * @param int $baseUid 基准用户uid
  478. * @param int $groupPid 要检查的group_pid
  479. * @param int $productId 商品ID
  480. * @param StoreProductGiftGroupService $giftGroupService 礼包服务
  481. * @param array $checked 已检查的用户(防止循环)
  482. * @return bool 如果是小组下级返回true,否则返回false
  483. */
  484. protected function isGroupSubordinate($baseUid, $groupPid, $productId, $giftGroupService, $checked = [])
  485. {
  486. // 如果已经检查过这个groupPid,跳过(防止循环)
  487. if (isset($checked[$groupPid])) {
  488. return false;
  489. }
  490. $checked[$groupPid] = true;
  491. // 如果groupPid是0,说明没有小组关系
  492. if (empty($groupPid)) {
  493. return false;
  494. }
  495. // 如果groupPid等于基准用户,说明是直接下级
  496. if ($groupPid == $baseUid) {
  497. return true;
  498. }
  499. // 递归检查group_pid是否是基准用户的下级
  500. $member = $giftGroupService->getOne([
  501. 'product_id' => $productId,
  502. 'uid' => $groupPid
  503. ]);
  504. if ($member) {
  505. // 继续检查这个用户的group_pid
  506. return $this->isGroupSubordinate($baseUid, $member['group_pid'], $productId, $giftGroupService, $checked);
  507. }
  508. return false;
  509. }
  510. /**
  511. * 检查某个用户是否是另一个用户的下级团队成员
  512. * @param int $uid 当前用户
  513. * @param int $targetUid 要检查的目标用户
  514. * @param int $productId 商品ID
  515. * @param StoreProductGiftGroupService $giftGroupService 礼包服务
  516. * @param array $checked 已检查的用户(防止循环)
  517. * @return bool 如果是下级返回true,否则返回false
  518. */
  519. protected function isSubordinate($uid, $targetUid, $productId, $giftGroupService, $checked = [])
  520. {
  521. // 如果已经检查过这个用户,跳过(防止循环)
  522. if (isset($checked[$uid])) {
  523. return false;
  524. }
  525. $checked[$uid] = true;
  526. // 查找该用户的所有直推下级
  527. $subordinates = $giftGroupService->getList([
  528. 'product_id' => $productId,
  529. 'pid' => $uid
  530. ], 'uid', 0, 0, 'create_time asc');
  531. // 检查目标用户是否在直推下级中
  532. foreach ($subordinates as $sub) {
  533. if ($sub['uid'] == $targetUid) {
  534. return true; // 找到了,是下级
  535. }
  536. }
  537. // 递归检查每个下级的下级
  538. foreach ($subordinates as $sub) {
  539. if ($this->isSubordinate($sub['uid'], $targetUid, $productId, $giftGroupService, $checked)) {
  540. return true; // 在下级的下级中找到了
  541. }
  542. }
  543. return false; // 没找到,不是下级
  544. }
  545. }