Skip to content

Instantly share code, notes, and snippets.

@hungerburg
Last active July 23, 2022 14:07
Show Gist options
  • Save hungerburg/ba90e5fe4bdf29734ace2a43ae023d5b to your computer and use it in GitHub Desktop.
Save hungerburg/ba90e5fe4bdf29734ace2a43ae023d5b to your computer and use it in GitHub Desktop.
Analyse TrackWorkTime Report
<?php
/*
* The fine app https://github.com/mathisdt/trackworktime can save reports to CSV.
* Below script transforms the raw all data export for printing from a spreadsheet e.g.
*/
// Wrap library call
function my_getcsv($line) {
return str_getcsv($line, ';');
}
// Read the file into an array, Separate column headers
$punches = array_map('my_getcsv', file('events-all-data.csv'));
$headers = array_shift($punches);
// Combine punches by their date
$workdays = array();
$prev_type = 'out';
$prev_date = '';
array_walk($punches, function (&$punch) use ($headers, &$workdays, &$prev_type, &$prev_date) {
$punch = array_combine($headers, $punch);
$date = date('Y-m-d', strtotime($punch['time']));
$type = $punch['type'];
if ($type === $prev_type) { return; } // What if double 'out'?
if ($type === 'in' && isset($workdays[$date])) {
$workdays[$date][] = $punch;
$prev_type = 'in';
} elseif ($type === 'in' && !isset($workdays[$date])) {
$workdays[$date] = array($punch);
$prev_date = $date;
$prev_type = 'in';
} elseif ($type === 'out' && isset($workdays[$date])) {
$workdays[$date][] = $punch;
$prev_type = 'out';
} elseif ($type === 'out' && isset($workdays[$prev_date])) {
$workdays[$prev_date][] = $punch;
$prev_type = 'out';
} else {
print('Missing "in" for "out": ');
die(print_r($punch));
}
});
#die(print_r($workdays));
// Sum up each workday's punches
array_walk($workdays, function (&$events, $date) {
$num_events = count($events);
if ($num_events %2 === 1) {
print('Missing "out" for "in": ');
die(print_r($events));
}
$events['sum'] = new DateTime('00:00:00');
$event0 = clone $events['sum'];
$events['cnt'] = $num_events;
$events['txt'] = array();
for ($task = 0; $task < $num_events; $task += 2) {
$in = new DateTime($events[$task]['time']);
$in->setTime($in->format('G'), $in->format('i'));
$out = new DateTime($events[$task + 1]['time']);
$out->setTime($out->format('G'), $out->format('i'));
$events['sum']->add($in->diff($out));
$events['txt'][] = date('H:i', strtotime($events[$task]['time']))
. '-' . date('H:i', strtotime($events[$task + 1]['time']));
}
$events['sum'] = $event0->diff($events['sum']);
$events['sum'] = sprintf('%02d:%02d', $events['sum']->d*24 + $events['sum']->h, $events['sum']->i);
$events['txt'] = implode(';', $events['txt']);
});
#die(print_r($workdays));
// Print summaries as CSV
print("date;sum;cnt;text\n");
foreach($workdays as $date => $workday) {
print($date . ';' . $workday['sum'] . ';' . $workday['cnt'] . ';' . $workday['txt'] . "\n");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment