Merge branch 'main' of bitbucket.org:studiotem/jandl-taskmanager-app into production

# Conflicts:
#	app/dist/css/index.8b20f5d4.css
#	app/dist/index.html
This commit is contained in:
StudioTem committed 2025-05-05 11:00:00 +02:00
commit 082d8bc084
213 files changed
+20320 -1013

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;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
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();
// 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 = Office365Service::getBlockers_from_office_365_events($events);
$subtasks_from_office365 = Office365Service::getSubtasks_from_office_365_events($events);
Office365Service::addBlockers($blockers_from_office365);
Office365Service::editBlockers($blockers_from_office365);
Office365Service::removeBlockers($blockers_from_office365);
Office365Service::addSubtasks($subtasks_from_office365);
Office365Service::editSubtasks($subtasks_from_office365);
Office365Service::removeSubtasks($subtasks_from_office365);
return Command::SUCCESS;
}
}
+2
View File
@@ -31,6 +31,8 @@ class Kernel extends ConsoleKernel
$schedule->command('karat:sync-projects')->everyFiveMinutes();
$schedule->command('karat:sync-projects-name')->hourly();
$schedule->command('karat:sync-timesheets')->everyFiveMinutes();
$schedule->command('office365:sync')->everyFiveMinutes();
$schedule->command('office365:finish-subtasks')->hourly();
}
}
@@ -84,12 +84,13 @@ class MasterTaskController extends Controller
$created_by = User::getUserIdFromBearerToken($request->bearerToken());
$validator = Validator::make($request->all(), [
'data.name' => 'required',
'data.description' => 'required',
'data.duration' => 'required',
'data.deadline' => 'required',
'data.project_id' => 'required',
'data.employees' => 'required',
'data.name' => 'required',
'data.description' => 'required',
'data.duration' => 'required',
'data.deadline' => 'required',
'data.project_id' => 'required',
'data.employees' => 'required',
'data.estimated_duration' => 'required',
]);
if ($validator->fails()) {
@@ -107,12 +108,22 @@ class MasterTaskController extends Controller
}
}
// validaci na to, ci uz neexistuje master task pod tymto projektom
$existingMasterTask = MasterTask::where('project_id', $request->all()['data']['project_id'])->first();
if ($existingMasterTask) {
return response()->json([
'message' => 'Master task already exists for this project',
], 400);
}
// upratanie requestu, pretoze frontend pouziva inu nomenklaturu fieldov ako appka
$data['data'] = $request->all()['data'];
$data['data']['title'] = $request->all()['data']['name'];
$data['data']['estimated_time'] = $request->all()['data']['duration'];
$data['data']['created_by'] = $created_by;
$data['data'] = $request->all()['data'];
$data['data']['title'] = $request->all()['data']['name'];
$data['data']['estimated_time'] = $request->all()['data']['duration'];
$data['data']['pricequote_time'] = $request->all()['data']['estimated_duration'];
$data['data']['created_by'] = $created_by;
foreach ($data['data']['employees'] as $key => $employee) {
$data['data']['employees'][$key]['user_id'] = $employee['id'];
+17 -15
View File
@@ -10,26 +10,28 @@ class MasterTaskResource extends JsonResource
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
*
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->title,
'created_by' => $this->created_by,
'description' => $this->description,
'duration' => $this->estimated_time,
'time_worked' => $this->tracked_time,
'is_finished' => $this->is_finished,
'starts_at' => $this->created_at,
'deadline' => $this->deadline,
'project_code' => ($this->project) ? $this->project->code . ' ' . $this->project->name : null,
'team' => ($this->team) ?: null,
'employees' => UserResource::collection($this->usersOutsideTeam),
'subtasks' => SubTaskResource::collection($this->subtasks),
'files' => AttachmentResource::collection($this->attachments),
'color' => $this->color,
'id' => $this->id,
'name' => $this->title,
'created_by' => $this->created_by,
'description' => $this->description,
'duration' => $this->estimated_time,
'estimated_duration' => $this->pricequote_time,
'time_worked' => $this->tracked_time,
'is_finished' => $this->is_finished,
'starts_at' => $this->created_at,
'deadline' => $this->deadline,
'project_code' => ($this->project) ? $this->project->code . ' ' . $this->project->name : null,
'team' => ($this->team) ?: null,
'employees' => UserResource::collection($this->usersOutsideTeam),
'subtasks' => SubTaskResource::collection($this->subtasks),
'files' => AttachmentResource::collection($this->attachments),
'color' => $this->color,
];
}
}
+22 -20
View File
@@ -10,32 +10,34 @@ class SubTaskResource extends JsonResource
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
*
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'created_by' => $this->created_by,
'master_task' => $this->mastertask->title,
'id' => $this->id,
'type' => $this->type,
'created_by' => $this->created_by,
'master_task' => $this->mastertask->title,
'master_task_description' => $this->mastertask->description,
'master_task_deadline' => $this->mastertask->deadline,
'master_task_id' => $this->mastertask->id,
'description' => $this->description,
'project_code' => ($this->mastertask->project) ? $this->mastertask->project->code . ' ' . $this->mastertask->project->name : null,
'title' => $this->title,
'team_id' => ($this->mastertask->team) ? $this->mastertask->team->id : null,
'team' => $this->mastertask->team,
'employee_id' => $this->user->id,
'duration' => $this->estimated_time,
'spent_time' => $this->tracked_time,
'deadline' => $this->deadline,
'is_finished' => $this->is_finished,
'timeblocks' => TimeblockResource::collection($this->timeblocks),
'timesheets' => TimesheetResource::collection($this->timesheets),
'files' => AttachmentResource::collection($this->attachments->isNotEmpty() ? $this->attachments : $this->mastertask->attachments),
'color' => $this->mastertask->color,
'master_task_deadline' => $this->mastertask->deadline,
'master_task_id' => $this->mastertask->id,
'description' => $this->description,
'project_code' => ($this->mastertask->project) ? $this->mastertask->project->code . ' ' . $this->mastertask->project->name : null,
'title' => $this->title,
'team_id' => ($this->mastertask->team) ? $this->mastertask->team->id : null,
'team' => $this->mastertask->team,
'employee_id' => $this->user->id,
'duration' => $this->estimated_time,
'spent_time' => $this->tracked_time,
'deadline' => $this->deadline,
'office365_location' => $this->office365_location,
'is_finished' => $this->is_finished,
'timeblocks' => TimeblockResource::collection($this->timeblocks),
'timesheets' => TimesheetResource::collection($this->timesheets),
'files' => AttachmentResource::collection($this->attachments->isNotEmpty() ? $this->attachments : $this->mastertask->attachments),
'color' => $this->mastertask->color,
];
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Listeners;
use App\Events\MasterTaskEdited;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
class SendTrackedTimeReachingPriceQouteTimeNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param object $event
*
* @return void
*/
public function handle(MasterTaskEdited $event)
{
// neposiela sa, pokial tracked time neprekrocil 80% estimated time alebo bola uz notifikacia v minulosti poslana
if ($event->mastertask->tracked_time < $event->mastertask->pricequote_time * 0.8 || $event->mastertask->pricequote_time_notification_sent) {
return;
}
$receiver = User::find($event->mastertask->created_by);
// pripad ked bol user soft deletnuty
if ( ! $receiver) {
return;
}
// only send if email wasnt sent before
if ($event->mastertask->pricequote_time_email_sent) {
return;
}
Mail::to($receiver->email)->send(new \App\Mail\MasterTaskTrackedTimeReachingPricQouteTime($event->mastertask));
// updatnem tak, aby mi to nespustilo dalsi event - dostal by som email loop
$event->mastertask->withoutEvents(function () use ($event) {
$event->mastertask->update(['pricequote_time_notification_sent' => 1]);
});;
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Mail;
use App\Models\MasterTask;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class MasterTaskTrackedTimeReachingPricQouteTime extends Mailable
{
use Queueable, SerializesModels;
public $mastertask;
public $creator;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(MasterTask $mastertask)
{
$creator = \App\Models\User::find($mastertask->created_by);
$this->mastertask = $mastertask;
$this->creator = ($creator) ? $creator->firstname . ' ' . $creator->lastname : '';
}
/**
* Get the message envelope.
*
* @return \Illuminate\Mail\Mailables\Envelope
*/
public function envelope()
{
return new Envelope(
subject: 'Master Task ' . $this->mastertask->project->code . ' - ' . $this->mastertask->title . ' ma natrackovaných viac ako 80% odhadovaných hodín',
);
}
/**
* Get the message content definition.
*
* @return \Illuminate\Mail\Mailables\Content
*/
public function content()
{
return new Content(
view: 'emails.task.master_task_reaching_pricequote_time',
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments()
{
return [];
}
}
+15 -16
View File
@@ -12,6 +12,12 @@ class MasterTask extends Model
public $timestamps = true;
public $guarded = ['id'];
public static function generateMasterTaskColor()
{
// return random value from array
return collect(['#E9FFE5', '#F6ECD3', '#FDE1FF', '#FFC9C9', '#DADEF8', '#EDFFFE', '#FFDED7'])->random();
}
public function subtasks()
{
return $this->hasMany(SubTask::class);
@@ -22,11 +28,6 @@ class MasterTask extends Model
return $this->belongsTo(Project::class);
}
public function attachments()
{
return $this->hasMany(Attachment::class);
}
public function team()
{
return $this->belongsTo(Team::class);
@@ -38,12 +39,12 @@ class MasterTask extends Model
$users = $this->subtasks->pluck('user')->unique();
// ak nie je uvedeny ziaden team, tak sa vratia vsetci useri
if (!$this->team){
if ( ! $this->team) {
return $users;
}
return $users->filter(function ($user) {
return !in_array($this->team->id, $user->teams->pluck('id')->unique()->toArray());
return ! in_array($this->team->id, $user->teams->pluck('id')->unique()->toArray());
});
}
@@ -53,15 +54,9 @@ class MasterTask extends Model
return $this->subtasks->pluck('user')->unique();
}
public static function generateMasterTaskColor()
{
// return random value from array
return collect(['#E9FFE5', '#F6ECD3', '#FDE1FF', '#FFC9C9', '#DADEF8', '#EDFFFE', '#FFDED7'])->random();
}
public function deleteAttachments()
{
foreach ( $this->attachments as $attachment ) {
foreach ($this->attachments as $attachment) {
$attachment->deleteFromS3();
}
@@ -70,6 +65,11 @@ class MasterTask extends Model
return true;
}
public function attachments()
{
return $this->hasMany(Attachment::class);
}
public function recalculateEstimatedTime()
{
$this->estimated_time = $this->subtasks->sum('estimated_time');
@@ -80,12 +80,11 @@ class MasterTask extends Model
{
$trackedTime = 0.0;
foreach ( $this->subtasks as $subtask ) {
foreach ($this->subtasks as $subtask) {
$trackedTime += $subtask->timesheets->sum('time');
}
$this->tracked_time = $trackedTime;
$this->save();
}
}
+11 -10
View File
@@ -12,6 +12,7 @@ use App\Listeners\SendEditedMasterTaskNotification;
use App\Listeners\SendEditedSubTaskNotification;
use App\Listeners\SendFinishedTimeBlockNotification;
use App\Listeners\SendNewSubTaskEmailNotification;
use App\Listeners\SendTrackedTimeReachingPriceQouteTimeNotification;
use App\Models\MasterTask;
use App\Models\SubTask;
use App\Models\Timeblock;
@@ -21,7 +22,6 @@ use App\Observers\TimeBlockObserver;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
@@ -31,21 +31,22 @@ class EventServiceProvider extends ServiceProvider
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
Registered::class => [
SendEmailVerificationNotification::class,
],
SubTaskCreated::class => [
SubTaskCreated::class => [
SendNewSubTaskEmailNotification::class,
//LogEvent::class,
],
SubTaskDeleted::class => [
SubTaskDeleted::class => [
SendDeletedSubTaskNotification::class
],
SubTaskEdited::class => [
SubTaskEdited::class => [
SendEditedSubTaskNotification::class
],
MasterTaskEdited::class => [
SendEditedMasterTaskNotification::class
MasterTaskEdited::class => [
SendEditedMasterTaskNotification::class,
SendTrackedTimeReachingPriceQouteTimeNotification::class
],
TimeBlockFinished::class => [
SendFinishedTimeBlockNotification::class
@@ -59,9 +60,9 @@ class EventServiceProvider extends ServiceProvider
*/
public function boot()
{
MasterTask::observe( MasterTaskObserver::class);
SubTask::observe( SubTaskObserver::class);
Timeblock::observe( TimeBlockObserver::class);
MasterTask::observe(MasterTaskObserver::class);
SubTask::observe(SubTaskObserver::class);
Timeblock::observe(TimeBlockObserver::class);
}
/**
@@ -0,0 +1,521 @@
<?php
namespace App\Services\Office365;
use App\Mail\Error;
use App\Models\Blocker;
use App\Models\MasterTask;
use App\Models\Project;
use App\Models\SubTask;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
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'];
}
private 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()) {
throw new \Exception('Failed to obtain access token: ' . $response->body());
}
return $response->json()['access_token'];
}
public static function addBlockers(mixed $blockers_from_office365)
{
// 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'];
});
foreach ($newBlockers as $blocker) {
try {
self::addBlocker($blocker);
} catch (\Exception $e) {
// log error
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
}
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'] = Carbon::parse($blocker['start']['dateTime'])->setTimezone('Europe/Bratislava');
$blockerToInsert['end'] = Carbon::parse($blocker['end']['dateTime'])->setTimezone('Europe/Bratislava');
$blockerToInsert['approved'] = 1;
$blockerToInsert['created_at'] = Carbon::now()->toDateTimeString();
$blockerToInsert['updated_at'] = Carbon::now()->toDateTimeString();
Blocker::insert($blockerToInsert);
}
}
/**
* @param mixed $events
*
* @return mixed
*/
public static function getBlockers_from_office_365_events(mixed $events): mixed
{
return 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();
});
}
public static function editBlockers(mixed $blockers_from_office365)
{
// 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'];
});
foreach ($editedBlockers as $editedBlocker) {
try {
self::editBlocker($editedBlocker);
} catch (\Exception $e) {
// log error
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
}
private static function editBlocker(mixed $editedBlocker)
{
$attendees = $editedBlocker['attendees'];
// ak sa v nasej DB pod blockerom nachadza nejaky user, ktory sa uz nenachadza medzi attendees, tak mu tento blocker vymazeme
$blockersToDelete = Blocker::where('office365_id', $editedBlocker['id'])->get()->filter(function ($blocker) use
(
$attendees
) {
$event = collect($attendees)->firstWhere('emailAddress.address', $blocker->user->email);
return ! $event;
});
foreach ($blockersToDelete as $blocker) {
$blocker->delete();
}
// 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();
// ak sa nenachadza blocker, znamena to, ze je to novy user medzi attendees, ktory este nema u nas vytvoreny blocker. tak ho vytvorime
if ( ! $blocker) {
Blocker::create([
'office365_id' => $editedBlocker['id'],
'office365_change_key' => $editedBlocker['changeKey'],
'user_id' => $user->id,
'name' => $editedBlocker['subject'],
'type' => "office365_blocker",
'start' => Carbon::parse($editedBlocker['start']['dateTime'])->setTimezone('Europe/Bratislava'),
'end' => Carbon::parse($editedBlocker['end']['dateTime'])->setTimezone('Europe/Bratislava'),
'approved' => 1,
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString()
]
);
} else {
$blocker->update([
'office365_change_key' => $editedBlocker['changeKey'],
'name' => $editedBlocker['subject'],
'start' => Carbon::parse($editedBlocker['start']['dateTime'])->setTimezone('Europe/Bratislava'),
'end' => Carbon::parse($editedBlocker['end']['dateTime'])->setTimezone('Europe/Bratislava'),
'updated_at' => Carbon::now()->toDateTimeString(),
]);
}
}
}
public static function addSubtasks(mixed $subtasks_from_office365)
{
$newSubtasks = array_filter($subtasks_from_office365, function ($event) {
return ! SubTask::where('office365_id', $event['id'])->exists() && ! $event['isCancelled'];
});
foreach ($newSubtasks as $newSubtask) {
try {
$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);
} catch (\Exception $e) {
// log error
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
}
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. ak title ma len 1 slovo (project code), tak sa ako title vlozi "No title"
$subtasksToInsert[$i]['title'] = ( ! str_contains($newSubtask['subject'],
' ')) ? 'No 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' => Carbon::parse($newSubtask['start']['dateTime'])->setTimezone('Europe/Bratislava'),
'end' => Carbon::parse($newSubtask['end']['dateTime'])->setTimezone('Europe/Bratislava'),
'is_finished' => 0,
]
]);
}
// manualne musim trigernut tuto operaciu, lebo cez Observer sa to nespusti - ten je nastaveny len na update subtasku
$mastertask->recalculateEstimatedTime();
}
/**
* @param mixed $events
*
* @return mixed
*/
public static function getSubtasks_from_office_365_events(mixed $events): mixed
{
return 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();
});
}
public static function editSubtasks(mixed $subtasks_from_office365)
{
// get edited subtasks - the ones, that has different changeKey from our database
$editedSubtasks = array_filter($subtasks_from_office365, function ($event) {
$subtask = SubTask::where('office365_id', $event['id'])->first();
return $subtask && $subtask->office365_change_key !== $event['changeKey'];
});
foreach ($editedSubtasks as $editedSubtask) {
try {
self::editSubtask($editedSubtask);
} catch (\Exception $e) {
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
}
private static function editSubtask(mixed $editedSubtask)
{
$attendees = $editedSubtask['attendees'];
// vrati subtasky pre userov, ktori sa uz nenachadzaju v evente, ale v nasej databaze tento subtask maju. ale iba v pripade, ak ich subtasky este nie su ukoncene (is_finished != 1)
$subtasksToDelete = self::getSubtasksToDeleteFromEditedEvents($editedSubtask['id'], $attendees);
foreach ($subtasksToDelete as $subtaskToDelete) {
self::removeSubtask($subtaskToDelete);
}
// novym ucastnikom sa klasicky vytvori subtask ako v pripade noveho subtasku. pre 1 subtask existuje iba 1 user.
self::createNewSubtaskToNewAttendee($attendees, $editedSubtask);
// existujucim ucastnikom sa updatne subtask
foreach ($attendees as $attendee) {
$idOfUserFromOffice365 = User::where('email', $attendee['emailAddress']['address'])->first();
// if user doesnt exist in our database, we skip it
if ( ! $idOfUserFromOffice365) {
continue;
}
$subtask = SubTask::where('office365_id', $editedSubtask['id'])->where('user_id',
$idOfUserFromOffice365->id)->first();
if ( ! $subtask) {
continue;
}
$subtask->update([
'office365_change_key' => $editedSubtask['changeKey'],
'title' => substr($editedSubtask['subject'], strpos($editedSubtask['subject'], ' ') + 1),
'estimated_time' => round((strtotime($editedSubtask['end']['dateTime']) - strtotime($editedSubtask['start']['dateTime'])) / 3600,
1),
'description' => $editedSubtask['body']['content'],
'deadline' => $editedSubtask['end']['dateTime'],
'office365_location' => $editedSubtask['location']['displayName'],
]);
$oldTimeblock = $subtask->timeblocks->first();
// ak sa zmenilo trvanie alebo casy subtasku, tak sa updatne aj timeblock
if ($oldTimeblock['start'] != Carbon::parse($editedSubtask['start']['dateTime'])->setTimezone('Europe/Bratislava') || $oldTimeblock['end'] != Carbon::parse($editedSubtask['end']['dateTime'])->setTimezone('Europe/Bratislava')) {
$subtask->syncTimeblocks([
[
'sub_task_id' => $subtask->id,
'start' => Carbon::parse($editedSubtask['start']['dateTime'])->setTimezone('Europe/Bratislava'),
'end' => Carbon::parse($editedSubtask['end']['dateTime'])->setTimezone('Europe/Bratislava'),
'is_finished' => 0,
]
]);
}
}
// manualne musim trignernut tuto operaciu, lebo cez Observer sa to nespusti - ten je nastaveny len na update subtasku
Subtask::where('office365_id', $editedSubtask['id'])->first()->mastertask->recalculateEstimatedTime();
}
private static function getSubtasksToDeleteFromEditedEvents(
$id,
mixed $attendees
): \Illuminate\Support\Collection|array|\LaravelIdea\Helper\App\Models\_IH_SubTask_C {
$subtasksToDelete = SubTask::where('is_finished', 0)->where('office365_id',
$id)->get()->filter(function ($subtask) use (
$attendees
) {
$event = collect($attendees)->firstWhere('emailAddress.address', $subtask->user->email);
return ! $event;
});
return $subtasksToDelete;
}
/**
* @param array|\LaravelIdea\Helper\App\Models\_IH_SubTask_C|\Illuminate\Support\Collection $removedSubtasks
*
* @return void
*/
private static function removeSubtask($subtask
): void {
// vymazanie timeblockov
foreach ($subtask->timeblocks as $timeblock) {
$timeblock->delete();
}
// vymazanie timesheetov
foreach ($subtask->timesheets as $timesheet) {
$timesheet->delete();
}
$subtask->delete();
}
/**
* @param mixed $attendees
* @param mixed $editedSubtask
*
* @return void
*/
private static function createNewSubtaskToNewAttendee(mixed $attendees, mixed $editedSubtask): void
{
$newAttendees = array_filter($attendees, function ($attendee) use ($editedSubtask) {
$idsOfAttendees = SubTask::where('office365_id', $editedSubtask['id'])->get()->pluck('user_id')->toArray();
$idOfUserFromOffice365 = User::where('email', $attendee['emailAddress']['address'])->first();
// if user doesnt exist in our database, we skip it
if ( ! $idOfUserFromOffice365) {
return false;
}
return ! in_array($idOfUserFromOffice365->id, $idsOfAttendees);
});
// nakopiruj subtask tak, ze bude obsahovat iba newAttendees
$editedSubtaskWithOnlyNewAttendees = $editedSubtask;
$editedSubtaskWithOnlyNewAttendees['attendees'] = $newAttendees;
$project = Project::where('code', explode(' ', $editedSubtask['subject'])[0])->first();
// ak existuje viac master taskov, pouzijeme posledny
$mastertask = MasterTask::where('project_id', $project->id)->latest()->first();
self::addSubtask($editedSubtaskWithOnlyNewAttendees, $mastertask);
}
public static function removeBlockers(mixed $blockers_from_office365)
{
// 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'];
});
$removedBlockers->each(function ($blocker) {
try {
$blocker->delete();
} catch (\Exception $e) {
// log error
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
});
}
/**
* @param $id
* @param mixed $attendees
*
* @return SubTask[]|\Illuminate\Support\Collection|\LaravelIdea\Helper\App\Models\_IH_SubTask_C
*/
public static function removeSubtasks(mixed $subtasks_from_office365)
{
// get all canceled subtasks - the ones, that are in our database and in the response they have isCancelled => true
$removedSubtasks = SubTask::where('is_finished', 0)->whereNotNull('office365_id')->get()->filter(function (
$subtask
) use (
$subtasks_from_office365
) {
$event = collect($subtasks_from_office365)->firstWhere('id', $subtask->office365_id);
return $event && $event['isCancelled'];
});
foreach ($removedSubtasks as $removed_subtask) {
try {
self::removeSubtask($removed_subtask);
} catch (\Exception $e) {
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
}
public static function finishSubtasks(mixed $subtasks)
{
foreach ($subtasks as $subtask) {
try {
// 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,
]);
} catch (\Exception $e) {
Mail::to('feher@studiotem.com')->send(new Error($e));
\Log::error($e->getMessage());
}
}
// manualne musim trignernut tuto operaciu, lebo cez Observer sa to nespusti - ten je nastaveny len na update subtasku
$subtasks->first()->mastertask->recalculateTrackedTime();
}
}