diff --git a/app/Http/Controllers/Api/V1/TimeEntryController.php b/app/Http/Controllers/Api/V1/TimeEntryController.php index 62fee3fd..308c8577 100644 --- a/app/Http/Controllers/Api/V1/TimeEntryController.php +++ b/app/Http/Controllers/Api/V1/TimeEntryController.php @@ -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); } diff --git a/app/Http/Resources/V1/Project/ProjectResource.php b/app/Http/Resources/V1/Project/ProjectResource.php index 2d8567cd..e96f2f04 100644 --- a/app/Http/Resources/V1/Project/ProjectResource.php +++ b/app/Http/Resources/V1/Project/ProjectResource.php @@ -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, ]; } } diff --git a/app/Http/Resources/V1/Task/TaskResource.php b/app/Http/Resources/V1/Task/TaskResource.php index 26107935..67411b00 100644 --- a/app/Http/Resources/V1/Task/TaskResource.php +++ b/app/Http/Resources/V1/Task/TaskResource.php @@ -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 */ diff --git a/app/Jobs/RecalculateSpentTimeForProject.php b/app/Jobs/RecalculateSpentTimeForProject.php new file mode 100644 index 00000000..528ddcc3 --- /dev/null +++ b/app/Jobs/RecalculateSpentTimeForProject.php @@ -0,0 +1,44 @@ +project = $project; + } + + /** + * Execute the job. + * + * @throws Exception + */ + public function handle(): void + { + $this->project->setComputedAttributeValue('spent_time'); + if ($this->project->isDirty()) { + $this->project->save(); + } + } +} diff --git a/app/Jobs/RecalculateSpentTimeForTask.php b/app/Jobs/RecalculateSpentTimeForTask.php new file mode 100644 index 00000000..fb5e38de --- /dev/null +++ b/app/Jobs/RecalculateSpentTimeForTask.php @@ -0,0 +1,44 @@ +task = $task; + } + + /** + * Execute the job. + * + * @throws Exception + */ + public function handle(): void + { + $this->task->setComputedAttributeValue('spent_time'); + if ($this->task->isDirty()) { + $this->task->save(); + } + } +} diff --git a/app/Models/Project.php b/app/Models/Project.php index 4eb555c7..7bf8ef02 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -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 */ @@ -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 + */ + 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 $builder + * @param array $attributes Attributes that will be generated. + * @return Builder + */ + 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 $builder + * @param array $attributes Attributes that will be validated. + * @return Builder + */ + public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder + { + return $this->scopeComputedAttributesGenerate($builder, $attributes); + } + /** * @return BelongsTo */ diff --git a/app/Models/Task.php b/app/Models/Task.php index fa696505..0344107b 100644 --- a/app/Models/Task.php +++ b/app/Models/Task.php @@ -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 */ @@ -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 + */ + 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 $builder + * @param array $attributes Attributes that will be generated. + * @return Builder + */ + 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 $builder + * @param array $attributes Attributes that will be validated. + * @return Builder + */ + public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder + { + return $this->scopeComputedAttributesGenerate($builder, $attributes); + } + /** * @return BelongsTo */ diff --git a/app/Models/TimeEntry.php b/app/Models/TimeEntry.php index c2276e16..9412ab60 100644 --- a/app/Models/TimeEntry.php +++ b/app/Models/TimeEntry.php @@ -81,6 +81,15 @@ class TimeEntry extends Model implements AuditableContract 'billable_rate', ]; + /** + * Attributes to exclude from the Audit. + * + * @var array + */ + protected array $auditExclude = [ + 'billable_rate', + ]; + public function getBillableRateComputed(): ?int { return app(BillableRateService::class)->getBillableRateForTimeEntry($this); diff --git a/database/migrations/2024_09_18_120203_add_spent_time_to_projects_and_tasks_table.php b/database/migrations/2024_09_18_120203_add_spent_time_to_projects_and_tasks_table.php new file mode 100644 index 00000000..7dd7eed0 --- /dev/null +++ b/database/migrations/2024_09_18_120203_add_spent_time_to_projects_and_tasks_table.php @@ -0,0 +1,36 @@ +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'); + }); + } +}; diff --git a/tests/Unit/Endpoint/Api/V1/TimeEntryEndpointTest.php b/tests/Unit/Endpoint/Api/V1/TimeEntryEndpointTest.php index c715e358..23a6d958 100644 --- a/tests/Unit/Endpoint/Api/V1/TimeEntryEndpointTest.php +++ b/tests/Unit/Endpoint/Api/V1/TimeEntryEndpointTest.php @@ -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 diff --git a/tests/Unit/Jobs/RecalculateSpentTimeForProjectTest.php b/tests/Unit/Jobs/RecalculateSpentTimeForProjectTest.php new file mode 100644 index 00000000..ec982f49 --- /dev/null +++ b/tests/Unit/Jobs/RecalculateSpentTimeForProjectTest.php @@ -0,0 +1,58 @@ +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); + } +} diff --git a/tests/Unit/Jobs/RecalculateSpentTimeForTaskTest.php b/tests/Unit/Jobs/RecalculateSpentTimeForTaskTest.php new file mode 100644 index 00000000..6aed29b1 --- /dev/null +++ b/tests/Unit/Jobs/RecalculateSpentTimeForTaskTest.php @@ -0,0 +1,58 @@ +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); + } +} diff --git a/tests/Unit/Jobs/Test/TestJobTest.php b/tests/Unit/Jobs/Test/TestJobTest.php new file mode 100644 index 00000000..b65440ad --- /dev/null +++ b/tests/Unit/Jobs/Test/TestJobTest.php @@ -0,0 +1,51 @@ +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'); + } +} diff --git a/tests/Unit/Model/ProjectModelTest.php b/tests/Unit/Model/ProjectModelTest.php index 5bda407d..c9056514 100644 --- a/tests/Unit/Model/ProjectModelTest.php +++ b/tests/Unit/Model/ProjectModelTest.php @@ -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