Output csv for rejection report #184

This commit is contained in:
Kendrick Chan 2019-02-26 03:07:56 +08:00
parent fb15b3e3bc
commit 71ed134e78

View file

@ -11,6 +11,7 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
@ -52,15 +53,38 @@ class ReportController extends BaseController
->getQuery();
// run query
$jors = $query->getResult();
// initialize counter
$counter = [];
// get results
$res = [];
foreach ($jors as $jor)
{
$jo = $jor->getJobOrder();
$hub = $jor->getHub();
$hub_id = $hub->getID();
$hub_name = $hub->getName() . ' - ' . $hub->getBranch();
$reason = $jor->getReason();
if (!isset($counter[$hub_id]))
$counter[$hub_id] = [
'reasons' => [],
'name' => $hub_name,
];
if (!isset($counter[$hub_id][$reason]))
{
$counter[$hub_id]['reasons'][$reason]['name'] = JORejectionReason::getName($reason);
$counter[$hub_id]['reasons'][$reason]['counter'] = 1;
}
else
{
$counter[$hub_id]['reasons'][$reason]['counter'] += 1;
}
$res[] = [
'jo_id' => $jo->getID(),
@ -73,9 +97,54 @@ class ReportController extends BaseController
];
}
// response
$resp = new StreamedResponse();
$resp->setCallback(function() use ($counter) {
// csv output
$csv_handle = fopen('php://output', 'w+');
fputcsv($csv_handle, ['Enrollee', 'Reason', 'Count']);
foreach ($counter as $centry)
{
$first = true;
foreach ($centry['reasons'] as $creason)
{
// first line has hub name
if ($first)
{
fputcsv($csv_handle, [
$centry['name'],
$creason['name'],
$creason['counter'],
]);
$first = false;
}
else
{
fputcsv($csv_handle, [
'',
$creason['name'],
$creason['counter'],
]);
}
}
}
fclose($csv_handle);
});
$filename = 'reject_' . $date_start->format('Ymd') . '_' . $date_end->format('Ymd') . '.csv';
$resp->setStatusCode(200);
$resp->headers->set('Content-Type', 'text/csv; charset=utf-8');
$resp->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
return $resp;
/*
return $this->json([
'result' => $res,
'counter' => $counter,
]);
*/
}
}