export user summary

PHOTO EMBED

Wed Jun 05 2024 06:55:26 GMT+0000 (Coordinated Universal Time)

Saved by @Hoangtinh2024 #php

public function exportUserSummary($workflow_id, Request $request)
{
$isValid = self::handleValidateUrl($workflow_id);
if ($isValid !== true) {
return $isValid;
}
$search_start_date = $request->start_date;
$search_end_date = $request->end_date;
$search_limit = $request->limit ?: 100;
$search_page = $request->page ?: 1;

$search_offset = ($search_page - 1) * $search_limit;

// Fetch user list

$rawList = SasageHelper::$companyObj->fetch_users($search_limit, $search_offset);
$userList = collect($rawList)->map(function ($obj) {
return collect($obj)->except(SasageHelper::$userHiddenProps);
});

// Fetch tracking data for all users
$trackingObj = new \Sasage\Tracking(SasageHelper::$sasageAuthentication);

$types = ['shoot', 'measure', 'data_input', 'confirm', 'sasage'];
$trackingList = [];
$fetchFailed = false;

foreach ($types as $type) {
$tempTrackingList = [];
$results = $trackingObj->fetch_user_daily_tracking($workflow_id, $type, $search_start_date, $search_end_date, -1, -1);
if (isset($results['errors'])) {
$fetchFailed = true;
break;
}
$tempTrackingList = array_merge($tempTrackingList, $results);
$trackingList = array_merge($trackingList, $tempTrackingList);
}
if ($fetchFailed) {
// Fetch failed
return response()->json([
'message' => 'Failed to fetch tracking.',
], 500);
}

// Init user summary props
foreach ($userList as $userIndex => $user) {
foreach ($types as $type) {
$user[$type . '_duration'] = 0;
$user[$type . '_total'] = 0;
$userList[$userIndex] = $user;
}
}

// Mapping all data in tracking list to user by user.id and tracking.created_by
foreach ($trackingList as $tracking) {
foreach ($userList as $userIndex => $user) {
if ($user['id'] === $tracking['created_by']) {
$user[$tracking['type'] . '_duration'] = $tracking['duration'];
$user[$tracking['type'] . '_total'] = count($tracking['product_ids']);
$userList[$userIndex] = $user;
}
}
}

// Create CSV file
$filename = "user_summary_{$workflow_id}_" . date('Ymd_His') . ".csv";
$handle = fopen($filename, 'w');
$header = [
'username',
'averageDuration',
'averageShootDuration',
'averageMeasureDuration',
'averageDataInputDuration',
'averageConfirmDuration'
];
fputcsv($handle, $header);

foreach ($userList as $user) {
fputcsv($handle, [
$user['username'],
$user['sasage_duration'],
$user['shoot_duration'],
$user['measure_duration'],
$user['data_input_duration'],
$user['confirm_duration'],
]);
}

fclose($handle);

return response()->download($filename);
}
content_copyCOPY