A typical day at the office... added by sjamaan on Thu Jul 9 10:22:16 2015

    public function findBadPerformanceCausesForPeriod($startDate, $endDate)
    {
        return $this->getQuery($this->mScore)
            ->where('lost_count', '>', 0) // Do NOT, repeat DO NOT put this _after_ the whereHas.  This will break the silly little query builder
            // In fact, don't add anything after this complex where.
            // It will generate a syntactically invalid query (if
            // you're lucky!  If you're unlucky, the generated query
            // will just be incorrect)
            ->whereHas('recruiter_earning', function($query) use ($startDate, $endDate) {
                return $query->whereHas('team', function($query) use ($startDate, $endDate) {
                    return $query->whereHas('shift', function($query) use ($startDate, $endDate) {
                       return $query->whereBetween('date', [$startDate, $endDate]);
                    });
                })->whereHas('recruiter', function ($query) use ($startDate, $endDate) {
                    return $query->whereExists(function($query) use ($startDate, $endDate) {
                        $query->select(\DB::raw(1))
                            ->from('recruiter_scores AS rs')
                            ->join('recruiter_earnings AS re', 're.id', '=', 'rs.recruiter_earning_id')
                            ->join('teams AS t', 't.id', '=', 're.team_id')
                            ->join('shifts AS s', 's.id', '=', 't.shift_id')
                            ->whereBetween('date', [$startDate, $endDate])
                            // Ick
                            ->having(\DB::raw('CASE '.
                                              '  WHEN SUM(rs.initially_recruited_count) <  5 THEN SUM(rs.lost_count) >= 2 '.
                                              '  WHEN SUM(rs.initially_recruited_count) < 15 THEN SUM(rs.lost_count) >= 3 '.
                                              '  WHEN SUM(rs.initially_recruited_count) < 25 THEN SUM(rs.lost_count) >= 4 '.
                                              '  WHEN SUM(rs.initially_recruited_count) > 25 THEN SUM(rs.lost_count) >= 5 '.
                                              // More silliness of the query builder: it does not understand that
                                              // in "HAVING foo", foo is a valid and complete boolean expression.
                                              'END'), '=', 'TRUE')
                            ->groupBy('re.recruiter_id')
                            ->whereRaw('re.recruiter_id = recruiters.id');
                    });
                });
            })->get();
    }