mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-08-08 00:02:15 +01:00
Add spend_time to projects and tasks
This commit is contained in:
committed by
Gregor Vostrak
parent
2e8da98287
commit
bff766d363
@@ -13,9 +13,12 @@ use App\Http\Requests\V1\TimeEntry\TimeEntryUpdateMultipleRequest;
|
||||
use App\Http\Requests\V1\TimeEntry\TimeEntryUpdateRequest;
|
||||
use App\Http\Resources\V1\TimeEntry\TimeEntryCollection;
|
||||
use App\Http\Resources\V1\TimeEntry\TimeEntryResource;
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\TimeEntryAggregationService;
|
||||
use App\Service\TimeEntryFilter;
|
||||
@@ -215,7 +218,16 @@ class TimeEntryController extends Controller
|
||||
throw new TimeEntryStillRunningApiException;
|
||||
}
|
||||
|
||||
$client = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id'))->client : null;
|
||||
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
|
||||
$client = $project?->client;
|
||||
$task = $request->input('task_id') !== null ? $project->tasks()->findOrFail((string) $request->input('task_id')) : null;
|
||||
|
||||
if ($project !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
$timeEntry = new TimeEntry;
|
||||
$timeEntry->fill($request->validated());
|
||||
@@ -250,16 +262,38 @@ class TimeEntryController extends Controller
|
||||
throw new TimeEntryCanNotBeRestartedApiException;
|
||||
}
|
||||
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
$project = null;
|
||||
if ($request->has('project_id')) {
|
||||
$client = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id'))->client : null;
|
||||
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
|
||||
$client = $project?->client;
|
||||
$timeEntry->client()->associate($client);
|
||||
}
|
||||
$task = null;
|
||||
if ($request->has('task_id')) {
|
||||
$task = $request->input('task_id') !== null ? Task::findOrFail((string) $request->input('task_id')) : null;
|
||||
}
|
||||
|
||||
$timeEntry->fill($request->validated());
|
||||
$timeEntry->description = $request->input('description', $timeEntry->description) ?? '';
|
||||
$timeEntry->setComputedAttributeValue('billable_rate');
|
||||
$timeEntry->save();
|
||||
|
||||
if ($oldProject !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($oldProject);
|
||||
}
|
||||
if ($oldTask !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($oldTask);
|
||||
}
|
||||
if ($project !== null && ($oldProject === null || $project->isNot($oldProject))) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null && ($oldTask === null || $task->isNot($oldTask))) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
return new TimeEntryResource($timeEntry);
|
||||
}
|
||||
|
||||
@@ -279,6 +313,10 @@ class TimeEntryController extends Controller
|
||||
|
||||
$timeEntries = TimeEntry::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->with([
|
||||
'project',
|
||||
'task',
|
||||
])
|
||||
->whereIn('id', $ids)
|
||||
->get();
|
||||
|
||||
@@ -288,13 +326,20 @@ class TimeEntryController extends Controller
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
$project = null;
|
||||
$client = null;
|
||||
$overwriteClient = false;
|
||||
if ($request->has('changes.project_id')) {
|
||||
$client = $request->input('changes.project_id') !== null ? Project::findOrFail((string) $request->input('changes.project_id'))->client : null;
|
||||
$project = $request->input('changes.project_id') !== null ? Project::findOrFail((string) $request->input('changes.project_id')) : null;
|
||||
$client = $project?->client;
|
||||
$overwriteClient = true;
|
||||
}
|
||||
|
||||
$task = null;
|
||||
if ($request->has('changes.task_id')) {
|
||||
$task = $request->input('changes.task_id') !== null ? Task::findOrFail((string) $request->input('changes.task_id')) : null;
|
||||
}
|
||||
|
||||
$success = new Collection;
|
||||
$error = new Collection;
|
||||
|
||||
@@ -313,12 +358,28 @@ class TimeEntryController extends Controller
|
||||
continue;
|
||||
|
||||
}
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
$timeEntry->fill($changes);
|
||||
if ($overwriteClient) {
|
||||
$timeEntry->client()->associate($client);
|
||||
}
|
||||
$timeEntry->setComputedAttributeValue('billable_rate');
|
||||
$timeEntry->save();
|
||||
if ($oldTask !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($oldTask);
|
||||
}
|
||||
if ($oldProject !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($oldProject);
|
||||
}
|
||||
if ($project !== null && ($oldProject === null || $project->isNot($oldProject))) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null && ($oldTask === null || $task->isNot($oldTask))) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
$success->push($id);
|
||||
}
|
||||
|
||||
@@ -343,8 +404,18 @@ class TimeEntryController extends Controller
|
||||
$this->checkPermission($organization, 'time-entries:delete:all', $timeEntry);
|
||||
}
|
||||
|
||||
$project = $timeEntry->project;
|
||||
$task = $timeEntry->task;
|
||||
|
||||
$timeEntry->delete();
|
||||
|
||||
if ($project !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
return response()
|
||||
->json(null, 204);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,8 @@ class ProjectResource extends BaseResource
|
||||
'is_billable' => $this->resource->is_billable,
|
||||
/** @var int|null $estimated_time Estimated time in seconds */
|
||||
'estimated_time' => $this->resource->estimated_time,
|
||||
/** @var int $spent_time Spent time on this project in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
'spent_time' => $this->resource->spent_time,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ class TaskResource extends BaseResource
|
||||
'project_id' => $this->resource->project_id,
|
||||
/** @var int|null $estimated_time Estimated time in seconds */
|
||||
'estimated_time' => $this->resource->estimated_time,
|
||||
/** @var int $spent_time Spent time on this task in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
'spent_time' => $this->resource->spent_time,
|
||||
/** @var string $created_at When the tag was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at When the tag was last updated */
|
||||
|
||||
44
app/Jobs/RecalculateSpentTimeForProject.php
Normal file
44
app/Jobs/RecalculateSpentTimeForProject.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Project;
|
||||
use Exception;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class RecalculateSpentTimeForProject implements ShouldQueue
|
||||
{
|
||||
use Dispatchable;
|
||||
use InteractsWithQueue;
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
public Project $project;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*/
|
||||
public function __construct(Project $project)
|
||||
{
|
||||
$this->project = $project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
$this->project->setComputedAttributeValue('spent_time');
|
||||
if ($this->project->isDirty()) {
|
||||
$this->project->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
44
app/Jobs/RecalculateSpentTimeForTask.php
Normal file
44
app/Jobs/RecalculateSpentTimeForTask.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Task;
|
||||
use Exception;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class RecalculateSpentTimeForTask implements ShouldQueue
|
||||
{
|
||||
use Dispatchable;
|
||||
use InteractsWithQueue;
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
public Task $task;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*/
|
||||
public function __construct(Task $task)
|
||||
{
|
||||
$this->task = $task;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
$this->task->setComputedAttributeValue('spent_time');
|
||||
if ($this->task->isDirty()) {
|
||||
$this->task->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Korridor\LaravelComputedAttributes\ComputedAttributes;
|
||||
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
|
||||
/**
|
||||
@@ -28,6 +30,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property bool $is_billable
|
||||
* @property-read bool $is_archived
|
||||
* @property int|null $estimated_time
|
||||
* @property int $spent_time
|
||||
* @property Carbon|null $archived_at
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
@@ -41,6 +44,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
*/
|
||||
class Project extends Model implements AuditableContract
|
||||
{
|
||||
use ComputedAttributes;
|
||||
use CustomAuditable;
|
||||
|
||||
/** @use HasFactory<ProjectFactory> */
|
||||
@@ -58,6 +62,7 @@ class Project extends Model implements AuditableContract
|
||||
'color' => 'string',
|
||||
'archived_at' => 'datetime',
|
||||
'estimated_time' => 'integer',
|
||||
'spent_time' => 'integer',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -69,6 +74,68 @@ class Project extends Model implements AuditableContract
|
||||
'is_billable' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that are computed. (f.e. for performance reasons)
|
||||
* These attributes can be regenerated at any time.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected array $computed = [
|
||||
'spent_time',
|
||||
];
|
||||
|
||||
/**
|
||||
* Attributes to exclude from the Audit.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $auditExclude = [
|
||||
'spent_time',
|
||||
];
|
||||
|
||||
public function getSpentTimeComputed(): ?int
|
||||
{
|
||||
if ($this->hasAttribute('spent_time_computed')) {
|
||||
return $this->attributes['spent_time_computed'] === null ? 0 : (int) $this->attributes['spent_time_computed'];
|
||||
} else {
|
||||
/** @var object{ spent_time: string } $result */
|
||||
$result = $this->timeEntries()
|
||||
->whereNotNull('end')
|
||||
->selectRaw('sum(extract(epoch from ("end" - start))) as spent_time')
|
||||
->first();
|
||||
|
||||
return (int) $result->spent_time;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This scope will be applied during the computed property generation with artisan computed-attributes:generate.
|
||||
*
|
||||
* @param Builder<Project> $builder
|
||||
* @param array<string> $attributes Attributes that will be generated.
|
||||
* @return Builder<Project>
|
||||
*/
|
||||
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
|
||||
{
|
||||
if (in_array('spent_time', $attributes, true)) {
|
||||
$builder->withAggregate('timeEntries as spent_time_computed', DB::raw('extract(epoch from ("end" - start))'), 'sum');
|
||||
}
|
||||
|
||||
return $builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* This scope will be applied during the computed property validation with artisan computed-attributes:validate.
|
||||
*
|
||||
* @param Builder<Project> $builder
|
||||
* @param array<string> $attributes Attributes that will be validated.
|
||||
* @return Builder<Project>
|
||||
*/
|
||||
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
|
||||
{
|
||||
return $this->scopeComputedAttributesGenerate($builder, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Organization, Project>
|
||||
*/
|
||||
|
||||
@@ -15,6 +15,8 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Korridor\LaravelComputedAttributes\ComputedAttributes;
|
||||
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
|
||||
/**
|
||||
@@ -24,6 +26,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property string $organization_id
|
||||
* @property Carbon|null $done_at
|
||||
* @property int|null $estimated_time
|
||||
* @property int $spent_time
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
* @property-read Project $project
|
||||
@@ -35,6 +38,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
*/
|
||||
class Task extends Model implements AuditableContract
|
||||
{
|
||||
use ComputedAttributes;
|
||||
use CustomAuditable;
|
||||
|
||||
/** @use HasFactory<TaskFactory> */
|
||||
@@ -53,6 +57,68 @@ class Task extends Model implements AuditableContract
|
||||
'done_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that are computed. (f.e. for performance reasons)
|
||||
* These attributes can be regenerated at any time.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected array $computed = [
|
||||
'spent_time',
|
||||
];
|
||||
|
||||
/**
|
||||
* Attributes to exclude from the Audit.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $auditExclude = [
|
||||
'spent_time',
|
||||
];
|
||||
|
||||
public function getSpentTimeComputed(): ?int
|
||||
{
|
||||
if ($this->hasAttribute('spent_time_computed')) {
|
||||
return $this->attributes['spent_time_computed'] === null ? 0 : (int) $this->attributes['spent_time_computed'];
|
||||
} else {
|
||||
/** @var object{ spent_time: string } $result */
|
||||
$result = $this->timeEntries()
|
||||
->whereNotNull('end')
|
||||
->selectRaw('sum(extract(epoch from ("end" - start))) as spent_time')
|
||||
->first();
|
||||
|
||||
return (int) $result->spent_time;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This scope will be applied during the computed property generation with artisan computed-attributes:generate.
|
||||
*
|
||||
* @param Builder<Task> $builder
|
||||
* @param array<string> $attributes Attributes that will be generated.
|
||||
* @return Builder<Task>
|
||||
*/
|
||||
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
|
||||
{
|
||||
if (in_array('spent_time', $attributes, true)) {
|
||||
$builder->withAggregate('timeEntries as spent_time_computed', DB::raw('extract(epoch from ("end" - start))'), 'sum');
|
||||
}
|
||||
|
||||
return $builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* This scope will be applied during the computed property validation with artisan computed-attributes:validate.
|
||||
*
|
||||
* @param Builder<Task> $builder
|
||||
* @param array<string> $attributes Attributes that will be validated.
|
||||
* @return Builder<Task>
|
||||
*/
|
||||
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
|
||||
{
|
||||
return $this->scopeComputedAttributesGenerate($builder, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Project, Task>
|
||||
*/
|
||||
|
||||
@@ -81,6 +81,15 @@ class TimeEntry extends Model implements AuditableContract
|
||||
'billable_rate',
|
||||
];
|
||||
|
||||
/**
|
||||
* Attributes to exclude from the Audit.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $auditExclude = [
|
||||
'billable_rate',
|
||||
];
|
||||
|
||||
public function getBillableRateComputed(): ?int
|
||||
{
|
||||
return app(BillableRateService::class)->getBillableRateForTimeEntry($this);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('projects', function (Blueprint $table): void {
|
||||
$table->integer('spent_time')->unsigned()->default(0);
|
||||
});
|
||||
Schema::table('tasks', function (Blueprint $table): void {
|
||||
$table->integer('spent_time')->unsigned()->default(0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('projects', function (Blueprint $table): void {
|
||||
$table->dropColumn('spent_time');
|
||||
});
|
||||
Schema::table('tasks', function (Blueprint $table): void {
|
||||
$table->dropColumn('spent_time');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -7,6 +7,8 @@ namespace Tests\Unit\Endpoint\Api\V1;
|
||||
use App\Enums\Role;
|
||||
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
|
||||
use App\Http\Controllers\Api\V1\TimeEntryController;
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
use App\Models\Project;
|
||||
@@ -16,6 +18,7 @@ use App\Models\TimeEntry;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Testing\Fluent\AssertableJson;
|
||||
use Laravel\Passport\Passport;
|
||||
@@ -1050,6 +1053,45 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_create_endpoint_recalculates_project_and_task_spent_time_if_time_entry_has_project_and_task(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = $this->createUserWithPermission([
|
||||
'time-entries:create:own',
|
||||
]);
|
||||
$project = Project::factory()->forOrganization($data->organization)->create();
|
||||
$task = Task::factory()->forOrganization($data->organization)->forProject($project)->create();
|
||||
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)->forProject($project)->forTask($task)->create();
|
||||
$timeEntryFake = TimeEntry::factory()->forOrganization($data->organization)->make();
|
||||
Passport::actingAs($data->user);
|
||||
Queue::fake([
|
||||
RecalculateSpentTimeForProject::class,
|
||||
RecalculateSpentTimeForTask::class,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
|
||||
'description' => $timeEntryFake->description,
|
||||
'billable' => $timeEntryFake->billable,
|
||||
'start' => Carbon::now()->toIso8601ZuluString(),
|
||||
'end' => Carbon::now()->addHour()->toIso8601ZuluString(),
|
||||
'member_id' => $data->member->getKey(),
|
||||
'project_id' => $project->getKey(),
|
||||
'task_id' => $task->getKey(),
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(201);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, 1);
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, 1);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, function (RecalculateSpentTimeForProject $job) use ($project): bool {
|
||||
return $job->project->is($project);
|
||||
});
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, function (RecalculateSpentTimeForTask $job) use ($task): bool {
|
||||
return $job->task->is($task);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_update_endpoint_fails_if_user_has_no_permission_to_update_own_time_entries(): void
|
||||
{
|
||||
// Arrange
|
||||
@@ -1385,6 +1427,82 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_endpoint_recalculates_project_and_task_spend_time_after_updating_time_entry_settings_a_project_and_a_task(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = $this->createUserWithPermission([
|
||||
'time-entries:update:own',
|
||||
]);
|
||||
$project = Project::factory()->forOrganization($data->organization)->create();
|
||||
$task = Task::factory()->forOrganization($data->organization)->forProject($project)->create();
|
||||
$timeEntry = TimeEntry::factory()->forOrganization($data->organization)->forProject(null)->forTask(null)->forMember($data->member)->create();
|
||||
TimeEntry::factory()->forOrganization($data->organization)->make();
|
||||
Passport::actingAs($data->user);
|
||||
Queue::fake([
|
||||
RecalculateSpentTimeForProject::class,
|
||||
RecalculateSpentTimeForTask::class,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->putJson(route('api.v1.time-entries.update', [$data->organization->getKey(), $timeEntry->getKey()]), [
|
||||
'project_id' => $project->getKey(),
|
||||
'task_id' => $task->getKey(),
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, 1);
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, 1);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForProject $job) use ($project): bool {
|
||||
return $job->project->is($project);
|
||||
}, 1);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForTask $job) use ($task): bool {
|
||||
return $job->task->is($task);
|
||||
}, 1);
|
||||
}
|
||||
|
||||
public function test_update_endpoint_recalculates_project_and_task_spend_time_after_updating_time_entry_settings_a_new_project_and_a_new_task(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = $this->createUserWithPermission([
|
||||
'time-entries:update:own',
|
||||
]);
|
||||
$oldProject = Project::factory()->forOrganization($data->organization)->create();
|
||||
$oldTask = Task::factory()->forOrganization($data->organization)->forProject($oldProject)->create();
|
||||
$timeEntry = TimeEntry::factory()->forOrganization($data->organization)->forProject($oldProject)->forTask($oldTask)->forMember($data->member)->create();
|
||||
$project = Project::factory()->forOrganization($data->organization)->create();
|
||||
$task = Task::factory()->forOrganization($data->organization)->forProject($project)->create();
|
||||
TimeEntry::factory()->forOrganization($data->organization)->make();
|
||||
Passport::actingAs($data->user);
|
||||
Queue::fake([
|
||||
RecalculateSpentTimeForProject::class,
|
||||
RecalculateSpentTimeForTask::class,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->putJson(route('api.v1.time-entries.update', [$data->organization->getKey(), $timeEntry->getKey()]), [
|
||||
'project_id' => $project->getKey(),
|
||||
'task_id' => $task->getKey(),
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, 2);
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, 2);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForProject $job) use ($project): bool {
|
||||
return $job->project->is($project);
|
||||
}, 1);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForProject $job) use ($oldProject): bool {
|
||||
return $job->project->is($oldProject);
|
||||
}, 1);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForTask $job) use ($task): bool {
|
||||
return $job->task->is($task);
|
||||
}, 1);
|
||||
Queue::assertPushed(function (RecalculateSpentTimeForTask $job) use ($oldTask): bool {
|
||||
return $job->task->is($oldTask);
|
||||
}, 1);
|
||||
}
|
||||
|
||||
public function test_destroy_endpoint_fails_if_user_tries_to_delete_time_entry_in_organization_that_they_does_belong_to(): void
|
||||
{
|
||||
// Arrange
|
||||
@@ -1493,6 +1611,68 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_destroy_endpoint_recalculates_project_and_task_spend_time_after_deleting_time_entry(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = $this->createUserWithPermission([
|
||||
'time-entries:delete:own',
|
||||
]);
|
||||
$project = Project::factory()->forOrganization($data->organization)->create();
|
||||
$task = Task::factory()->forOrganization($data->organization)->create();
|
||||
$timeEntry = TimeEntry::factory()->forOrganization($data->organization)->forProject($project)->forTask($task)->forMember($data->member)->create();
|
||||
$project = $timeEntry->project;
|
||||
$task = $timeEntry->task;
|
||||
Passport::actingAs($data->user);
|
||||
Queue::fake([
|
||||
RecalculateSpentTimeForProject::class,
|
||||
RecalculateSpentTimeForTask::class,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->deleteJson(route('api.v1.time-entries.destroy', [$data->organization->getKey(), $timeEntry->getKey()]));
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(204);
|
||||
$response->assertNoContent();
|
||||
$this->assertDatabaseMissing(TimeEntry::class, [
|
||||
'id' => $timeEntry->getKey(),
|
||||
]);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, 1);
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, 1);
|
||||
Queue::assertPushed(RecalculateSpentTimeForProject::class, function (RecalculateSpentTimeForProject $job) use ($project) {
|
||||
return $job->project->is($project);
|
||||
});
|
||||
Queue::assertPushed(RecalculateSpentTimeForTask::class, function (RecalculateSpentTimeForTask $job) use ($task) {
|
||||
return $job->task->is($task);
|
||||
});
|
||||
}
|
||||
|
||||
public function test_destroy_endpoint_does_not_recalculate_project_and_task_spend_time_after_deleting_time_entry_if_time_entry_had_no_project_and_task(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = $this->createUserWithPermission([
|
||||
'time-entries:delete:own',
|
||||
]);
|
||||
$timeEntry = TimeEntry::factory()->forOrganization($data->organization)->forProject(null)->forTask(null)->forMember($data->member)->create();
|
||||
Passport::actingAs($data->user);
|
||||
Queue::fake([
|
||||
RecalculateSpentTimeForProject::class,
|
||||
RecalculateSpentTimeForTask::class,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->deleteJson(route('api.v1.time-entries.destroy', [$data->organization->getKey(), $timeEntry->getKey()]));
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(204);
|
||||
$response->assertNoContent();
|
||||
$this->assertDatabaseMissing(TimeEntry::class, [
|
||||
'id' => $timeEntry->getKey(),
|
||||
]);
|
||||
Queue::assertNotPushed(RecalculateSpentTimeForProject::class);
|
||||
Queue::assertNotPushed(RecalculateSpentTimeForTask::class);
|
||||
}
|
||||
|
||||
public function test_update_multiple_endpoint_fails_if_user_has_no_permission_to_update_own_time_entries_or_all_time_entries(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
58
tests/Unit/Jobs/RecalculateSpentTimeForProjectTest.php
Normal file
58
tests/Unit/Jobs/RecalculateSpentTimeForProjectTest.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Jobs;
|
||||
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Models\Project;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
|
||||
class RecalculateSpentTimeForProjectTest extends TestCaseWithDatabase
|
||||
{
|
||||
public function test_recalculates_spent_time_for_project(): void
|
||||
{
|
||||
// Arrange
|
||||
$project = Project::factory()->create([
|
||||
'spent_time' => 0,
|
||||
]);
|
||||
TimeEntry::factory()->startWithDuration(now(), 10)->forProject($project)->create();
|
||||
TimeEntry::factory()->startWithDuration(now(), 11)->forProject($project)->create();
|
||||
|
||||
$project->refresh();
|
||||
$recalculateSpentTimeForProject = new RecalculateSpentTimeForProject($project);
|
||||
DB::enableQueryLog();
|
||||
|
||||
// Act
|
||||
$recalculateSpentTimeForProject->handle();
|
||||
|
||||
// Assert
|
||||
self::assertCount(2, DB::getQueryLog());
|
||||
$project->refresh();
|
||||
self::assertEquals(21, $project->spent_time);
|
||||
}
|
||||
|
||||
public function test_does_not_save_project_if_value_is_already_correct(): void
|
||||
{
|
||||
// Arrange
|
||||
$project = Project::factory()->create([
|
||||
'spent_time' => 21,
|
||||
]);
|
||||
TimeEntry::factory()->startWithDuration(now(), 10)->forProject($project)->create();
|
||||
TimeEntry::factory()->startWithDuration(now(), 11)->forProject($project)->create();
|
||||
|
||||
$project->refresh();
|
||||
$recalculateSpentTimeForProject = new RecalculateSpentTimeForProject($project);
|
||||
DB::enableQueryLog();
|
||||
|
||||
// Act
|
||||
$recalculateSpentTimeForProject->handle();
|
||||
|
||||
// Assert
|
||||
self::assertCount(1, DB::getQueryLog());
|
||||
$project->refresh();
|
||||
self::assertEquals(21, $project->spent_time);
|
||||
}
|
||||
}
|
||||
58
tests/Unit/Jobs/RecalculateSpentTimeForTaskTest.php
Normal file
58
tests/Unit/Jobs/RecalculateSpentTimeForTaskTest.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Jobs;
|
||||
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
|
||||
class RecalculateSpentTimeForTaskTest extends TestCaseWithDatabase
|
||||
{
|
||||
public function test_recalculates_spent_time_for_task(): void
|
||||
{
|
||||
// Arrange
|
||||
$task = Task::factory()->create([
|
||||
'spent_time' => 0,
|
||||
]);
|
||||
TimeEntry::factory()->startWithDuration(now(), 10)->forTask($task)->create();
|
||||
TimeEntry::factory()->startWithDuration(now(), 11)->forTask($task)->create();
|
||||
|
||||
$task->refresh();
|
||||
$recalculateSpentTimeForTask = new RecalculateSpentTimeForTask($task);
|
||||
DB::enableQueryLog();
|
||||
|
||||
// Act
|
||||
$recalculateSpentTimeForTask->handle();
|
||||
|
||||
// Assert
|
||||
self::assertCount(2, DB::getQueryLog());
|
||||
$task->refresh();
|
||||
self::assertEquals(21, $task->spent_time);
|
||||
}
|
||||
|
||||
public function test_does_not_save_task_if_value_is_already_correct(): void
|
||||
{
|
||||
// Arrange
|
||||
$task = Task::factory()->create([
|
||||
'spent_time' => 21,
|
||||
]);
|
||||
TimeEntry::factory()->startWithDuration(now(), 10)->forTask($task)->create();
|
||||
TimeEntry::factory()->startWithDuration(now(), 11)->forTask($task)->create();
|
||||
|
||||
$task->refresh();
|
||||
$recalculateSpentTimeForTask = new RecalculateSpentTimeForTask($task);
|
||||
DB::enableQueryLog();
|
||||
|
||||
// Act
|
||||
$recalculateSpentTimeForTask->handle();
|
||||
|
||||
// Assert
|
||||
self::assertCount(1, DB::getQueryLog());
|
||||
$task->refresh();
|
||||
self::assertEquals(21, $task->spent_time);
|
||||
}
|
||||
}
|
||||
51
tests/Unit/Jobs/Test/TestJobTest.php
Normal file
51
tests/Unit/Jobs/Test/TestJobTest.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Jobs\Test;
|
||||
|
||||
use App\Jobs\Test\TestJob;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
use TiMacDonald\Log\LogEntry;
|
||||
|
||||
class TestJobTest extends TestCaseWithDatabase
|
||||
{
|
||||
public function test_logs_debug_message(): void
|
||||
{
|
||||
// Arrange
|
||||
$user = User::factory()->create();
|
||||
$message = 'Test message';
|
||||
$job = new TestJob($user, $message);
|
||||
|
||||
// Act
|
||||
$job->handle();
|
||||
|
||||
// Assert
|
||||
Log::assertLoggedTimes(fn (LogEntry $log) => $log->level === 'debug'
|
||||
&& $log->message === 'TestJob: '.$message
|
||||
&& $log->context['user'] === $user->getKey(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
public function test_can_fail_if_parameter_fail_is_true(): void
|
||||
{
|
||||
// Arrange
|
||||
$user = User::factory()->create();
|
||||
$message = 'Test message';
|
||||
$job = new TestJob($user, $message, true);
|
||||
|
||||
// Act
|
||||
try {
|
||||
$job->handle();
|
||||
} catch (\Exception $e) {
|
||||
// Assert
|
||||
$this->assertEquals('TestJob failed.', $e->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail('Expected exception not thrown');
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\ProjectMember;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\UsesClass;
|
||||
|
||||
@@ -117,6 +119,47 @@ class ProjectModelTest extends ModelTestAbstract
|
||||
], $allProjects);
|
||||
}
|
||||
|
||||
public function test_computed_spent_time_returns_the_sum_of_all_time_entries_excl_running_timers(): void
|
||||
{
|
||||
// Arrange
|
||||
$project = Project::factory()->create();
|
||||
$otherProject = Project::factory()->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($otherProject)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($otherProject)->start(now())->active()->create();
|
||||
|
||||
// Act
|
||||
$project->refresh();
|
||||
$spentTime = $project->getSpentTimeComputed();
|
||||
|
||||
// Assert
|
||||
$this->assertEquals(30, $spentTime);
|
||||
}
|
||||
|
||||
public function test_computed_spent_time_returns_already_computed_value_if_present(): void
|
||||
{
|
||||
// Arrange
|
||||
$project = Project::factory()->create();
|
||||
$otherProject = Project::factory()->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($project)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($otherProject)->startWithDuration(now(), 10)->create();
|
||||
TimeEntry::factory()->forProject($otherProject)->start(now())->active()->create();
|
||||
$timeEntries = Project::query()
|
||||
->withAggregate('timeEntries as spent_time_computed', DB::raw('extract(epoch from ("end" - start))'), 'sum')
|
||||
->get();
|
||||
|
||||
// Act
|
||||
$project->refresh();
|
||||
$spentTime = $timeEntries->first()->getSpentTimeComputed();
|
||||
|
||||
// Assert
|
||||
$this->assertEquals(30, $spentTime);
|
||||
}
|
||||
|
||||
public function test_accessor_is_archived_is_true_if_archived_at_is_not_null(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
Reference in New Issue
Block a user