1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 21:22:58 +01:00
invoiceninja/app/Jobs/Cron/UpdateCalculatedFields.php

100 lines
2.4 KiB
PHP
Raw Normal View History

2023-04-04 13:34:01 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Jobs\Cron;
use App\Libraries\MultiDB;
2023-10-26 04:57:44 +02:00
use App\Models\Project;
2023-04-04 13:34:01 +02:00
use Illuminate\Foundation\Bus\Dispatchable;
2023-10-26 04:57:44 +02:00
use Illuminate\Support\Facades\Auth;
2023-04-04 13:34:01 +02:00
class UpdateCalculatedFields
{
use Dispatchable;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* @return void
*/
public function handle() : void
{
nlog("Updating calculated fields");
2023-05-04 01:42:42 +02:00
Auth::logout();
2023-04-04 13:34:01 +02:00
if (! config('ninja.db.multi_db_enabled')) {
2023-10-26 04:57:44 +02:00
Project::query()->with('tasks')->whereHas('tasks', function ($query) {
$query->where('updated_at', '>', now()->subHours(2));
2023-07-26 11:00:47 +02:00
})
2023-04-04 13:34:01 +02:00
->cursor()
->each(function ($project) {
$project->current_hours = $this->calculateDuration($project);
$project->save();
2023-10-26 04:57:44 +02:00
});
2023-04-04 13:34:01 +02:00
} else {
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
2023-10-26 04:57:44 +02:00
Project::query()->with('tasks')->whereHas('tasks', function ($query) {
2023-07-26 11:00:47 +02:00
$query->where('updated_at', '>', now()->subHours(2));
2023-10-26 04:57:44 +02:00
})
->cursor()
->each(function ($project) {
$project->current_hours = $this->calculateDuration($project);
$project->save();
});
2023-04-04 13:34:01 +02:00
}
}
}
private function calculateDuration($project): int
{
$duration = 0;
$project->tasks->each(function ($task) use (&$duration) {
2023-10-27 10:30:42 +02:00
if(is_iterable(json_decode($task->time_log) )) {
foreach(json_decode($task->time_log) as $log) {
2023-04-04 13:34:01 +02:00
2023-10-26 04:57:44 +02:00
$start_time = $log[0];
$end_time = $log[1] == 0 ? time() : $log[1];
2023-04-04 13:34:01 +02:00
2023-10-26 04:57:44 +02:00
$duration += $end_time - $start_time;
2023-04-04 13:34:01 +02:00
2023-10-26 04:57:44 +02:00
}
2023-04-04 13:34:01 +02:00
}
2023-04-04 13:34:01 +02:00
});
return round(($duration/60/60), 0);
2023-04-04 13:34:01 +02:00
}
}