Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add endpoint to delete multiple time entries #161

Merged
merged 3 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions app/Http/Controllers/Api/V1/TimeEntryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
use App\Exceptions\Api\TimeEntryStillRunningApiException;
use App\Http\Requests\V1\TimeEntry\TimeEntryAggregateRequest;
use App\Http\Requests\V1\TimeEntry\TimeEntryDestroyMultipleRequest;
use App\Http\Requests\V1\TimeEntry\TimeEntryIndexRequest;
use App\Http\Requests\V1\TimeEntry\TimeEntryStoreRequest;
use App\Http\Requests\V1\TimeEntry\TimeEntryUpdateMultipleRequest;
Expand Down Expand Up @@ -429,4 +430,52 @@ public function destroy(Organization $organization, TimeEntry $timeEntry): JsonR
return response()
->json(null, 204);
}

/**
* Delete multiple time entries
*
* @throws AuthorizationException
*
* @operationId deleteTimeEntries
*/
public function destroyMultiple(Organization $organization, TimeEntryDestroyMultipleRequest $request): JsonResponse
{
$this->checkAnyPermission($organization, ['time-entries:delete:all', 'time-entries:delete:own']);
$canDeleteAll = $this->hasPermission($organization, 'time-entries:delete:all');

$ids = $request->validated('ids');
$timeEntries = TimeEntry::query()
->whereBelongsTo($organization, 'organization')
->whereIn('id', $ids)
->get();

$success = new Collection();
$error = new Collection();

foreach ($ids as $id) {
/** @var TimeEntry|null $timeEntry */
$timeEntry = $timeEntries->firstWhere('id', $id);
if ($timeEntry === null) {
// Note: ID wrong or time entry in different organization
$error->push($id);

continue;
}

if (! $canDeleteAll && $timeEntry->user_id !== Auth::id()) {
$error->push($id);

continue;

}

$timeEntry->delete();
$success->push($id);
}

return response()->json([
'success' => $success->toArray(),
'error' => $error->toArray(),
]);
}
}
34 changes: 34 additions & 0 deletions app/Http/Requests/V1/TimeEntry/TimeEntryDestroyMultipleRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests\V1\TimeEntry;

use App\Models\Organization;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;

/**
* @property Organization $organization Organization from model binding
*/
class TimeEntryDestroyMultipleRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'ids' => [
'required',
'array',
],
'ids.*' => [
'string',
'uuid',
],
];
}
}
4 changes: 1 addition & 3 deletions resources/js/Pages/ReportingDetailed.vue
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ const totalPages = computed(() => {
const timeEntriesStore = useTimeEntriesStore();

async function deleteTimeEntries(timeEntries: TimeEntry[]) {
for (const timeEntry of timeEntries) {
await timeEntriesStore.deleteTimeEntry(timeEntry.id);
}
await timeEntriesStore.deleteTimeEntries(timeEntries);
selectedTimeEntries.value = [];
await updateFilteredTimeEntries();
}
Expand Down
4 changes: 1 addition & 3 deletions resources/js/Pages/Time.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ async function startTimeEntry(
}

function deleteTimeEntries(timeEntries: TimeEntry[]) {
timeEntries.forEach((entry) => {
useTimeEntriesStore().deleteTimeEntry(entry.id);
});
useTimeEntriesStore().deleteTimeEntries(timeEntries);
fetchTimeEntries();
}

Expand Down
48 changes: 48 additions & 0 deletions resources/js/packages/api/src/openapi.json.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2325,6 +2325,54 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
},
],
},
{
method: 'delete',
path: '/v1/organizations/:organization/time-entries',
alias: 'deleteTimeEntries',
requestFormat: 'json',
parameters: [
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'ids',
type: 'Query',
schema: z.array(z.string().uuid()),
},
],
response: z
.object({ success: z.string(), error: z.string() })
.passthrough(),
errors: [
{
status: 401,
description: `Unauthenticated`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 403,
description: `Authorization error`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 404,
description: `Not found`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.passthrough(),
},
],
},
{
method: 'put',
path: '/v1/organizations/:organization/time-entries/:timeEntry',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ const expanded = ref(false);
class="opacity-20 hidden sm:flex group-hover:opacity-100"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
@delete="
deleteTimeEntries(timeEntry.timeEntries)
deleteTimeEntries(timeEntry?.timeEntries ?? [])
"></TimeEntryMoreOptionsDropdown>
</div>
</div>
Expand Down
22 changes: 22 additions & 0 deletions resources/js/utils/useTimeEntries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,27 @@ export const useTimeEntriesStore = defineStore('timeEntries', () => {
}
}

async function deleteTimeEntries(timeEntries: TimeEntry[]) {
const organizationId = getCurrentOrganizationId();
const timeEntryIds = timeEntries.map((entry) => entry.id);
if (organizationId) {
await handleApiRequestNotifications(
() =>
api.deleteTimeEntries(undefined, {
queries: {
ids: timeEntryIds,
},
params: {
organization: organizationId,
},
}),
'Time entries deleted successfully',
'Failed to delete time entries'
);
await fetchTimeEntries();
}
}

return {
timeEntries,
fetchTimeEntries,
Expand All @@ -177,5 +198,6 @@ export const useTimeEntriesStore = defineStore('timeEntries', () => {
fetchMoreTimeEntries,
allTimeEntriesLoaded,
updateTimeEntries,
deleteTimeEntries,
};
});
1 change: 1 addition & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
Route::put('/organizations/{organization}/time-entries/{timeEntry}', [TimeEntryController::class, 'update'])->name('update')->middleware('check-organization-blocked');
Route::patch('/organizations/{organization}/time-entries', [TimeEntryController::class, 'updateMultiple'])->name('update-multiple')->middleware('check-organization-blocked');
Route::delete('/organizations/{organization}/time-entries/{timeEntry}', [TimeEntryController::class, 'destroy'])->name('destroy');
Route::delete('/organizations/{organization}/time-entries', [TimeEntryController::class, 'destroyMultiple'])->name('destroy-multiple');
});

