StoreOrderSuccessServices.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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\adminapi\controller\v1\marketing\StoreCouponUser;
  13. use app\dao\order\StoreOrderDao;
  14. use app\model\user\User;
  15. use app\services\activity\coupon\StoreCouponIssueServices;
  16. use app\services\activity\lottery\LuckLotteryServices;
  17. use app\services\activity\combination\StorePinkServices;
  18. use app\services\BaseServices;
  19. use app\services\pay\PayServices;
  20. use app\services\user\UserBrokerageServices;
  21. use app\services\user\UserServices;
  22. use crmeb\exceptions\ApiException;
  23. /**
  24. * Class StoreOrderSuccessServices
  25. * @package app\services\order
  26. * @method getOne(array $where, ?string $field = '*', array $with = []) 获取去一条数据
  27. */
  28. class StoreOrderSuccessServices extends BaseServices
  29. {
  30. /**
  31. *
  32. * StoreOrderSuccessServices constructor.
  33. * @param StoreOrderDao $dao
  34. */
  35. public function __construct(StoreOrderDao $dao)
  36. {
  37. $this->dao = $dao;
  38. }
  39. /**
  40. * 0元支付
  41. * @param array $orderInfo
  42. * @param int $uid
  43. * @return bool
  44. * @throws \think\Exception
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\ModelNotFoundException
  47. * @throws \think\exception\DbException
  48. */
  49. public function zeroYuanPayment(array $orderInfo, int $uid, string $payType = PayServices::YUE_PAY)
  50. {
  51. if ($orderInfo['paid']) {
  52. throw new ApiException(410265);
  53. }
  54. return $this->paySuccess($orderInfo, $payType);//余额支付成功
  55. }
  56. /**
  57. * 支付成功
  58. * @param array $orderInfo
  59. * @param string $paytype
  60. * @param array $other
  61. * @return bool
  62. * @throws \Psr\SimpleCache\InvalidArgumentException
  63. * @throws \think\db\exception\DataNotFoundException
  64. * @throws \think\db\exception\DbException
  65. * @throws \think\db\exception\ModelNotFoundException
  66. */
  67. public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
  68. {
  69. $updata = ['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()];
  70. $orderInfo['pay_time'] = $updata['pay_time'];
  71. $orderInfo['pay_type'] = $paytype;
  72. if ($other && isset($other['trade_no'])) {
  73. $updata['trade_no'] = $other['trade_no'];
  74. }
  75. /** @var StoreOrderCartInfoServices $orderInfoServices */
  76. $orderInfoServices = app()->make(StoreOrderCartInfoServices::class);
  77. $orderInfo['storeName'] = $orderInfoServices->getCarIdByProductTitle((int)$orderInfo['id']);
  78. $res1 = $this->dao->update($orderInfo['id'], $updata);
  79. $resPink = true;
  80. if ($orderInfo['combination_id'] && $res1 && !$orderInfo['refund_status']) {
  81. /** @var StorePinkServices $pinkServices */
  82. $pinkServices = app()->make(StorePinkServices::class);
  83. /** @var StoreOrderServices $orderServices */
  84. $orderServices = app()->make(StoreOrderServices::class);
  85. $resPink = $pinkServices->createPink($orderServices->tidyOrder($orderInfo, true));//创建拼团
  86. }
  87. //缓存抽奖次数 除过线下支付
  88. if (isset($orderInfo['pay_type']) && $orderInfo['pay_type'] != 'offline') {
  89. /** @var LuckLotteryServices $luckLotteryServices */
  90. $luckLotteryServices = app()->make(LuckLotteryServices::class);
  91. $luckLotteryServices->setCacheLotteryNum((int)$orderInfo['uid'], 'order');
  92. }
  93. $orderInfo['send_name'] = $orderInfo['real_name'];
  94. //订单支付成功后置事件
  95. event('OrderPaySuccessListener', [$orderInfo]);
  96. //用户推送消息事件
  97. event('NoticeListener', [$orderInfo, 'order_pay_success']);
  98. //支付成功给客服发送消息
  99. event('NoticeListener', [$orderInfo, 'admin_pay_success_code']);
  100. // 推送订单
  101. event('OutPushListener', ['order_pay_push', ['order_id' => (int)$orderInfo['id']]]);
  102. // 小程序订单管理 (自提商品)
  103. if ($orderInfo['shipping_type'] == 2) {
  104. event('OrderShipping', ['product', $orderInfo, 4, '', '']);
  105. }
  106. $res = $res1 && $resPink;
  107. if ($orderInfo['order_type']==1){ //礼包商品订单赠送复购商品优惠卷
  108. $grant_id = sys_config('repeat_voucher',0);
  109. $grant_num = sys_config('repeat_voucher_num',0);
  110. if ($grant_id>0 && $grant_num>0){
  111. for ($i=0;$i<$grant_num;$i++){
  112. self::grantUser($grant_id,$orderInfo['uid']);
  113. }
  114. }
  115. }
  116. $spread_id = User::where('uid',$orderInfo['uid'])->value('spread_uid');
  117. if ($spread_id>0){
  118. self::spreadReward($spread_id,$orderInfo);
  119. }
  120. return false !== $res;
  121. }
  122. /**
  123. * 发放优惠券到指定个人
  124. * @return mixed
  125. */
  126. public function grantUser($id,$uid)
  127. {
  128. $data['id'] = $id;
  129. $data['uid'] = $uid;
  130. if (!$data['id']) return app('json')->fail(100100);
  131. /** @var StoreCouponIssueServices $issueService */
  132. $issueService = app()->make(StoreCouponIssueServices::class);
  133. $coupon = $issueService->get($data['id']);
  134. if (!$coupon) {
  135. return app('json')->fail(100026);
  136. } else {
  137. $coupon = $coupon->toArray();
  138. }
  139. $user = explode(',', $data['uid']);
  140. $issueService->setCoupon($coupon, $user);
  141. return true;
  142. }
  143. // 发放分销奖励()
  144. public function spreadReward($spread_uid, $orderInfo){
  145. try {
  146. // 获取上级的分销等级
  147. $agent_level = User::where('uid', $spread_uid)->value('agent_level');
  148. if (!$agent_level) {
  149. return false;
  150. }
  151. // 获取分销等级详细信息
  152. $agentLevelInfo = \app\model\agent\AgentLevel::where('id', $agent_level)->find();
  153. if (!$agentLevelInfo) {
  154. return false;
  155. }
  156. $agentLevelInfo = $agentLevelInfo->toArray();
  157. // 发放优惠券奖励
  158. if ($agentLevelInfo['free_issue'] > 0) {
  159. $this->grantUser($agentLevelInfo['free_issue'], $spread_uid);
  160. }
  161. // 发放佣金奖励
  162. if ($agentLevelInfo['spread_brokerage'] > 0) {
  163. // 计算佣金金额:订单价格 * spread_brokerage / 100
  164. $brokerageAmount = bcmul((string)$orderInfo['total_price'], (string)($agentLevelInfo['spread_brokerage'] / 100), 2);
  165. if ($brokerageAmount > 0) {
  166. /** @var UserServices $userServices */
  167. $userServices = app()->make(UserServices::class);
  168. /** @var UserBrokerageServices $userBrokerageServices */
  169. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  170. $balance = $userServices->value(['uid' => $spread_uid], 'brokerage_price');
  171. $nickname = User::where('uid',$orderInfo['uid'])->value('nickname');
  172. $userBrokerageServices->income('get_brokerage', $spread_uid, [
  173. 'nickname' => $nickname,
  174. 'pay_price' => $orderInfo['total_price'],
  175. 'number' => $brokerageAmount,
  176. ], bcadd((string)$balance, (string)$brokerageAmount, 2), $orderInfo['id'] ?? 0);
  177. $userServices->bcInc($spread_uid, 'brokerage_price', $brokerageAmount, 'uid');
  178. // 发放平级奖励
  179. $this->issueSameLevelReward($spread_uid, $brokerageAmount);
  180. }
  181. }
  182. return true;
  183. } catch (\Exception $e) {
  184. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-spreadReward报错内容\r\n", 8);
  185. @file_put_contents("quanju.txt", json_encode($e->getLine())."-spreadReward报错位置\r\n", 8);
  186. @file_put_contents("quanju.txt", json_encode($e->getFile())."-spreadReward报错文件\r\n", 8);
  187. throw $e;
  188. }
  189. }
  190. /**
  191. * 发放核销订单线路奖励 定时任务
  192. * 针对分销等级为4的用户,统计其直推下级团队中门店核销订单数量
  193. * 当两条线都达到200单时,奖励verific_reward金额
  194. * 当第三条线达到200单时,再奖励more_reward金额
  195. * 第四条及以后达到200单,每次奖励more_reward金额
  196. * @param int $spread_uid 分销等级为4的用户UID
  197. * @return bool
  198. */
  199. public function verifyLineReward($spread_uid){
  200. try {
  201. // 获取用户的分销等级ID
  202. $agent_level_id = User::where('uid', $spread_uid)->value('agent_level');
  203. if (!$agent_level_id) {
  204. return false;
  205. }
  206. // 获取分销等级的grade字段
  207. $agentLevelInfo = \app\model\agent\AgentLevel::where('id', $agent_level_id)->find();
  208. if (!$agentLevelInfo) {
  209. return false;
  210. }
  211. $agentGrade = $agentLevelInfo->grade;
  212. // 只处理分销等级为4的用户
  213. if ($agentGrade != 4) {
  214. return false;
  215. }
  216. // 获取该用户的所有直推下级
  217. $directUsers = User::where('spread_uid', $spread_uid)
  218. ->column('uid');
  219. if (empty($directUsers)) {
  220. return false;
  221. }
  222. // 收集所有需要统计的用户(包括直推下级及其所有下级)
  223. $allLineUsers = [];
  224. foreach ($directUsers as $directUid) {
  225. $lineUsers = $this->getAllTeamUsers($directUid);
  226. $allLineUsers[] = $lineUsers;
  227. }
  228. if (empty($allLineUsers)) {
  229. return false;
  230. }
  231. // 统计每条线的核销订单数量
  232. $lineVerifyCounts = [];
  233. foreach ($allLineUsers as $lineUsers) {
  234. if (empty($lineUsers)) {
  235. $lineVerifyCounts[] = 0;
  236. continue;
  237. }
  238. // 查询这些用户拥有的门店的核销订单总量
  239. $totalVerifyNum = \app\model\system\store\SystemStore::whereIn('uid', $lineUsers)
  240. ->sum('verify_num');
  241. $lineVerifyCounts[] = (int)$totalVerifyNum;
  242. }
  243. // 统计达到200单的线路数量
  244. $qualifiedLines = 0;
  245. foreach ($lineVerifyCounts as $count) {
  246. if ($count >= 200) {
  247. $qualifiedLines++;
  248. }
  249. }
  250. if ($qualifiedLines < 2) {
  251. return false;
  252. }
  253. // 获取奖励配置
  254. $verificReward = sys_config('verific_reward', 0);
  255. $moreReward = sys_config('more_reward', 0);
  256. if ($verificReward <= 0 && $moreReward <= 0) {
  257. return false;
  258. }
  259. // 查询用户已发放的奖励记录
  260. $rewardRecords = \app\model\user\UserBrokerage::where('uid', $spread_uid)
  261. ->where('type', 'get_brokerage')
  262. ->where('title', 'like', '%核销线路奖励%')
  263. ->column('id', 'number');
  264. // 计算应该发放的奖励
  265. $verificRewardCount = 0; // verific_reward应该发放的次数(最多1次)
  266. $moreRewardCount = 0; // more_reward应该发放的次数
  267. if ($qualifiedLines >= 2) {
  268. $verificRewardCount = 1;
  269. // 超过2条线,每多一条线发放一次more_reward
  270. $moreRewardCount = $qualifiedLines - 2;
  271. }
  272. // 查询已发放的verific_reward次数
  273. $issuedVerificCount = 0;
  274. foreach ($rewardRecords as $amount => $id) {
  275. if (abs($amount - $verificReward) < 0.01) {
  276. $issuedVerificCount++;
  277. }
  278. }
  279. // 查询已发放的more_reward次数
  280. $issuedMoreCount = 0;
  281. foreach ($rewardRecords as $amount => $id) {
  282. if (abs($amount - $moreReward) < 0.01) {
  283. $issuedMoreCount++;
  284. }
  285. }
  286. // 判断是否需要发放奖励
  287. $needVerificReward = $verificRewardCount > $issuedVerificCount;
  288. $needMoreReward = $moreRewardCount > $issuedMoreCount;
  289. if (!$needVerificReward && !$needMoreReward) {
  290. return false;
  291. }
  292. /** @var UserServices $userServices */
  293. $userServices = app()->make(UserServices::class);
  294. /** @var UserBrokerageServices $userBrokerageServices */
  295. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  296. $balance = $userServices->value(['uid' => $spread_uid], 'brokerage_price');
  297. // 发放verific_reward(两条线达标奖励)
  298. if ($needVerificReward && $verificReward > 0) {
  299. $userBrokerageServices->income('line_two_reward', $spread_uid, [
  300. // 'pay_price' => 0,
  301. 'number' => $verificReward,
  302. ], bcadd((string)$balance, (string)$verificReward, 2), 0);
  303. $userServices->bcInc($spread_uid, 'brokerage_price', $verificReward, 'uid');
  304. $balance = bcadd((string)$balance, (string)$verificReward, 2);
  305. // 发放平级奖励
  306. $this->issueSameLevelReward($spread_uid, $verificReward);
  307. }
  308. // 发放more_reward(第三条及以上线达标,可能多次)
  309. if ($needMoreReward && $moreReward > 0) {
  310. $needIssueMoreCount = $moreRewardCount - $issuedMoreCount;
  311. for ($i = 0; $i < $needIssueMoreCount; $i++) {
  312. $userBrokerageServices->income('line_more_reward', $spread_uid, [
  313. // 'pay_price' => 0,
  314. 'number' => $moreReward,
  315. ], bcadd((string)$balance, (string)$moreReward, 2), 0);
  316. $userServices->bcInc($spread_uid, 'brokerage_price', $moreReward, 'uid');
  317. $balance = bcadd((string)$balance, (string)$moreReward, 2);
  318. // 发放平级奖励
  319. $this->issueSameLevelReward($spread_uid, $moreReward);
  320. }
  321. }
  322. return true;
  323. } catch (\Exception $e) {
  324. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-verifyLineReward报错内容\r\n", 8);
  325. @file_put_contents("quanju.txt", json_encode($e->getLine())."-verifyLineReward报错位置\r\n", 8);
  326. @file_put_contents("quanju.txt", json_encode($e->getFile())."-verifyLineReward报错文件\r\n", 8);
  327. throw $e;
  328. }
  329. }
  330. /**
  331. * 获取用户的所有下级(递归查询团队)
  332. * @param int $uid 用户UID
  333. * @return array 所有下级UID数组
  334. */
  335. private function getAllTeamUsers($uid){
  336. $allUsers = [];
  337. $this->getTeamUsersRecursive($uid, $allUsers);
  338. return $allUsers;
  339. }
  340. /**
  341. * 递归获取用户的所有下级
  342. * @param int $uid 当前用户UID
  343. * @param array &$allUsers 已收集的用户数组(引用传递)
  344. */
  345. private function getTeamUsersRecursive($uid, &$allUsers){
  346. // 查询该用户的直接下级
  347. $directUsers = User::where('spread_uid', $uid)
  348. ->column('uid');
  349. if (empty($directUsers)) {
  350. return;
  351. }
  352. foreach ($directUsers as $userUid) {
  353. $allUsers[] = $userUid;
  354. // 递归查询该用户的下级
  355. $this->getTeamUsersRecursive($userUid, $allUsers);
  356. }
  357. }
  358. /**
  359. * 发放平级奖励
  360. * 无限向上查找上级,如果上级的分销等级等于指定等级,发放平级奖励
  361. * @param int $rewardUid 获得奖励的用户UID
  362. * @param float $rewardAmount 奖励金额
  363. * @param int $agentLevelId 分销等级ID
  364. * @param float $sameLevelRatio 平级奖励比例
  365. * @return bool
  366. */
  367. public function sameLevelReward($rewardUid, $rewardAmount, $agentLevelId, $sameLevelRatio){
  368. try {
  369. if ($rewardAmount <= 0 || $sameLevelRatio <= 0) {
  370. return false;
  371. }
  372. /** @var UserServices $userServices */
  373. $userServices = app()->make(UserServices::class);
  374. /** @var UserBrokerageServices $userBrokerageServices */
  375. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  376. // 计算平级奖励金额:奖励金额 * 平级比例 / 100
  377. $sameLevelAmount = bcmul((string)$rewardAmount, (string)($sameLevelRatio / 100), 2);
  378. if ($sameLevelAmount <= 0) {
  379. return false;
  380. }
  381. // 从奖励用户开始,无限向上查找上级
  382. $currentUid = $rewardUid;
  383. while ($currentUid > 0) {
  384. // 查询当前用户的上级
  385. $spreadUid = User::where('uid', $currentUid)->value('spread_uid');
  386. if (!$spreadUid || $spreadUid <= 0) {
  387. break;
  388. }
  389. // 查询上级的分销等级
  390. $spreadAgentLevelId = User::where('uid', $spreadUid)->value('agent_level');
  391. if (!$spreadAgentLevelId) {
  392. $currentUid = $spreadUid;
  393. continue;
  394. }
  395. // 如果上级的分销等级ID等于指定的等级ID,发放平级奖励
  396. if ($spreadAgentLevelId == $agentLevelId) {
  397. $balance = $userServices->value(['uid' => $spreadUid], 'brokerage_price');
  398. $userBrokerageServices->income('get_same_level_reward', $spreadUid, [
  399. 'pay_price' => 0,
  400. 'number' => $sameLevelAmount,
  401. ], bcadd((string)$balance, (string)$sameLevelAmount, 2), 0);
  402. $userServices->bcInc($spreadUid, 'brokerage_price', $sameLevelAmount, 'uid');
  403. }
  404. // 继续向上查找
  405. $currentUid = $spreadUid;
  406. }
  407. return true;
  408. } catch (\Exception $e) {
  409. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-sameLevelReward报错内容\r\n", 8);
  410. @file_put_contents("quanju.txt", json_encode($e->getLine())."-sameLevelReward报错位置\r\n", 8);
  411. @file_put_contents("quanju.txt", json_encode($e->getFile())."-sameLevelReward报错文件\r\n", 8);
  412. throw $e;
  413. }
  414. }
  415. /**
  416. * 发放平级奖励(内部调用方法)
  417. * 查询所有设置平级奖的等级并发放奖励
  418. * @param int $rewardUid 获得奖励的用户UID
  419. * @param float $rewardAmount 奖励金额
  420. * @return bool
  421. */
  422. private function issueSameLevelReward($rewardUid, $rewardAmount){
  423. try {
  424. // 查询所有设置了平级奖的分销等级(equal_award > 0)
  425. $agentLevelsWithAward = \app\model\agent\AgentLevel::where('equal_award', '>', 0)
  426. ->column('equal_award', 'id');
  427. if (empty($agentLevelsWithAward)) {
  428. return false;
  429. }
  430. // 遍历所有设置了平级奖的等级,发放奖励
  431. foreach ($agentLevelsWithAward as $agentLevelId => $equalAward) {
  432. $this->sameLevelReward($rewardUid, $rewardAmount, $agentLevelId, $equalAward);
  433. }
  434. return true;
  435. } catch (\Exception $e) {
  436. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-issueSameLevelReward报错内容\r\n", 8);
  437. @file_put_contents("quanju.txt", json_encode($e->getLine())."-issueSameLevelReward报错位置\r\n", 8);
  438. @file_put_contents("quanju.txt", json_encode($e->getFile())."-issueSameLevelReward报错文件\r\n", 8);
  439. throw $e;
  440. }
  441. }
  442. }