processing(); })->settlable()->chunkById(200, function ($orders) { $orders->load(['user', 'afterSales']); foreach ($orders as $order) { try { DB::beginTransaction(); $this->settle($order); DB::commit(); } catch (Throwable $e) { DB::rollBack(); report($e); } } }); return 0; } /** * 结算成长值 * * @param \App\Models\Order $order * @return void */ protected function settle(Order $order) { // 用户可得销售值 $salesValue = $order->sales_value; foreach ($order->afterSales as $afterSale) { if ($afterSale->isCancelled()) { continue; } $salesValue = bcsub($salesValue, $afterSale->sales_value, 2); } $user = $order->user; // 结算下单用户的成长值 $user->userInfo()->update([ 'growth_value' => DB::raw("growth_value+{$salesValue}"), 'pre_growth_value' => DB::raw("pre_growth_value-{$salesValue}"), ]); // 尝试提升用户的代理等级 $user->userInfo->attemptUpgradeAgentLevel(); if (count($pids = $user->userInfo->parent_ids) > 0) { // 更新上级的团队销售值 UserInfo::whereIn('user_id', $pids)->update([ 'group_sales_value' => DB::raw("group_sales_value + {$salesValue}"), ]); $ancestors = UserInfo::whereIn('user_id', $pids)->latest('depth')->get(); foreach ($ancestors as $ancestor) { $ancestor->attemptUpgradeAgentLevel(); } } // 将订单标记未已结算 $order->update([ 'is_settle' => true, ]); // 将预收益标记为结算中 DistributionPreIncome::where('order_id', $order->id)->update([ 'status' => DistributionPreIncome::STATUS_PROCESSING, ]); } }