Refactor code and do more work on import function

This commit is contained in:
Troels Liebe Bentsen 2014-10-06 20:42:07 +02:00
parent 56a296f103
commit 28b5b5f9c2
5 changed files with 189 additions and 186 deletions

View File

@ -9,11 +9,9 @@ class ImportTimesheetData extends Command {
protected $name = 'ninja:import-timesheet-data'; protected $name = 'ninja:import-timesheet-data';
protected $description = 'Import timesheet data'; protected $description = 'Import timesheet data';
public function fire() public function fire() {
{
$this->info(date('Y-m-d') . ' Running ImportTimesheetData...'); $this->info(date('Y-m-d') . ' Running ImportTimesheetData...');
/* try { /* try {
$dt = new DateTime("now"); $dt = new DateTime("now");
var_dump($dt); var_dump($dt);
@ -25,11 +23,6 @@ class ImportTimesheetData extends Command {
} }
exit(0); */ exit(0); */
// Create some initial sources we can test with // Create some initial sources we can test with
$user = User::first(); $user = User::first();
if (!$user) { if (!$user) {
@ -38,7 +31,6 @@ class ImportTimesheetData extends Command {
} }
// TODO: Populate with own test data until test data has been created // TODO: Populate with own test data until test data has been created
// Truncate the tables // Truncate the tables
$this->info("Truncate tables"); $this->info("Truncate tables");
DB::statement('SET FOREIGN_KEY_CHECKS=0;'); DB::statement('SET FOREIGN_KEY_CHECKS=0;');
@ -77,6 +69,7 @@ class ImportTimesheetData extends Command {
$event_source->url = $source['url']; $event_source->url = $source['url'];
$event_source->owner = $source['owner']; $event_source->owner = $source['owner'];
$event_source->type = 'ical'; $event_source->type = 'ical';
//$event_source->from_date = new DateTime("2009-01-01");
$event_source->save(); $event_source->save();
} }
} }
@ -113,35 +106,12 @@ class ImportTimesheetData extends Command {
# Fix lines broken by 76 char limit # Fix lines broken by 76 char limit
$eventstr = preg_replace('/\r?\n\s/s', '', $eventstr); $eventstr = preg_replace('/\r?\n\s/s', '', $eventstr);
//$this->info("Parse data"); //$this->info("Parse data");
if(preg_match_all('/(?:^|\r?\n)([^;:]+)[;:]([^\r\n]+)/s', $eventstr, $eventmatches)) { $data = TimesheetUtils::parseICALEvent($eventstr);
// Build ICAL event array if ($data) {
$data = ['summary' => ''];
foreach($eventmatches[1] as $i => $key) {
# Convert escaped linebreakes to linebreak
$value = preg_replace("/\r?\n\s/", "", $eventmatches[2][$i]);
# Unescape , and ;
$value = preg_replace('/\\\\([,;])/s', '$1', $value);
$data[strtolower($key)] = $value;
}
// Extract code for summary so we only import events we use // Extract code for summary so we only import events we use
//$this->info("Match summary"); list($codename, $tags, $title) = TimesheetUtils::parseEventSummary($data['summary']);
if(preg_match('/^\s*([^\s:\/]+)(?:\/([^:]+))?\s*:\s*(.*?)\s*$/s', $data['summary'], $matches)) { if ($codename != null) {
$codename = strtoupper($matches[1]);
$tags = strtolower($matches[2]);
$title = $matches[3];
//$this->info("Check code");
if(isset($codes[$codename])) {
//var_dump($data);
$code = $codes[$codename];
$event = TimesheetEvent::createNew($user); $event = TimesheetEvent::createNew($user);
$event->summary = $title;
$event->description = $title;
$event->owner = $event_source->owner;
$event->timesheet_event_source_id = $event_source->id;
$event->project_id = $code->project_id;
$event->project_code_id = $code->id;
$event->uid = $data['uid']; $event->uid = $data['uid'];
# Add RECURRENCE-ID to the UID to make sure the event is unique # Add RECURRENCE-ID to the UID to make sure the event is unique
@ -161,31 +131,21 @@ class ImportTimesheetData extends Command {
$uids[$event->uid] = $data; $uids[$event->uid] = $data;
//TODO: Bail on RRULE as we don't support that //TODO: Bail on RRULE as we don't support that
// Convert to DateTime objects
//$event->org_data = $eventstr;
if(isset($data['location'])) {
$event->location = $data['location'];
}
foreach (['dtstart', 'dtend', 'created', 'last-modified'] as $key) { foreach (['dtstart', 'dtend', 'created', 'last-modified'] as $key) {
// Parse and create DataTime object from ICAL format // Parse and create DataTime object from ICAL format
$dt = null; list($dt, $timezone) = TimesheetUtils::parseICALDate($data[$key]);
$timezone = null;
if (preg_match('/^TZID=(.+?):([12]\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)$/', $data[$key], $m)) { // Handle bad dates in created and last-modified
$timezone = $m[1]; if ($dt == null) {
$dt = new DateTime("{$m[2]}-{$m[3]}-{$m[4]}T{$m[5]}:{$m[6]}:{$m[7]}", new DateTimeZone($m[1])); if ($key == 'created' || $key == 'last-modified') {
} else if (preg_match('/^VALUE=DATE:([12]\d\d\d)(\d\d)(\d\d)$/', $data[$key], $m)) {
$dt = new DateTime("{$m[1]}-{$m[2]}-{$m[3]}T00:00:00", new DateTimeZone("UTC"));
} else if (preg_match('/^([12]\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/', $data[$key], $m)) {
$dt = new DateTime("{$m[1]}-{$m[2]}-{$m[3]}T{$m[4]}:{$m[5]}:{$m[6]}", new DateTimeZone("UTC"));
} else if($key == 'created' || $key == 'last-modified') {
$dt = new DateTime('1970-01-01T00:00:00', new DateTimeZone("UTC")); // Default to UNIX epoc $dt = new DateTime('1970-01-01T00:00:00', new DateTimeZone("UTC")); // Default to UNIX epoc
echo "Could not parse date for $key: '" . $data[$key] . "' so default to UNIX Epoc\n"; // TODO write to error table echo "Could not parse date for $key: '" . $data[$key] . "' so default to UNIX Epoc\n"; // TODO write to error table
} else { } else {
echo "Could not parse date for $key: '" . $data[$key] . "'\n"; // TODO write to error table echo "Could not parse date for $key: '" . $data[$key] . "'\n"; // TODO write to error table
exit(255); // TODO: Bail on this event exit(255); // TODO: Bail on this event
} }
}
// Assign DateTime object to // Assign DateTime object to
switch ($key) { switch ($key) {
@ -197,8 +157,20 @@ class ImportTimesheetData extends Command {
$event->end_date = $dt; $event->end_date = $dt;
$event->org_end_date_timezone = $timezone; $event->org_end_date_timezone = $timezone;
break; break;
case 'created': $event->org_created_at = $dt; break; case 'created': $event->org_created_at = $dt;
case 'last-modified': $event->org_updated_at = $dt; break; break;
case 'last-modified': $event->org_updated_at = $dt;
break;
}
}
// Check that we are witin the range
if ($event_source->from_date != null) {
$from_date = new DateTime($event_source->from_date, new DateTimeZone('UTC'));
if ($from_date > $event->end_date) {
// Skip this event
echo "Skiped: $codename: $title\n";
continue;
} }
} }
@ -206,15 +178,23 @@ class ImportTimesheetData extends Command {
$di = $event->end_date->diff($event->start_date); $di = $event->end_date->diff($event->start_date);
$event->hours = $di->h + $di->i / 60; $event->hours = $di->h + $di->i / 60;
/*var_dump($event); // Copy data to new object
exit();*/ $event->org_data = $eventstr;
$event->summary = $title;
// Save event $event->description = $title;
$event->org_code = $code;
//if(!preg_match("/forbered møde med Peter Pietras - nyt sjovt projekt./", $event->summary)) { $event->owner = $event_source->owner;
$event->timesheet_event_source_id = $event_source->id;
if (isset($codes[$codename])) {
$event->project_id = $codes[$codename]->project_id;
$event->project_code_id = $codes[$codename]->id;
}
if (isset($data['location'])) {
$event->location = $data['location'];
}
try { try {
//$event->start_date = new DateTime(""); // Save event
$event->save(); $event->save();
} catch (Exception $ex) { } catch (Exception $ex) {
echo "'" . $event->summary . "'\n"; echo "'" . $event->summary . "'\n";
@ -223,20 +203,12 @@ class ImportTimesheetData extends Command {
echo $ex->getTraceAsString(); echo $ex->getTraceAsString();
//exit(); //exit();
} }
//}
} else {
//TODO: Add to error table so we can show user
echo "Code not found: $codename\n";
} }
} }
} }
}
} else { } else {
// Parse error // Parse error
} }
} else { } else {
// Curl Error // Curl Error
} }
@ -270,26 +242,23 @@ class ImportTimesheetData extends Command {
while ($still_running) { while ($still_running) {
// Do curl stuff // Do curl stuff
while (($mrc = curl_multi_exec($multi, $still_running)) === CURLM_CALL_MULTI_PERFORM); while (($mrc = curl_multi_exec($multi, $still_running)) === CURLM_CALL_MULTI_PERFORM);
if ($mrc !== CURLM_OK) { break; } if ($mrc !== CURLM_OK) {
break;
}
// Try to read from handles that are ready // Try to read from handles that are ready
while ($info = curl_multi_info_read($multi)) { while ($info = curl_multi_info_read($multi)) {
if ($info["result"] == CURLE_OK) { if ($info["result"] == CURLE_OK) {
$results[$ch2idx[(int) $info["handle"]]] = curl_multi_getcontent($info["handle"]); $results[$ch2idx[(int) $info["handle"]]] = curl_multi_getcontent($info["handle"]);
} else { } else {
if (CURLE_UNSUPPORTED_PROTOCOL == $info["result"]) { if (CURLE_UNSUPPORTED_PROTOCOL == $info["result"]) {
$results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Unsupported protocol"]; $results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Unsupported protocol"];
} else if (CURLE_URL_MALFORMAT == $info["result"]) { } else if (CURLE_URL_MALFORMAT == $info["result"]) {
$results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Malform url"]; $results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Malform url"];
} else if (CURLE_COULDNT_RESOLVE_HOST == $info["result"]) { } else if (CURLE_COULDNT_RESOLVE_HOST == $info["result"]) {
$results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Could not resolve host"]; $results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Could not resolve host"];
} else if (CURLE_OPERATION_TIMEDOUT == $info["result"]) { } else if (CURLE_OPERATION_TIMEDOUT == $info["result"]) {
$results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Timed out waiting for operations to finish"]; $results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Timed out waiting for operations to finish"];
} else { } else {
$results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Unknown curl error code"]; $results[$ch2idx[(int) $info["handle"]]] = [$info["result"], "Unknown curl error code"];
} }
@ -301,7 +270,6 @@ class ImportTimesheetData extends Command {
usleep(20); // select failed for some reason, so we sleep for 20ms and run some more curl stuff usleep(20); // select failed for some reason, so we sleep for 20ms and run some more curl stuff
} }
} }
} finally { } finally {
foreach ($handles as $chi => $ch) { foreach ($handles as $chi => $ch) {
curl_multi_remove_handle($multi, $ch); curl_multi_remove_handle($multi, $ch);
@ -313,17 +281,13 @@ class ImportTimesheetData extends Command {
return $results; return $results;
} }
protected function getArguments() protected function getArguments() {
{
return array( return array(
); );
} }
protected function getOptions() protected function getOptions() {
{
return array( return array(
); );
} }

View File

@ -79,6 +79,9 @@ class AddTimesheets extends Migration {
$t->string('url'); $t->string('url');
$t->enum('type', array('ical', 'googlejson')); $t->enum('type', array('ical', 'googlejson'));
$t->dateTime('from_date')->nullable();
$t->dateTime('to_date')->nullable();
$t->foreign('account_id')->references('id')->on('accounts'); $t->foreign('account_id')->references('id')->on('accounts');
$t->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
}); });
@ -94,23 +97,31 @@ class AddTimesheets extends Migration {
$t->timestamps(); $t->timestamps();
$t->softDeletes(); $t->softDeletes();
$t->string('summary'); // Basic fields
$t->string('uid'); $t->string('uid');
$t->string('summary');
$t->text('description'); $t->text('description');
$t->string('location'); $t->string('location');
$t->string('owner'); $t->string('owner');
$t->dateTime('start_date'); $t->dateTime('start_date');
$t->dateTime('end_date'); $t->dateTime('end_date');
# Calculated values
$t->decimal('hours'); $t->decimal('hours');
$t->float('discount'); $t->float('discount');
// Original data
$t->string('org_code');
$t->timeStamp('org_created_at'); $t->timeStamp('org_created_at');
$t->timeStamp('org_updated_at'); $t->timeStamp('org_updated_at');
$t->string('org_start_date_timezone')->nullable(); $t->string('org_start_date_timezone')->nullable();
$t->string('org_end_date_timezone')->nullable(); $t->string('org_end_date_timezone')->nullable();
$t->text('org_data'); $t->text('org_data');
// Error and merge handling
$t->string('import_error')->nullable();
$t->text('updated_data')->nullable();
$t->foreign('account_id')->references('id')->on('accounts'); $t->foreign('account_id')->references('id')->on('accounts');
$t->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$t->foreign('timesheet_event_source_id')->references('id')->on('timesheet_event_sources')->onDelete('cascade'); $t->foreign('timesheet_event_source_id')->references('id')->on('timesheet_event_sources')->onDelete('cascade');

View File

@ -35,6 +35,9 @@ class TimesheetEvent extends Eloquent
return $this->belongsTo('ProjectCode'); return $this->belongsTo('ProjectCode');
} }
/**
* @return TimesheetEvent
*/
public static function createNew($parent = false) public static function createNew($parent = false)
{ {
$className = get_called_class(); $className = get_called_class();

View File

@ -10,8 +10,7 @@ class ExampleTest extends TestCase {
public function testBasicExample() public function testBasicExample()
{ {
$crawler = $this->client->request('GET', '/'); $crawler = $this->client->request('GET', '/');
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertTrue($this->client->getResponse()->isOk());
} }
} }

View File

@ -0,0 +1,26 @@
<?php
class TimesheetUtilTest extends \PHPUnit_Framework_TestCase {
public function testParseEventSummary() {
list($code, $codes, $title) = TimesheetUtils::parseEventSummary('Riga :)');
$this->assertSame(null, $code);
list($code, $tags, $title) = TimesheetUtils::parseEventSummary('Test:');
$this->assertSame("TEST", $code);
list($code, $tags, $title) = TimesheetUtils::parseEventSummary('Test: ');
$this->assertSame("TEST", $code);
list($code, $tags, $title) = TimesheetUtils::parseEventSummary('Test::');
$this->assertSame("TEST", $code);
list($code, $tags, $title) = TimesheetUtils::parseEventSummary('TEST: Hello :)');
$this->assertSame("TEST", $code);
list($code, $tags, $title) = TimesheetUtils::parseEventSummary('Test/tags: ');
$this->assertSame('TEST', $code);
$this->assertSame('tags', $tags);
}
}