load(['userInfo.dealer', 'products']); foreach ($orders as $order) { try { DB::beginTransaction(); $this->processOrder($order); DB::commit(); } catch (Throwable $e) { DB::rollBack(); report($e); } } }); return 0; } /** * 处理经销商订单 * * @param \App\Models\DealerOrder $order * @return void */ protected function processOrder(DealerOrder $order) { $tz = now(); $dealers = $this->getDealers($userInfo = $order->userInfo); // 如果当前用户的上级有管理者,则需要增加管理者的商品销售业绩 if ($manager = $this->firstManager([$userInfo->dealer, ...$dealers])) { DealerManagerSalesLog::insert( $order->products->map(function ($product) use ($manager, $tz) { return [ 'user_id' => $manager->user_id, 'order_id' => $product->order_id, 'product_id' => $product->product_id, 'lvl' => $manager->lvl, 'sales_volume' => $product->qty, 'created_at' => $tz, 'updated_at' => $tz, ]; })->all() ); } } /** * 从给定的经销商中获取第一个管理者 * * @param array $dealers * @return \App\Models\Dealer|null */ protected function firstManager(array $dealers): ?Dealer { foreach ($dealers as $dealer) { if ($dealer->is_manager) { return $dealer; } } } /** * 获取给定用户的上级经销商 * * @param \App\Models\UserInfo $userInfo * @return array */ protected function getDealers(UserInfo $userInfo) { $ancestors = []; if (empty($pids = $userInfo->parent_ids)) { return $ancestors; } $ancestors = UserInfo::with(['dealer']) ->whereIn('user_id', $pids) ->latest('depth') ->get(['user_id', 'depth']); return $ancestors->map(function ($item) { return $item->dealer; })->all(); } }