$quotes = $this->quotes()
->select(\DB::raw("*, DATEDIFF(completed_at, created_at) AS DaysToComplete"))
->whereRaw(\DB::raw("quotes.created_at >= STR_TO_DATE('".$from->format('d/m/Y')." 00:00', '%d/%m/%Y %H:%i')"))
->whereRaw(\DB::raw("quotes.created_at <= STR_TO_DATE('".$to->format('d/m/Y')." 23:59', '%d/%m/%Y %H:%i')"))
->whereRaw('completed_at IS NOT NULL')
->whereRaw("completed_at <> '0000-00-00 00:00:00' ")
->get();
/**
* Puts Opening Hours into an array using
* DateTime/Carbon DayOfWeek as key
* these keys are saved against
* each day within the
* opening hours
* table
*
* SUNDAY // int(0)
* MONDAY // int(1)
* TUESDAY // int(2)
* WEDNESDAY // int(3)
* THURSDAY // int(4)
* FRIDAY // int(5)
* SATURDAY // int(6)
*/
$opening_hours = OpeningHour::all();
foreach($opening_hours as $hours){
$hrs[$hours->day] = [
'day' => $hours->day,
'name' => $hours->name,
'opening_time' => $hours->opening_time,
'closing_time' => $hours->closing_time,
'active' => $hours->active,
];
}
$quote_completion_time = array();
foreach($quotes as $quote){
$created_at = $quote->created_at;
$completed_at = $quote->completed_at;
$minutes = 0;
for($i = 0;$i <= $quote->DaysToComplete;$i++){
/**
* Manipulates the opening_time and closing_time to the same
* day so that you can check the diffInMinutes between 2
* carbon instances for the same day
*/
$opening_time = \Carbon::createFromFormat('Y-m-d H:i:s', $created_at->format('Y-m-d') . ' ' . $hrs[$created_at->dayOfWeek]['opening_time']);
$closing_time = \Carbon::createFromFormat('Y-m-d H:i:s', $created_at->format('Y-m-d') . ' ' . $hrs[$created_at->dayOfWeek]['closing_time']);
/**
* Checks if the day is active within opening hours
* that is set within the opening hours table
*/
if($hrs[$created_at->dayOfWeek]['active'] == 1){
if($quote->DaysToComplete == 0){
//For quotes that are created and completed on the same day
$minutes += $created_at->diffInMinutes($completed_at);
} elseif($i == 0){
// The first day of a quote opening but not being completed in the same day
$minutes += $created_at->diffInMinutes($closing_time);
}elseif($i == $quote->DaysToComplete){
//The day the quote was completed
$minutes += $opening_time->diffInMinutes($completed_at);
}else{
//full days where the quote was open but not completed
$minutes += $opening_time->diffInMinutes($closing_time);
}
}
//Add day to created_at ready for the next checks
$created_at->addDay();
}
$quote_completion_time[] = $minutes;
}
$quotes_collection = collect($quote_completion_time);
$minutes = $quotes_collection->avg();
if (empty($minutes)){
return 'N/A';
}
return \Carbon\CarbonInterval::create(0, 0, 0, floor($minutes/1440), floor(($minutes % 1440)/60), $minutes%60, 0);
这是我最终做的。我的开放时间表有一个名为day的字段,它与星期几和DateTime匹配
你想结束什么? –