isCancelled()) { return false; } // 订单成长值 $sales_value = $order->sales_value; $user = $order->user; // 已经添加过返现记录 if ($user->salesValueLogs()->where('order_id', $order->id)->exists()) { return false; } // 用户获得成长值 $user->salesValueLogs()->create([ 'order_id' => $order->id, 'order_user_id' => $order->user_id, 'type' => SalesValueLog::TYPE_INDIVIDUAL, 'change_sales_value' => $sales_value ]); $user->userInfo()->increment('growth_value', $sales_value); // 自动升级代理 $levels = Vip::orderBy('sort')->get(); $level_up = ''; foreach($levels->reverse() as $item) { if ($user->userInfo->growth_value >= $item->growth_value) { $level_up = $item; } } if ($level_up && $level_up->slug === 'favoite') { $user->userVip()->updateOrCreate([], [ 'vip_id' => $level_up->id, 'growth_value' => $level_up->growth_value ]); } // 上级返现 $parent_ids = array_reverse($user->userInfo->parent_ids); $parents = User::with(['userInfo', 'userVip.vip'])->whereIn('id', $parent_ids)->get(); // 过滤掉不是代理身份的用户 // 过滤掉当前等级 大于 下一级的等级的用户 $filtered = $parents->filter(function ($item, $key) use ($parents) { if (!$item->userVip) { return false; } $next = $parents->get($key + 1); if ($next && $next->userVip) { return $item->userVip->vip->sort < $next->userVip->vip->sort; } return true; }); // 生成返现记录 $profit_list = []; $money_sum = 0; foreach($filtered->reverse() as $item) { $vip = $item->userVip->vip??''; if (!$vip) { continue; } $money = floor($sales_value * $vip->ratio) / 100 - $money_sum; array_unshift($profit_list, [ 'from_user_id' => $user->id, 'user_id' => $item->id, 'role' => $vip->slug . '-' . $vip->sort, 'role_name' => $vip->name, 'ratio' => $vip->ratio, 'growth_value' => $sales_value, 'money' => $money ]); $money_sum += $money; } $order->update([ 'profit' => $money_sum ]); $order->profits()->createMany($profit_list); } /** * 使用微信企业付款 * 调用之前, 需要提前生成商户订单号 */ public function wechatTransfer(OrderProfit $profit) { $user = $profit->user; $openid = $user->socialites()->where('socialite_type', SocialiteType::WechatMiniProgram->value)->value('socialite_id'); $result = (new WxpayService())->transfer([ 'partner_trade_no' => $profit->pay_no, 'openid' => $openid, 'check_name' => 'NO_CHECK', 'amount' => $profit->money * 100, 'desc' => '推荐返利', ]); $this->success($profit, $result); } /** * 返现记录支付成功 * * @param \App\Models\OrderProfit $profit * @param mixed $data */ public function success(OrderProfit $profit, $data = null) { $profit->update([ 'status' => 2, 'paid_at' => data_get($data, 'paid_at', now()), 'pay_data' => $data, 'remarks' => data_get($data, 'remarks'), ]); } }