StoreOrderSuccessServices.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. }
  180. return true;
  181. } catch (\Exception $e) {
  182. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-spreadReward报错内容\r\n", 8);
  183. @file_put_contents("quanju.txt", json_encode($e->getLine())."-spreadReward报错位置\r\n", 8);
  184. @file_put_contents("quanju.txt", json_encode($e->getFile())."-spreadReward报错文件\r\n", 8);
  185. throw $e;
  186. }
  187. }
  188. /**
  189. * 发放核销订单线路奖励
  190. * 针对分销等级为4的用户,统计其直推下级团队中门店核销订单数量
  191. * 当两条线都达到200单时,奖励verific_reward金额
  192. * 当第三条线达到200单时,再奖励more_reward金额
  193. * 第四条及以后达到200单,每次奖励more_reward金额
  194. * @param int $spread_uid 分销等级为4的用户UID
  195. * @return bool
  196. */
  197. public function verifyLineReward($spread_uid){
  198. try {
  199. // 获取用户的分销等级ID
  200. $agent_level_id = User::where('uid', $spread_uid)->value('agent_level');
  201. if (!$agent_level_id) {
  202. return false;
  203. }
  204. // 获取分销等级的grade字段
  205. $agentLevelInfo = \app\model\agent\AgentLevel::where('id', $agent_level_id)->find();
  206. if (!$agentLevelInfo) {
  207. return false;
  208. }
  209. $agentGrade = $agentLevelInfo->grade;
  210. // 只处理分销等级为4的用户
  211. if ($agentGrade != 4) {
  212. return false;
  213. }
  214. // 获取该用户的所有直推下级
  215. $directUsers = User::where('spread_uid', $spread_uid)
  216. ->column('uid');
  217. if (empty($directUsers)) {
  218. return false;
  219. }
  220. // 收集所有需要统计的用户(包括直推下级及其所有下级)
  221. $allLineUsers = [];
  222. foreach ($directUsers as $directUid) {
  223. $lineUsers = $this->getAllTeamUsers($directUid);
  224. $allLineUsers[] = $lineUsers;
  225. }
  226. if (empty($allLineUsers)) {
  227. return false;
  228. }
  229. // 统计每条线的核销订单数量
  230. $lineVerifyCounts = [];
  231. foreach ($allLineUsers as $lineUsers) {
  232. if (empty($lineUsers)) {
  233. $lineVerifyCounts[] = 0;
  234. continue;
  235. }
  236. // 查询这些用户拥有的门店的核销订单总量
  237. $totalVerifyNum = \app\model\system\store\SystemStore::whereIn('uid', $lineUsers)
  238. ->sum('verify_num');
  239. $lineVerifyCounts[] = (int)$totalVerifyNum;
  240. }
  241. // 统计达到200单的线路数量
  242. $qualifiedLines = 0;
  243. foreach ($lineVerifyCounts as $count) {
  244. if ($count >= 200) {
  245. $qualifiedLines++;
  246. }
  247. }
  248. if ($qualifiedLines < 2) {
  249. return false;
  250. }
  251. // 获取奖励配置
  252. $verificReward = sys_config('verific_reward', 0);
  253. $moreReward = sys_config('more_reward', 0);
  254. if ($verificReward <= 0 && $moreReward <= 0) {
  255. return false;
  256. }
  257. // 查询用户已发放的奖励记录
  258. $rewardRecords = \app\model\user\UserBrokerage::where('uid', $spread_uid)
  259. ->where('type', 'get_brokerage')
  260. ->where('title', 'like', '%核销线路奖励%')
  261. ->column('id', 'number');
  262. // 计算应该发放的奖励
  263. $verificRewardCount = 0; // verific_reward应该发放的次数(最多1次)
  264. $moreRewardCount = 0; // more_reward应该发放的次数
  265. if ($qualifiedLines >= 2) {
  266. $verificRewardCount = 1;
  267. // 超过2条线,每多一条线发放一次more_reward
  268. $moreRewardCount = $qualifiedLines - 2;
  269. }
  270. // 查询已发放的verific_reward次数
  271. $issuedVerificCount = 0;
  272. foreach ($rewardRecords as $amount => $id) {
  273. if (abs($amount - $verificReward) < 0.01) {
  274. $issuedVerificCount++;
  275. }
  276. }
  277. // 查询已发放的more_reward次数
  278. $issuedMoreCount = 0;
  279. foreach ($rewardRecords as $amount => $id) {
  280. if (abs($amount - $moreReward) < 0.01) {
  281. $issuedMoreCount++;
  282. }
  283. }
  284. // 判断是否需要发放奖励
  285. $needVerificReward = $verificRewardCount > $issuedVerificCount;
  286. $needMoreReward = $moreRewardCount > $issuedMoreCount;
  287. if (!$needVerificReward && !$needMoreReward) {
  288. return false;
  289. }
  290. /** @var UserServices $userServices */
  291. $userServices = app()->make(UserServices::class);
  292. /** @var UserBrokerageServices $userBrokerageServices */
  293. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  294. $balance = $userServices->value(['uid' => $spread_uid], 'brokerage_price');
  295. // 发放verific_reward(两条线达标奖励)
  296. if ($needVerificReward && $verificReward > 0) {
  297. $userBrokerageServices->income('line_two_reward', $spread_uid, [
  298. 'pay_price' => 0,
  299. 'number' => $verificReward,
  300. ], bcadd((string)$balance, (string)$verificReward, 2), 0);
  301. $userServices->bcInc($spread_uid, 'brokerage_price', $verificReward, 'uid');
  302. $balance = bcadd((string)$balance, (string)$verificReward, 2);
  303. }
  304. // 发放more_reward(第三条及以上线达标,可能多次)
  305. if ($needMoreReward && $moreReward > 0) {
  306. $needIssueMoreCount = $moreRewardCount - $issuedMoreCount;
  307. for ($i = 0; $i < $needIssueMoreCount; $i++) {
  308. $userBrokerageServices->income('line_more_reward', $spread_uid, [
  309. 'pay_price' => 0,
  310. 'number' => $moreReward,
  311. ], bcadd((string)$balance, (string)$moreReward, 2), 0);
  312. $userServices->bcInc($spread_uid, 'brokerage_price', $moreReward, 'uid');
  313. $balance = bcadd((string)$balance, (string)$moreReward, 2);
  314. }
  315. }
  316. return true;
  317. } catch (\Exception $e) {
  318. @file_put_contents("quanju.txt", json_encode($e->getMessage())."-verifyLineReward报错内容\r\n", 8);
  319. @file_put_contents("quanju.txt", json_encode($e->getLine())."-verifyLineReward报错位置\r\n", 8);
  320. @file_put_contents("quanju.txt", json_encode($e->getFile())."-verifyLineReward报错文件\r\n", 8);
  321. throw $e;
  322. }
  323. }
  324. /**
  325. * 获取用户的所有下级(递归查询团队)
  326. * @param int $uid 用户UID
  327. * @return array 所有下级UID数组
  328. */
  329. private function getAllTeamUsers($uid){
  330. $allUsers = [];
  331. $this->getTeamUsersRecursive($uid, $allUsers);
  332. return $allUsers;
  333. }
  334. /**
  335. * 递归获取用户的所有下级
  336. * @param int $uid 当前用户UID
  337. * @param array &$allUsers 已收集的用户数组(引用传递)
  338. */
  339. private function getTeamUsersRecursive($uid, &$allUsers){
  340. // 查询该用户的直接下级
  341. $directUsers = User::where('spread_uid', $uid)
  342. ->column('uid');
  343. if (empty($directUsers)) {
  344. return;
  345. }
  346. foreach ($directUsers as $userUid) {
  347. $allUsers[] = $userUid;
  348. // 递归查询该用户的下级
  349. $this->getTeamUsersRecursive($userUid, $allUsers);
  350. }
  351. }
  352. }