office365 integration

This commit is contained in:
StudioTem committed 2025-03-17 09:54:13 +01:00
1 parent 264ca10078
commit e1712c8fcd
11 files changed
+551 -16

No files matched your search

@@ -0,0 +1,53 @@
<?php
namespace App\Console\Commands;
use App\Models\SubTask;
use App\Services\Office365\Office365Service;
use Illuminate\Console\Command;
class FinishOffice365Subtasks extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'office365:finish-subtasks';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Prida is_finished a timesheet subtaskom (eventom), ktore uz skoncili';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$events = Office365Service::getCalendarEvents();
// vrati vsetky office365 subtasky z nasej DB, ktore maju is_finished = 0 a porovna to s eventami z office365. ak je nejaky end time v office365 v minulosti, tak vrati tento subtask
$subtasksThatFinished = SubTask::where('is_finished', 0)->get()->filter(function ($subtask) use ($events) {
$event = collect($events)->firstWhere('id', $subtask->office365_id);
if ( ! $event) {
return false;
}
return strtotime($event['end']['dateTime']) < time();
});
// ak neexistuju ziadne subtasky, ktore uz skoncili
if ($subtasksThatFinished->isEmpty()) {
return Command::SUCCESS;
}
Office365Service::finishSubtasks($subtasksThatFinished);
return Command::SUCCESS;
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Console\Commands;
use App\Models\Blocker;
use App\Models\Project;
use App\Models\SubTask;
use App\Services\Office365\Office365Service;
use Illuminate\Console\Command;
class SyncOffice365 extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'office365:sync';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$events = Office365Service::getCalendarEvents();
// TODO: asi prerobit na CreateAndUpdate
// determine if event is blocker or subtask. if the first word in event name is project code, then it is subtask. otherwise it is blocker
// but first, remove "Canceled: " from the event name in case of canceled event
$events = array_map(function ($event) {
if ($event['isCancelled']) {
$event['subject'] = str_replace('Canceled: ', '', $event['subject']);
}
return $event;
}, $events);
$blockers_from_office365 = array_filter($events, function ($event) {
$projectCode = explode(' ', $event['subject'])[0];
// if project code doesnt exist in database, then it is blocker
return ! Project::where('code', $projectCode)->exists();
});
$subtasks = array_filter($events, function ($event) {
$projectCode = explode(' ', $event['subject'])[0];
// if project code exist in database, then it is subtask
return Project::where('code', $projectCode)->exists();
});
// get only new events - the ones that doesnt have any office365_id in blockers table and only events that doesnt have isCancelled => true
$newBlockers = array_filter($blockers_from_office365, function ($event) {
return ! Blocker::where('office365_id', $event['id'])->exists() && ! $event['isCancelled'];
});
$newSubtasks = array_filter($subtasks, function ($event) {
return ! SubTask::where('office365_id', $event['id'])->exists() && ! $event['isCancelled'];
});
Office365Service::addBlockers($newBlockers);
Office365Service::addSubtasks($newSubtasks);
// get edited blockers - the ones, that has different changeKey from our database
$editedBlockers = array_filter($blockers_from_office365, function ($event) {
$blocker = Blocker::where('office365_id', $event['id'])->first();
return $blocker && $blocker->office365_change_key !== $event['changeKey'];
});
Office365Service::editBlockers($editedBlockers);
// get all canceled blockers - the ones, that are in our database and in the response they have isCancelled => true
$removedBlockers = Blocker::whereNotNull('office365_id')->get()->filter(function ($blocker) use (
$blockers_from_office365
) {
$event = collect($blockers_from_office365)->firstWhere('id', $blocker->office365_id);
return $event && $event['isCancelled'];
});
// TODO dat do service
$removedBlockers->each(function ($blocker) {
$blocker->delete();
});
dd('he');
}
}
+2
View File
@@ -31,6 +31,8 @@ class Kernel extends ConsoleKernel
$schedule->command('karat:sync-projects')->everyFiveMinutes(); $schedule->command('karat:sync-projects')->everyFiveMinutes();
$schedule->command('karat:sync-projects-name')->hourly(); $schedule->command('karat:sync-projects-name')->hourly();
$schedule->command('karat:sync-timesheets')->everyFiveMinutes(); $schedule->command('karat:sync-timesheets')->everyFiveMinutes();
$schedule->command('office365:sync')->everyFiveMinutes();
$schedule->command('office365:finish-subtasks')->hourly();
} }
} }
+17 -15
View File
@@ -10,26 +10,28 @@ class MasterTaskResource extends JsonResource
* Transform the resource into an array. * Transform the resource into an array.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
*
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/ */
public function toArray($request) public function toArray($request)
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'name' => $this->title, 'name' => $this->title,
'created_by' => $this->created_by, 'created_by' => $this->created_by,
'description' => $this->description, 'description' => $this->description,
'duration' => $this->estimated_time, 'duration' => $this->estimated_time,
'time_worked' => $this->tracked_time, 'estimated_duration' => $this->pricequote_time,
'is_finished' => $this->is_finished, 'time_worked' => $this->tracked_time,
'starts_at' => $this->created_at, 'is_finished' => $this->is_finished,
'deadline' => $this->deadline, 'starts_at' => $this->created_at,
'project_code' => ($this->project) ? $this->project->code . ' ' . $this->project->name : null, 'deadline' => $this->deadline,
'team' => ($this->team) ?: null, 'project_code' => ($this->project) ? $this->project->code . ' ' . $this->project->name : null,
'employees' => UserResource::collection($this->usersOutsideTeam), 'team' => ($this->team) ?: null,
'subtasks' => SubTaskResource::collection($this->subtasks), 'employees' => UserResource::collection($this->usersOutsideTeam),
'files' => AttachmentResource::collection($this->attachments), 'subtasks' => SubTaskResource::collection($this->subtasks),
'color' => $this->color, 'files' => AttachmentResource::collection($this->attachments),
'color' => $this->color,
]; ];
} }
} }
@@ -0,0 +1,214 @@
<?php
namespace App\Services\Office365;
use App\Models\Blocker;
use App\Models\MasterTask;
use App\Models\Project;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
class Office365Service
{
public static function getCalendarEvents()
{
$token = self::getAccessToken();
$groupId = env('OFFICE365_GROUP_ID');
$response = Http::withToken($token)->get("https://graph.microsoft.com/v1.0/groups/$groupId/events");
return $response->json()['value'];
}
public static function getAccessToken()
{
$tenantId = env('MICROSOFT_TENANT_ID');
$clientId = env('MICROSOFT_CLIENT_ID');
$clientSecret = env('MICROSOFT_CLIENT_SECRET');
$username = env('MICROSOFT_USERNAME');
$password = env('MICROSOFT_PASSWORD');
$response = Http::asForm()->post("https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/token", [
'grant_type' => 'password',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'username' => $username,
'password' => $password,
'scope' => 'https://graph.microsoft.com/.default',
]);
if ($response->failed()) {
dd($response->body());
throw new \Exception('Failed to obtain access token: ' . $response->body());
}
return $response->json()['access_token'];
}
public static function addBlockers(mixed $blockers)
{
foreach ($blockers as $blocker) {
self::addBlocker($blocker);
}
}
private static function addBlocker(mixed $blocker)
{
$attendees = $blocker['attendees'];
// pre kazdeho cloveka z eventu, ktory je zaroven userom v TM vytvorime blocker
foreach ($attendees as $attendee) {
$user = User::where('email', $attendee['emailAddress']['address'])->first();
if ( ! $user) {
continue;
}
$blockerToInsert = [];
$blockerToInsert['office365_id'] = $blocker['id'];
$blockerToInsert['office365_change_key'] = $blocker['changeKey'];
$blockerToInsert['user_id'] = $user->id;
$blockerToInsert['name'] = $blocker['subject'];
$blockerToInsert['type'] = "office365_blocker";
$blockerToInsert['start'] = $blocker['start']['dateTime'];
$blockerToInsert['end'] = $blocker['end']['dateTime'];
$blockerToInsert['approved'] = 1;
$blockerToInsert['created_at'] = Carbon::now()->toDateTimeString();
$blockerToInsert['updated_at'] = Carbon::now()->toDateTimeString();
Blocker::insert($blockerToInsert);
}
}
public static function editBlockers(mixed $editedBlockers)
{
foreach ($editedBlockers as $editedBlocker) {
self::editBlocker($editedBlocker);
}
}
private static function editBlocker(mixed $editedBlocker)
{
$attendees = $editedBlocker['attendees'];
// pre kazdeho cloveka z eventu, ktory je zaroven userom v TM updatneme blocker
foreach ($attendees as $attendee) {
$user = User::where('email', $attendee['emailAddress']['address'])->first();
if ( ! $user) {
continue;
}
$blocker = Blocker::where('office365_id', $editedBlocker['id'])->where('user_id', $user->id)->first();
$blocker->update([
'office365_change_key' => $editedBlocker['changeKey'],
'name' => $editedBlocker['subject'],
'start' => $editedBlocker['start']['dateTime'],
'end' => $editedBlocker['end']['dateTime'],
'updated_at' => Carbon::now()->toDateTimeString(),
]);
}
}
public static function addSubtasks(mixed $newSubtasks)
{
foreach ($newSubtasks as $newSubtask) {
$project = Project::where('code', explode(' ', $newSubtask['subject'])[0])->first();
// ak existuje viac master taskov, pouzijeme posledny
$mastertask = MasterTask::where('project_id', $project->id)->latest()->first();
// ak neexistuje master task k danemu projektu, tak sa subtask neprida
if ( ! $mastertask) {
continue;
}
self::addSubtask($newSubtask, $mastertask);
}
}
private static function addSubtask(mixed $newSubtask, mixed $mastertask)
{
$attendees = $newSubtask['attendees'];
$subtasksToInsert = [];
$i = 0;
// pre kazdeho cloveka z eventu, ktory je zaroven userom v TM vytvorime subtask
foreach ($attendees as $attendee) {
$user = User::where('email', $attendee['emailAddress']['address'])->first();
$creator = User::where('email', $newSubtask['organizer']['emailAddress']['address'])->first();
if ( ! $user || ! $creator) {
continue;
}
$subtasksToInsert[$i]['user_id'] = $user->id;
// vymazem prve slovo z title, ktore je project code
$subtasksToInsert[$i]['title'] = substr($newSubtask['subject'],
strpos($newSubtask['subject'], ' ') + 1);
// estimated_time je rozdiel medzi end.dateTime a start.dateTime zakhruhleny na najblizsiu 0.5 hodinu
$subtasksToInsert[$i]['estimated_time'] = round((strtotime($newSubtask['end']['dateTime']) - strtotime($newSubtask['start']['dateTime'])) / 3600,
1);
$subtasksToInsert[$i]['tracked_time'] = 0;
$subtasksToInsert[$i]['created_by'] = $creator->id;
$subtasksToInsert[$i]['office365_id'] = $newSubtask['id'];
$subtasksToInsert[$i]['office365_change_key'] = $newSubtask['changeKey'];
$subtasksToInsert[$i]['type'] = 'office365';
$subtasksToInsert[$i]['description'] = $newSubtask['body']['content'];
$subtasksToInsert[$i]['deadline'] = $newSubtask['end']['dateTime'];
$subtasksToInsert[$i]['office365_location'] = $newSubtask['location']['displayName'];
$subtasksToInsert[$i]['is_finished'] = 0;
}
$subtasks = $mastertask->subtasks()->createMany($subtasksToInsert);
// vytvorenie timeblocks
foreach ($subtasks as $subtask) {
$subtask->syncTimeblocks([
[
'sub_task_id' => $subtask->id,
'start' => $newSubtask['start']['dateTime'],
'end' => $newSubtask['end']['dateTime'],
'is_finished' => 0,
]
]);
}
// manualne musim trigernut tuto operaciu, lebo cez Observer sa to nespusti - ten je nastaveny len na update subtasku
$mastertask->recalculateEstimatedTime();
}
public static function finishSubtasks(mixed $subtasks)
{
foreach ($subtasks as $subtask) {
// ukoncenie timeblocks
foreach ($subtask->timeblocks as $timeblock) {
$timeblock->update([
'is_finished' => 1,
]);
}
// pridanie odtrackovaneho casu
$subtask->syncTimesheets([
[
'sub_task_id' => $subtask->id,
'employee_id' => $subtask->user_id,
'time' => $subtask->estimated_time,
],
]);
$subtask->update([
'is_finished' => 1,
]);
}
// manualne musim trignernut tuto operaciu, lebo cez Observer sa to nespusti - ten je nastaveny len na update subtasku
$subtasks->first()->mastertask->recalculateTrackedTime();
}
}
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('blockers', function (Blueprint $table) {
$table->string('office365_id')->index()->nullable()->default(null)->after('intranet_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('blockers', function (Blueprint $table) {
//
});
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('blockers', function (Blueprint $table) {
$table->string('office365_change_key')->index()->nullable()->default(null)->after('office365_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('blockers', function (Blueprint $table) {
//
});
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('sub_tasks', function (Blueprint $table) {
$table->string('office365_id')->index()->nullable()->default(null)->after('id');
});
Schema::table('sub_tasks', function (Blueprint $table) {
$table->string('office365_change_key')->index()->nullable()->default(null)->after('office365_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('subtasks', function (Blueprint $table) {
//
});
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('master_tasks', function (Blueprint $table) {
$table->float('estimated_duration')->after('description')->comment('tento field je fixny a neupdatuje sa na zaklade subtaskov');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('master_task', function (Blueprint $table) {
//
});
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('master_tasks', function (Blueprint $table) {
$table->renameColumn('estimated_duration', 'pricequote_time');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('master_task', function (Blueprint $table) {
//
});
}
};
+4 -1
View File
@@ -14,7 +14,10 @@ use Illuminate\Support\Facades\Route;
*/ */
Route::get('/', function () { Route::get('/', function () {
return view('welcome'); });
Route::get('/run-office365', function () {
\Artisan::call('office365:sync');
}); });
Route::prefix('be')->group(function () { Route::prefix('be')->group(function () {