Route::name('users.time-entries.')->group(static function (): void {
Expand Down
140 changes: 140 additions & 0 deletions tests/Unit/Endpoint/Api/V1/TimeEntryEndpointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1660,6 +1660,146 @@ public function test_destroy_endpoint_deletes_time_entry_of_other_user_in_organi
]);
}

public function test_destroy_multiple_endpoint_fails_if_user_has_no_permission_to_delete_own_time_entries_or_all_time_entries(): void
{
// Arrange
$data = $this->createUserWithPermission();
$timeEntries = TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)->createMany(3);
Passport::actingAs($data->user);

// Act
$response = $this->deleteJson(route('api.v1.time-entries.destroy-multiple', [$data->organization->getKey()]), [
'ids' => $timeEntries->pluck('id')->toArray(),
]);

// Assert
$response->assertValid();
$response->assertForbidden();
}

public function test_destroy_multiple_endpoint_fails_if_ids_contains_non_uuid_id(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:delete:own',
]);
Passport::actingAs($data->user);

// Act
$response = $this->deleteJson(route('api.v1.time-entries.destroy-multiple', [$data->organization->getKey()]), [
'ids' => [
Str::uuid(),
'non-uuid',
],
]);

// Assert
$response->assertStatus(422);
$response->assertJsonValidationErrors([
'ids.1' => ['The ids.1 field must be a valid UUID.'],
]);
}

public function test_destroy_multiple_endpoint_own_time_entries_and_fails_for_time_entries_of_other_users_and_and_other_organizations_with_own_time_entries_permission(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:delete:own',
]);
$otherData = $this->createUserWithPermission();
$otherUser = User::factory()->create();
$otherMember = Member::factory()->forOrganization($data->organization)->forUser($otherUser)->role(Role::Employee)->create();

$ownTimeEntry = TimeEntry::factory()->forMember($data->member)->create();
$otherTimeEntry = TimeEntry::factory()->forMember($otherMember)->create();
$otherOrganizationTimeEntry = TimeEntry::factory()->forMember($otherData->member)->create();
$wrongId = Str::uuid();
Passport::actingAs($data->user);

// Act
$response = $this->deleteJson(route('api.v1.time-entries.destroy-multiple', [$data->organization->getKey()]), [
'ids' => [
$ownTimeEntry->getKey(),
$otherTimeEntry->getKey(),
$otherOrganizationTimeEntry->getKey(),
$wrongId,
],
]);

// Assert
$response->assertValid();
$response->assertStatus(200);
$response->assertExactJson([
'success' => [
$ownTimeEntry->getKey(),
],
'error' => [
$otherTimeEntry->getKey(),
$otherOrganizationTimeEntry->getKey(),
$wrongId,
],
]);
$this->assertDatabaseMissing(TimeEntry::class, [
'id' => $ownTimeEntry->getKey(),
]);
$this->assertDatabaseHas(TimeEntry::class, [
'id' => $otherTimeEntry->getKey(),
]);
$this->assertDatabaseHas(TimeEntry::class, [
'id' => $otherOrganizationTimeEntry->getKey(),
]);
}

public function test_destroy_multiple_deletes_all_time_entries_and_fails_for_time_entries_of_other_users_and_and_other_organizations_with_all_time_entries_permission(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:delete:all',
]);
$otherData = $this->createUserWithPermission();
$otherUser = User::factory()->create();
$otherMember = Member::factory()->forOrganization($data->organization)->forUser($otherUser)->role(Role::Employee)->create();

$ownTimeEntry = TimeEntry::factory()->forMember($data->member)->create();
$otherTimeEntry = TimeEntry::factory()->forMember($otherMember)->create();
$otherOrganizationTimeEntry = TimeEntry::factory()->forMember($otherData->member)->create();
$wrongId = Str::uuid();
Passport::actingAs($data->user);

// Act
$response = $this->deleteJson(route('api.v1.time-entries.destroy-multiple', [$data->organization->getKey()]), [
'ids' => [
$ownTimeEntry->getKey(),
$otherTimeEntry->getKey(),
$otherOrganizationTimeEntry->getKey(),
$wrongId,
],
]);

// Assert
$response->assertValid();
$response->assertStatus(200);
$response->assertExactJson([
'success' => [
$ownTimeEntry->getKey(),
$otherTimeEntry->getKey(),
],
'error' => [
$otherOrganizationTimeEntry->getKey(),
$wrongId,
],
]);
$this->assertDatabaseMissing(TimeEntry::class, [
'id' => $ownTimeEntry->getKey(),
]);
$this->assertDatabaseMissing(TimeEntry::class, [
'id' => $otherTimeEntry->getKey(),
]);
$this->assertDatabaseHas(TimeEntry::class, [
'id' => $otherOrganizationTimeEntry->getKey(),
]);
}

public function test_destroy_endpoint_recalculates_project_and_task_spend_time_after_deleting_time_entry(): void
{
// Arrange
Expand Down
Loading