with(['owner'=>function($query){ $query->select('id',"code"); }])->where("counting_month","like",$year."-".$lastMonth."%")->get(); $reports = OwnerReport::query()->where("counting_month","like",$year."-".$lastMonth."%")->orWhere("counting_month","like",$historyYear."-".$historyMonth."%")->get(); $bills = OwnerBillReport::query()->where("counting_month","like",$year."-".$lastMonth."%")->get(); //日均单量统计 $query = DB::raw("select count(*) c,CUSTOMERID from DOC_ORDER_HEADER where EDITTIME >= to_date('$year-$lastMonth-01 00:00:00','yyyy-mm-dd hh24:mi:ss') and EDITTIME <= to_date('$year-$lastMonth-$lastDay 23:59:59','yyyy-mm-dd hh24:mi:ss') group by CUSTOMERID"); $orderStatistic = DB::connection("oracle")->select($query); $map = []; foreach ($orderStatistic as $item){ $map[$item->customerid] = round($item->c / $lastDay,2); } //已存在的报表记录 $reportMap = []; $historyReportMap = []; foreach ($reports as $report){ if ($report->counting_month == ($historyYear."-".$historyMonth)){ $historyReportMap[$report->owner_id."_".$report->counting_month] = $report->current_month_counting_area; continue; } $reportMap[$report->owner_id."_".$report->counting_month] = $report->id; } //组装账单记录 $billMap = []; foreach ($bills as $index => $bill){ $bill[$bill->owner_id."_".$bill->counting_month] = $index; } //组装报表记录数据 $updateReports = [[ "id","daily_average_order_amount","current_month_counting_area","owner_bill_report_id" ]]; $createReports = []; foreach ($areas as $area){ if ($reportMap[$area->owner_id."_".$area->counting_month] ?? false){ $updateReports[] = [ "id"=>$reportMap[$area->owner_id."_".$area->counting_month], "daily_average_order_amount"=>$area->owner ? ($map[$area->owner->code] ?? 0) : 0, "current_month_counting_area"=>$area->accounting_area ?? 0, "owner_bill_report_id" => $billMap[$area->owner_id."_".$area->counting_month] ?? 0, ]; }else $createReports[] = [ "owner_id"=>$area->owner_id, "counting_month"=>$area->counting_month."-01", "daily_average_order_amount"=>$area->owner ? ($map[$area->owner->code] ?? 0) : 0, "current_month_counting_area"=>$area->accounting_area ?? 0, "owner_bill_report_id" => $billMap[$area->owner_id."_".$area->counting_month] ?? 0, "last_month_counting_area" => $historyReportMap[$area->owner_id."_".($historyYear."-".$historyMonth)] ?? 0, ]; } //执行生成或修改 app('LogService')->log(__METHOD__,"生成货主报表",json_encode($createReports)); app(BatchUpdateService::class)->batchUpdate('owner_reports', $updateReports); DB::table("owner_reports")->insert($createReports); } }