From 4c8215a889062b9ff643769ec4710bf72183316a Mon Sep 17 00:00:00 2001 From: Constantin Graf Date: Wed, 18 Nov 2026 17:18:15 +0100 Subject: [PATCH] Store exports in the database and process them in a queued job --- .../Commands/Export/ExportPruneCommand.php | 105 ++++++ app/Console/Kernel.php | 4 + app/Enums/ExportStatus.php | 35 ++ app/Enums/ExportType.php | 17 + app/Exceptions/Api/ApiException.php | 5 +- .../ExportAlreadyInProgressApiException.php | 15 + .../ExportFileNotAvailableApiException.php | 15 + app/Filament/Resources/ExportResource.php | 193 +++++++++++ .../ExportResource/Pages/ListExports.php | 19 ++ .../ExportResource/Pages/ViewExport.php | 19 ++ .../Controllers/Api/V1/ExportController.php | 91 +++++- .../Requests/V1/Export/ExportIndexRequest.php | 27 ++ .../Resources/V1/Export/ExportCollection.php | 17 + .../Resources/V1/Export/ExportResource.php | 45 +++ app/Jobs/ProcessExport.php | 78 +++++ app/Models/Export.php | 111 +++++++ app/Service/DeletionService.php | 15 + app/Service/Export/ExportService.php | 119 ++++++- config/export.php | 34 ++ config/scheduling.php | 1 + database/factories/ExportFactory.php | 81 +++++ ...2026_11_18_000001_create_exports_table.php | 56 ++++ e2e/import-export.spec.ts | 7 +- lang/en/exceptions.php | 4 + .../js/Pages/Teams/Partials/ExportData.vue | 228 +++++++++++-- resources/js/packages/api/src/index.ts | 2 +- .../packages/api/src/openapi.json.client.ts | 179 ++++++++++- routes/api.php | 3 + .../Export/ExportPruneCommandTest.php | 113 +++++++ .../Endpoint/Api/V1/ExportEndpointTest.php | 300 ++++++++++++++---- .../Unit/Exceptions/Api/ApiExceptionTest.php | 4 + .../Filament/Resources/ExportResourceTest.php | 60 ++++ tests/Unit/Jobs/ProcessExportTest.php | 113 +++++++ tests/Unit/Model/ExportModelTest.php | 72 +++++ tests/Unit/Service/DeletionServiceTest.php | 16 +- .../Unit/Service/Export/ExportServiceTest.php | 153 +++++++++ 36 files changed, 2248 insertions(+), 108 deletions(-) create mode 100644 app/Console/Commands/Export/ExportPruneCommand.php create mode 100644 app/Enums/ExportStatus.php create mode 100644 app/Enums/ExportType.php create mode 100644 app/Exceptions/Api/ExportAlreadyInProgressApiException.php create mode 100644 app/Exceptions/Api/ExportFileNotAvailableApiException.php create mode 100644 app/Filament/Resources/ExportResource.php create mode 100644 app/Filament/Resources/ExportResource/Pages/ListExports.php create mode 100644 app/Filament/Resources/ExportResource/Pages/ViewExport.php create mode 100644 app/Http/Requests/V1/Export/ExportIndexRequest.php create mode 100644 app/Http/Resources/V1/Export/ExportCollection.php create mode 100644 app/Http/Resources/V1/Export/ExportResource.php create mode 100644 app/Jobs/ProcessExport.php create mode 100644 app/Models/Export.php create mode 100644 config/export.php create mode 100644 database/factories/ExportFactory.php create mode 100644 database/migrations/2026_11_18_000001_create_exports_table.php create mode 100644 tests/Unit/Console/Commands/Export/ExportPruneCommandTest.php create mode 100644 tests/Unit/Filament/Resources/ExportResourceTest.php create mode 100644 tests/Unit/Jobs/ProcessExportTest.php create mode 100644 tests/Unit/Model/ExportModelTest.php diff --git a/app/Console/Commands/Export/ExportPruneCommand.php b/app/Console/Commands/Export/ExportPruneCommand.php new file mode 100644 index 00000000..ab6c3eed --- /dev/null +++ b/app/Console/Commands/Export/ExportPruneCommand.php @@ -0,0 +1,105 @@ +option('dry-run'); + if ($dryRun) { + $this->comment('Running in dry-run mode. Nothing will be saved or deleted.'); + } + + $jobTimeout = (int) config('export.job_timeout'); + $runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS); + $pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS); + $staleExports = 0; + Export::query() + ->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void { + $query->where(function (Builder $query) use ($runningStaleBefore): void { + $query->where('status', ExportStatus::Running) + ->where('started_at', '<', $runningStaleBefore); + })->orWhere(function (Builder $query) use ($pendingStaleBefore): void { + $query->where('status', ExportStatus::Pending) + ->where('created_at', '<', $pendingStaleBefore); + }); + }) + ->orderBy('created_at', 'asc') + ->chunkById(500, function (Collection $exports) use ($dryRun, $exportService, &$staleExports): void { + /** @var Collection $exports */ + foreach ($exports as $export) { + $this->info('Mark stale export '.$export->getKey().' ('.$export->status->value.') as failed'); + $staleExports++; + if (! $dryRun) { + $exportService->markAsFailed($export, 'Export could not be finished'); + } + } + }); + + $retentionBefore = Carbon::now()->subDays((int) config('export.file_retention_days')); + $prunedFiles = 0; + Export::query() + ->whereNotNull('file_path') + ->whereNotNull('finished_at') + ->where('finished_at', '<', $retentionBefore) + ->orderBy('created_at', 'asc') + ->chunkById(500, function (Collection $exports) use ($dryRun, &$prunedFiles): void { + /** @var Collection $exports */ + foreach ($exports as $export) { + $this->info('Delete file of export '.$export->getKey().' ('.$export->file_path.')'); + $prunedFiles++; + if (! $dryRun) { + Storage::disk(config('filesystems.private'))->delete((string) $export->file_path); + $export->file_path = null; + $export->save(); + } + } + }); + + $this->comment('Marked '.$staleExports.' stale exports as failed and deleted '.$prunedFiles.' export files.'); + + return self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 000dddca..4afe9bc5 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -48,6 +48,10 @@ class Kernel extends ConsoleKernel ->when(fn (): bool => config('scheduling.tasks.import_prune')) ->everyFiveMinutes(); + $schedule->command('export:prune') + ->when(fn (): bool => config('scheduling.tasks.export_prune')) + ->everyFiveMinutes(); + $schedule->command('self-host:database-consistency') ->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency')) ->everySixHours(); diff --git a/app/Enums/ExportStatus.php b/app/Enums/ExportStatus.php new file mode 100644 index 00000000..39e76e2e --- /dev/null +++ b/app/Enums/ExportStatus.php @@ -0,0 +1,35 @@ + + */ + public static function active(): array + { + return [self::Pending, self::Running]; + } + + public function isActive(): bool + { + return in_array($this, self::active(), true); + } +} diff --git a/app/Enums/ExportType.php b/app/Enums/ExportType.php new file mode 100644 index 00000000..133fd40f --- /dev/null +++ b/app/Enums/ExportType.php @@ -0,0 +1,17 @@ +columns(2) + ->components([ + TextInput::make('id') + ->label('ID') + ->disabled(), + Select::make('organization_id') + ->label('Organization') + ->relationship(name: 'organization', titleAttribute: 'name') + ->hintAction( + Action::make('open-organization') + ->label('Open organization') + ->icon('heroicon-o-arrow-top-right-on-square') + ->url(fn (?Export $record): ?string => $record !== null + ? OrganizationResource::getUrl('view', ['record' => $record->organization_id]) + : null) + ) + ->disabled(), + Select::make('user_id') + ->label('User') + ->relationship(name: 'user', titleAttribute: 'email') + ->hintAction( + Action::make('open-user') + ->label('Open user') + ->icon('heroicon-o-arrow-top-right-on-square') + ->hidden(fn (?Export $record): bool => $record?->user_id === null) + ->url(fn (?Export $record): ?string => $record?->user_id !== null + ? UserResource::getUrl('view', ['record' => $record->user_id]) + : null) + ) + ->disabled(), + Select::make('type') + ->label('Type') + ->options(ExportType::class) + ->disabled(), + Select::make('status') + ->label('Status') + ->options(ExportStatus::class) + ->disabled(), + TextInput::make('file_path') + ->label('File path') + ->disabled(), + Textarea::make('error_message') + ->label('Error message') + ->columnSpanFull() + ->disabled(), + Textarea::make('error_details') + ->label('Error details') + ->helperText('Exception chain and stack trace, only visible in the admin panel') + // The attribute is hidden for serialization, so it is not filled into the form automatically + ->formatStateUsing(fn (Export $record): ?string => $record->error_details) + ->rows(15) + ->extraInputAttributes(['style' => 'font-family: monospace; font-size: 80%;']) + ->columnSpanFull() + ->disabled(), + DateTimePicker::make('created_at') + ->label('Created at') + ->disabled(), + DateTimePicker::make('started_at') + ->label('Started at') + ->disabled(), + DateTimePicker::make('finished_at') + ->label('Finished at') + ->disabled(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('organization.name') + ->url(fn (Export $record): string => OrganizationResource::getUrl('view', ['record' => $record->organization_id])) + ->searchable() + ->sortable(), + TextColumn::make('user.email') + ->label('User') + ->url(fn (Export $record): ?string => $record->user_id !== null + ? UserResource::getUrl('view', ['record' => $record->user_id]) + : null) + ->searchable() + ->toggleable(), + TextColumn::make('type') + ->sortable() + ->toggleable(isToggledHiddenByDefault: true), + TextColumn::make('status') + ->badge() + ->color(fn (Export $record): string => match ($record->status) { + ExportStatus::Pending => 'gray', + ExportStatus::Running => 'info', + ExportStatus::Completed => 'success', + ExportStatus::Failed => 'danger', + }) + ->sortable(), + TextColumn::make('error_message') + ->limit(80) + ->toggleable(), + TextColumn::make('created_at') + ->dateTime() + ->sortable(), + TextColumn::make('duration') + ->label('Duration') + ->state(function (Export $record): ?string { + if ($record->started_at === null || $record->finished_at === null) { + return null; + } + + return $record->started_at->diffForHumans($record->finished_at, [ + 'syntax' => CarbonInterface::DIFF_ABSOLUTE, + 'parts' => 2, + ]); + }), + ]) + ->defaultSort('created_at', 'desc') + ->filters([ + SelectFilter::make('status') + ->options(ExportStatus::class), + SelectFilter::make('type') + ->options(ExportType::class), + SelectFilter::make('organization') + ->label('Organization') + ->relationship('organization', 'name') + ->searchable(), + SelectFilter::make('organization_id') + ->label('Organization ID') + ->relationship('organization', 'id') + ->searchable(), + ]) + ->recordActions([ + Action::make('download-file') + ->label('File') + ->icon('heroicon-o-arrow-down-tray') + ->color('gray') + ->hidden(fn (Export $record): bool => $record->file_path === null) + ->action(fn (Export $record): StreamedResponse => Storage::disk(config('filesystems.private')) + ->download((string) $record->file_path, $record->getDownloadFilename('UTC'))), + ViewAction::make(), + ]) + ->toolbarActions([ + ]); + } + + public static function canCreate(): bool + { + return false; + } + + public static function getPages(): array + { + return [ + 'index' => ListExports::route('/'), + 'view' => ViewExport::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/ExportResource/Pages/ListExports.php b/app/Filament/Resources/ExportResource/Pages/ListExports.php new file mode 100644 index 00000000..b7f590df --- /dev/null +++ b/app/Filament/Resources/ExportResource/Pages/ListExports.php @@ -0,0 +1,19 @@ +checkPermission($organization, 'export'); - $filepath = $exportService->export($organization); + $export = $exportService->createOrganizationExport($organization, $this->user()); + + return (new ExportResource($export->refresh())) + ->response() + ->setStatusCode(202); + } + + /** + * Get exports + * + * @throws AuthorizationException + * + * @operationId getExports + */ + public function index(Organization $organization, ExportIndexRequest $request): ExportCollection + { + $this->checkPermission($organization, 'export'); + + $exports = Export::query() + ->whereBelongsTo($organization, 'organization') + ->orderBy('created_at', 'desc') + ->orderBy('id') + ->paginate(config('app.pagination_per_page_default')); + + return new ExportCollection($exports); + } + + /** + * Get export + * + * @throws AuthorizationException + * + * @operationId getExport + */ + public function show(Organization $organization, Export $export): ExportResource + { + $this->checkPermission($organization, 'export'); + $this->checkExportBelongsToOrganization($organization, $export); + + return new ExportResource($export); + } + + /** + * Get download URL of an export + * + * The download URL is only valid for a short time, request a new one for every download. + * + * @throws AuthorizationException + * @throws ExportFileNotAvailableApiException + * + * @operationId downloadExport + */ + public function download(Organization $organization, Export $export): JsonResponse + { + $this->checkPermission($organization, 'export'); + $this->checkExportBelongsToOrganization($organization, $export); + + if ($export->status !== ExportStatus::Completed || $export->file_path === null) { + throw new ExportFileNotAvailableApiException; + } + $downloadUrl = Storage::disk(config('filesystems.private')) - ->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [ - 'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"', + ->temporaryUrl($export->file_path, Carbon::now()->addMinutes(10), [ + 'ResponseContentDisposition' => 'attachment; filename="'.$export->getDownloadFilename($this->user()->timezone).'"', ]); return new JsonResponse([ - 'success' => true, + /** @var string $download_url Temporary download URL of the export file, valid for 10 minutes */ 'download_url' => $downloadUrl, ], 200); } + + /** + * @throws AuthorizationException + */ + private function checkExportBelongsToOrganization(Organization $organization, Export $export): void + { + if ($export->organization_id !== $organization->getKey()) { + throw new AuthorizationException('Export does not belong to organization'); + } + } } diff --git a/app/Http/Requests/V1/Export/ExportIndexRequest.php b/app/Http/Requests/V1/Export/ExportIndexRequest.php new file mode 100644 index 00000000..f83a5bb7 --- /dev/null +++ b/app/Http/Requests/V1/Export/ExportIndexRequest.php @@ -0,0 +1,27 @@ +> + */ + public function rules(): array + { + return [ + 'page' => [ + 'integer', + 'min:1', + 'max:2147483647', + ], + ]; + } +} diff --git a/app/Http/Resources/V1/Export/ExportCollection.php b/app/Http/Resources/V1/Export/ExportCollection.php new file mode 100644 index 00000000..c6993986 --- /dev/null +++ b/app/Http/Resources/V1/Export/ExportCollection.php @@ -0,0 +1,17 @@ + + */ + public function toArray(Request $request): array + { + return [ + /** ID of the export */ + 'id' => $this->resource->id, + /** Type of the export */ + 'type' => $this->resource->type, + /** Status of the export */ + 'status' => $this->resource->status, + /** @var bool $download_available Whether the export file can be downloaded, the file is deleted after the retention period */ + 'download_available' => $this->resource->status === ExportStatus::Completed && $this->resource->file_path !== null, + /** Error message, only set if the export failed */ + 'error_message' => $this->resource->error_message, + /** ID of the user that started the export */ + 'user_id' => $this->resource->user_id, + /** @var string|null $started_at Date when the export was started */ + 'started_at' => $this->formatDateTime($this->resource->started_at), + /** @var string|null $finished_at Date when the export was finished */ + 'finished_at' => $this->formatDateTime($this->resource->finished_at), + /** @var string|null $created_at Date when the export was created */ + 'created_at' => $this->formatDateTime($this->resource->created_at), + ]; + } +} diff --git a/app/Jobs/ProcessExport.php b/app/Jobs/ProcessExport.php new file mode 100644 index 00000000..27445810 --- /dev/null +++ b/app/Jobs/ProcessExport.php @@ -0,0 +1,78 @@ +export = $export; + $this->timeout = (int) config('export.job_timeout'); + $this->onQueue(config('export.queue')); + } + + /** + * Execute the job. + */ + public function handle(ExportService $exportService): void + { + $exportService->process($this->export); + } + + /** + * Handle a job failure. + */ + public function failed(?Throwable $exception): void + { + // A MaxAttemptsExceededException (that is not a timeout) is thrown if the export runs longer than the + // "retry_after" of the queue connection and the queue hands out the job a second time, while the first + // attempt is still running. The export must not be marked as failed in this case. + // The export:prune command marks the export as failed if it is really stale. + // Note: Unlike imports, exports do not run in a database transaction, so a timed out export can be marked + // as failed here. + if ($exception instanceof MaxAttemptsExceededException && ! $exception instanceof TimeoutExceededException) { + return; + } + + $this->export->refresh(); + if ($this->export->status->isActive()) { + app(ExportService::class)->markAsFailed($this->export, 'Export could not be finished'); + } + } +} diff --git a/app/Models/Export.php b/app/Models/Export.php new file mode 100644 index 00000000..2021ea53 --- /dev/null +++ b/app/Models/Export.php @@ -0,0 +1,111 @@ + */ + use HasFactory; + + use HasUuids; + + private const int DOWNLOAD_FILENAME_SLUG_MAX_LENGTH = 40; + + /** + * The attributes that should be cast. + * + * @var array + */ + protected $casts = [ + 'type' => ExportType::class, + 'status' => ExportStatus::class, + 'started_at' => 'datetime', + 'finished_at' => 'datetime', + ]; + + /** + * The attributes that should be hidden for serialization. + * + * @var list + */ + protected $hidden = [ + 'error_details', + ]; + + /** + * @return BelongsTo + */ + public function organization(): BelongsTo + { + return $this->belongsTo(Organization::class, 'organization_id'); + } + + /** + * The user that started the export, null if the user was deleted. + * + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } + + /** + * Filename that is used when the export file is downloaded, for example + * "solidtime-export_acme-gmbh_2026-11-18_10-20_1f2470b2.zip". + * The short export ID makes the filename unique, even for exports of organizations with the same name. + * + * @param string $timezone Timezone of the date in the filename + */ + public function getDownloadFilename(string $timezone): string + { + $organizationSlug = Str::limit(Str::slug($this->organization->name), self::DOWNLOAD_FILENAME_SLUG_MAX_LENGTH, ''); + $organizationSlug = trim($organizationSlug, '-'); + if ($organizationSlug === '') { + $organizationSlug = 'organization'; + } + $createdAt = ($this->created_at ?? Carbon::now())->copy()->setTimezone($timezone); + + return 'solidtime-export_'.$organizationSlug.'_'.$createdAt->format('Y-m-d_H-i').'_'.Str::substr($this->getKey(), 0, 8).'.zip'; + } + + /** + * @param Builder $builder + * @return Builder + */ + public function scopeActive(Builder $builder): Builder + { + return $builder->whereIn('status', ExportStatus::active()); + } +} diff --git a/app/Service/DeletionService.php b/app/Service/DeletionService.php index e9954cdd..114d629f 100644 --- a/app/Service/DeletionService.php +++ b/app/Service/DeletionService.php @@ -9,6 +9,7 @@ use App\Events\BeforeOrganizationDeletion; use App\Events\BeforeUserDeletion; use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers; use App\Models\Client; +use App\Models\Export; use App\Models\Goal; use App\Models\Import; use App\Models\Member; @@ -96,6 +97,20 @@ class DeletionService }); } + // Delete all exports, the stored export files are deleted after the transaction is committed, + // since the deletion of files is not reversible via a database rollback + $exportFilePaths = Export::query() + ->whereBelongsTo($organization, 'organization') + ->whereNotNull('file_path') + ->pluck('file_path') + ->all(); + Export::query()->whereBelongsTo($organization, 'organization')->delete(); + if (count($exportFilePaths) > 0) { + DB::afterCommit(function () use ($exportFilePaths): void { + Storage::disk(config('filesystems.private'))->delete($exportFilePaths); + }); + } + // Reset the current organization $organization->owner() ->where('current_team_id', $organization->getKey()) diff --git a/app/Service/Export/ExportService.php b/app/Service/Export/ExportService.php index 22d85963..fb85597d 100644 --- a/app/Service/Export/ExportService.php +++ b/app/Service/Export/ExportService.php @@ -4,7 +4,12 @@ declare(strict_types=1); namespace App\Service\Export; +use App\Enums\ExportStatus; +use App\Enums\ExportType; +use App\Exceptions\Api\ExportAlreadyInProgressApiException; +use App\Jobs\ProcessExport; use App\Models\Client; +use App\Models\Export; use App\Models\Member; use App\Models\Organization; use App\Models\OrganizationInvitation; @@ -13,8 +18,10 @@ use App\Models\ProjectMember; use App\Models\Tag; use App\Models\Task; use App\Models\TimeEntry; +use App\Models\User; use Exception; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Http\File; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Log; @@ -25,18 +32,117 @@ use League\Csv\Exception as LeagueCsvException; use League\Csv\UnavailableStream; use League\Csv\Writer; use Spatie\TemporaryDirectory\TemporaryDirectory; +use Throwable; use ZipArchive; class ExportService { public const string VERSION = '1.0'; + private const int ERROR_DETAILS_MAX_LENGTH = 50000; + /** + * Creates an export of all data of the organization and queues it. + * + * @throws ExportAlreadyInProgressApiException + */ + public function createOrganizationExport(Organization $organization, ?User $user): Export + { + if (Export::query()->whereBelongsTo($organization, 'organization')->active()->exists()) { + throw new ExportAlreadyInProgressApiException; + } + + $export = new Export; + $export->type = ExportType::Organization; + $export->status = ExportStatus::Pending; + $export->organization()->associate($organization); + $export->user()->associate($user); + + try { + $export->save(); + } catch (UniqueConstraintViolationException) { + // Another export of the organization was created in the meantime + throw new ExportAlreadyInProgressApiException; + } + + ProcessExport::dispatch($export); + + return $export; + } + + /** + * Runs the export, the result (file path or error message) is stored on the export. + */ + public function process(Export $export): void + { + if ($export->status !== ExportStatus::Pending) { + Log::warning('Skipping export that is not pending', [ + 'export_id' => $export->getKey(), + 'status' => $export->status->value, + ]); + + return; + } + + $export->status = ExportStatus::Running; + $export->started_at = Carbon::now(); + $export->save(); + + try { + $export->file_path = $this->export($export->organization, $export->getKey()); + $export->status = ExportStatus::Completed; + } catch (Throwable $exception) { + // Export exceptions are already reported in the export method + if (! $exception instanceof ExportException) { + report($exception); + } + $export->status = ExportStatus::Failed; + $export->error_message = 'Export failed, please try again later or contact support'; + $export->error_details = $this->getErrorDetails($exception->getPrevious() ?? $exception); + } finally { + $export->finished_at = Carbon::now(); + $export->save(); + } + } + + /** + * Marks an export as failed that could not be finished, for example because the job timed out or the worker crashed. + */ + public function markAsFailed(Export $export, string $errorMessage): void + { + $export->status = ExportStatus::Failed; + $export->error_message = $errorMessage; + $export->finished_at = Carbon::now(); + $export->save(); + } + + /** + * Technical details of the exception and all previous exceptions for debugging in the admin panel. + */ + private function getErrorDetails(Throwable $exception): string + { + $parts = []; + $current = $exception; + while ($current !== null) { + $parts[] = $current::class.': '.$current->getMessage()."\n". + 'at '.$current->getFile().':'.$current->getLine()."\n". + $current->getTraceAsString(); + $current = $current->getPrevious(); + } + + return Str::limit(implode("\n\nCaused by: ", $parts), self::ERROR_DETAILS_MAX_LENGTH); + } + + /** + * Creates the export ZIP file and stores it on the private disk. + * + * @return string Path of the ZIP file on the private disk + * * @throws ExportException */ - public function export(Organization $organization): string + public function export(Organization $organization, ?string $exportId = null): string { - $exportId = Str::uuid(); + $exportId ??= (string) Str::uuid(); $timeStamp = Carbon::now(); $temporaryDirectory = TemporaryDirectory::make(); Log::debug('Start exporting organization', [ @@ -365,9 +471,10 @@ class ExportService $zip->close(); // Upload ZIP file to private storage - $filename = 'export_'.$organization->getKey().'_'.$timeStamp->format('Y-m-d_H-i-s').'_'.$exportId.'.zip'; + $folder = 'exports/'.$organization->getKey(); + $filename = $exportId.'.zip'; Storage::disk(config('filesystems.private'))->putFileAs( - 'exports', + $folder, new File($temporaryDirectoryZip->path('export.zip')), $filename ); @@ -381,11 +488,11 @@ class ExportService 'export_id' => $exportId, ]); - return 'exports/'.$filename; + return $folder.'/'.$filename; } catch (UnavailableStream|CannotInsertRecord|Exception|LeagueCsvException $exception) { report($exception); - throw new ExportException; + throw new ExportException(previous: $exception); } } } diff --git a/config/export.php b/config/export.php new file mode 100644 index 00000000..85b96420 --- /dev/null +++ b/config/export.php @@ -0,0 +1,34 @@ + (int) (env('EXPORT_JOB_TIMEOUT') ?: 3600), + + 'queue' => env('EXPORT_QUEUE'), + + /* + |-------------------------------------------------------------------------- + | Export file retention + |-------------------------------------------------------------------------- + | + | Number of days the export files are kept after the export finished. + | The export itself is kept, only the file is deleted. + | + */ + + 'file_retention_days' => (int) (env('EXPORT_FILE_RETENTION_DAYS') ?: 7), + +]; diff --git a/config/scheduling.php b/config/scheduling.php index 0b09dd44..6509fde0 100644 --- a/config/scheduling.php +++ b/config/scheduling.php @@ -10,6 +10,7 @@ return [ 'self_hosting_check_for_update' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_CHECK_FOR_UPDATE', true), 'self_hosting_telemetry' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_TELEMETRY', true), 'import_prune' => (bool) env('SCHEDULING_TASK_IMPORT_PRUNE', true), + 'export_prune' => (bool) env('SCHEDULING_TASK_EXPORT_PRUNE', true), 'self_hosting_database_consistency' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_DATABASE_CONSISTENCY', false), ], ]; diff --git a/database/factories/ExportFactory.php b/database/factories/ExportFactory.php new file mode 100644 index 00000000..a248ff81 --- /dev/null +++ b/database/factories/ExportFactory.php @@ -0,0 +1,81 @@ + + */ +class ExportFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'type' => ExportType::Organization, + 'status' => ExportStatus::Pending, + 'file_path' => null, + 'error_message' => null, + 'error_details' => null, + 'started_at' => null, + 'finished_at' => null, + 'organization_id' => Organization::factory(), + 'user_id' => User::factory(), + ]; + } + + public function forOrganization(Organization $organization): self + { + return $this->state(fn (array $attributes): array => [ + 'organization_id' => $organization->getKey(), + ]); + } + + public function forUser(?User $user): self + { + return $this->state(fn (array $attributes): array => [ + 'user_id' => $user?->getKey(), + ]); + } + + public function running(): self + { + return $this->state(fn (array $attributes): array => [ + 'status' => ExportStatus::Running, + 'started_at' => Carbon::now(), + ]); + } + + public function completed(): self + { + return $this->state(fn (array $attributes): array => [ + 'status' => ExportStatus::Completed, + 'started_at' => Carbon::now()->subMinute(), + 'finished_at' => Carbon::now(), + 'file_path' => 'exports/'.fake()->uuid().'/'.fake()->uuid().'.zip', + ]); + } + + public function failed(): self + { + return $this->state(fn (array $attributes): array => [ + 'status' => ExportStatus::Failed, + 'started_at' => Carbon::now()->subMinute(), + 'finished_at' => Carbon::now(), + 'error_message' => 'Export failed', + ]); + } +} diff --git a/database/migrations/2026_11_18_000001_create_exports_table.php b/database/migrations/2026_11_18_000001_create_exports_table.php new file mode 100644 index 00000000..10e8e3fd --- /dev/null +++ b/database/migrations/2026_11_18_000001_create_exports_table.php @@ -0,0 +1,56 @@ +uuid('id')->primary(); + $table->string('type'); + $table->string('status'); + // Path of the export file on the private disk, null until the export is completed or after the file was pruned + $table->string('file_path')->nullable(); + $table->text('error_message')->nullable(); + $table->text('error_details')->nullable(); + $table->dateTime('started_at')->nullable(); + $table->dateTime('finished_at')->nullable(); + $table->uuid('organization_id'); + $table->foreign('organization_id') + ->references('id') + ->on('organizations') + ->restrictOnDelete() + ->cascadeOnUpdate(); + // User that started the export + $table->uuid('user_id')->nullable(); + $table->foreign('user_id') + ->references('id') + ->on('users') + ->nullOnDelete() + ->cascadeOnUpdate(); + $table->timestamps(); + $table->index(['organization_id', 'created_at']); + $table->index('finished_at'); + }); + + // Only one export per organization can be pending or running at the same time + DB::statement("CREATE UNIQUE INDEX exports_organization_id_active_unique ON exports (organization_id) WHERE status IN ('pending', 'running')"); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('exports'); + } +}; diff --git a/e2e/import-export.spec.ts b/e2e/import-export.spec.ts index 66542321..55e55320 100644 --- a/e2e/import-export.spec.ts +++ b/e2e/import-export.spec.ts @@ -72,7 +72,7 @@ test('test that export button triggers export and shows success modal', async ({ (response) => response.url().includes('/export') && response.request().method() === 'POST' && - response.status() === 200, + response.status() === 202, { timeout: 60000 } ), page.getByRole('button', { name: 'Export Organization Data' }).click(), @@ -80,6 +80,11 @@ test('test that export button triggers export and shows success modal', async ({ // Success modal should appear after export completes await expect(page.getByText('The export was successful!')).toBeVisible(); + await page.getByRole('button', { name: 'Close' }).click(); + + // The export is listed and can be downloaded again + await expect(page.getByText('Recent exports')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Download' }).first()).toBeVisible(); }); test('test that import type dropdown has multiple options', async ({ page }) => { diff --git a/lang/en/exceptions.php b/lang/en/exceptions.php index 110125b0..4513c3eb 100644 --- a/lang/en/exceptions.php +++ b/lang/en/exceptions.php @@ -7,6 +7,8 @@ use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization; use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed; use App\Exceptions\Api\EntityStillInUseApiException; +use App\Exceptions\Api\ExportAlreadyInProgressApiException; +use App\Exceptions\Api\ExportFileNotAvailableApiException; use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException; use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException; use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException; @@ -43,6 +45,8 @@ return [ OrganizationNeedsAtLeastOneOwner::KEY => 'Organization needs at least one owner', ChangingRoleToPlaceholderIsNotAllowed::KEY => 'Changing role to placeholder is not allowed', ExportException::KEY => 'Export failed, please try again later or contact support', + ExportAlreadyInProgressApiException::KEY => 'An export of this organization is already in progress', + ExportFileNotAvailableApiException::KEY => 'The export file is not available, please create a new export', OrganizationHasNoSubscriptionButMultipleMembersException::KEY => 'Organization has no subscription but multiple members', PdfRendererIsNotConfiguredException::KEY => 'PDF renderer is not configured', FeatureIsNotAvailableInFreePlanApiException::KEY => 'Feature is not available in free plan', diff --git a/resources/js/Pages/Teams/Partials/ExportData.vue b/resources/js/Pages/Teams/Partials/ExportData.vue index 7ae2f0c1..5f787145 100644 --- a/resources/js/Pages/Teams/Partials/ExportData.vue +++ b/resources/js/Pages/Teams/Partials/ExportData.vue @@ -1,8 +1,9 @@ @@ -54,7 +187,7 @@ async function exportData() { click here @@ -70,8 +203,9 @@ async function exportData() {

Export your solidtime organization data. This will include all clients, - projects, tasks, and time entries. You will receive a zip file with json files - for each entity. + projects, tasks, and time entries. You will receive a zip file with CSV files + for each entity. The export is prepared in the background, you can leave this + page and download it later.

@@ -81,9 +215,43 @@ async function exportData() { The following organization will be exported:
{{ organization?.name }} - Export Organization Data +
+ The export is being prepared, the download starts automatically when it is + ready. +
+ +
+
Recent exports
+
    +
  • +
    + + {{ + formatDateTimeLocalized( + item.created_at, + organization?.date_format, + organization?.time_format + ) + }} + + {{ statusLabel(item) }} +
    + + Download + +
  • +
diff --git a/resources/js/packages/api/src/index.ts b/resources/js/packages/api/src/index.ts index d1e1d5d3..6e57da30 100644 --- a/resources/js/packages/api/src/index.ts +++ b/resources/js/packages/api/src/index.ts @@ -100,7 +100,7 @@ export type MyMemberships = ZodiosResponseByAlias; +export type Export = ZodiosResponseByAlias['data']; export type ReportIndexResponse = ZodiosResponseByAlias; diff --git a/resources/js/packages/api/src/openapi.json.client.ts b/resources/js/packages/api/src/openapi.json.client.ts index efadf762..6fc09d67 100644 --- a/resources/js/packages/api/src/openapi.json.client.ts +++ b/resources/js/packages/api/src/openapi.json.client.ts @@ -42,6 +42,22 @@ const DestroyWithPasswordRequest = z password: z.string().nullish(), }) .passthrough(); +const ExportType = z.literal('organization'); +const ExportStatus = z.enum(['pending', 'running', 'completed', 'failed']); +const ExportResource = z + .object({ + id: z.string(), + type: ExportType, + status: ExportStatus, + download_available: z.boolean(), + error_message: z.union([z.string(), z.null()]), + user_id: z.union([z.string(), z.null()]), + started_at: z.union([z.string(), z.null()]), + finished_at: z.union([z.string(), z.null()]), + created_at: z.union([z.string(), z.null()]), + }) + .passthrough(); +const ExportCollection = z.array(ExportResource); const ImportRequest = z.object({ type: z.string(), data: z.string().max(52428800) }).passthrough(); const ImportSource = z.enum(['file', 'api']); const ImportStatus = z.enum(['pending', 'running', 'completed', 'failed']); @@ -871,6 +887,10 @@ export const schemas = { ClientResource, ClientStoreRequest, ClientUpdateRequest, + ExportType, + ExportStatus, + ExportResource, + ExportCollection, ImportRequest, ImportSource, ImportStatus, @@ -1643,6 +1663,8 @@ const endpoints = makeApi([ method: 'post', path: '/v1/organizations/:organization/export', alias: 'exportOrganization', + description: `The export is processed in the background. Use the returned export ID to poll the status of the export and +the download endpoint to get the download URL once the export is completed.`, requestFormat: 'json', parameters: [ { @@ -1651,7 +1673,162 @@ const endpoints = makeApi([ schema: z.string(), }, ], - response: z.object({ success: z.boolean(), download_url: z.string() }).passthrough(), + response: z.object({ data: ExportResource }).passthrough(), + errors: [ + { + status: 400, + description: `API exception`, + schema: z + .object({ error: z.boolean(), key: z.string(), message: z.string() }) + .passthrough(), + }, + { + 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(), + }, + ], + }, + { + method: 'get', + path: '/v1/organizations/:organization/exports', + alias: 'getExports', + requestFormat: 'json', + parameters: [ + { + name: 'organization', + type: 'Path', + schema: z.string(), + }, + { + name: 'page', + type: 'Query', + schema: z.number().int().gte(1).lte(2147483647).optional(), + }, + ], + response: z + .object({ + data: ExportCollection, + links: z + .object({ + first: z.union([z.string(), z.null()]), + last: z.union([z.string(), z.null()]), + prev: z.union([z.string(), z.null()]), + next: z.union([z.string(), z.null()]), + }) + .passthrough(), + meta: z + .object({ + current_page: z.number().int().gte(1), + from: z.union([z.number(), z.null()]), + last_page: z.number().int().gte(1), + links: z.array( + z + .object({ + url: z.union([z.string(), z.null()]), + label: z.string(), + active: z.boolean(), + }) + .passthrough() + ), + path: z.union([z.string(), z.null()]), + per_page: z.number().int().gte(0), + to: z.union([z.number(), z.null()]), + total: z.number().int().gte(0), + }) + .passthrough(), + }) + .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: 'get', + path: '/v1/organizations/:organization/exports/:export', + alias: 'getExport', + requestFormat: 'json', + parameters: [ + { + name: 'organization', + type: 'Path', + schema: z.string(), + }, + { + name: 'export', + type: 'Path', + schema: z.string(), + }, + ], + response: z.object({ data: ExportResource }).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(), + }, + ], + }, + { + method: 'get', + path: '/v1/organizations/:organization/exports/:export/download', + alias: 'downloadExport', + description: `The download URL is only valid for a short time, request a new one for every download.`, + requestFormat: 'json', + parameters: [ + { + name: 'organization', + type: 'Path', + schema: z.string(), + }, + { + name: 'export', + type: 'Path', + schema: z.string(), + }, + ], + response: z.object({ download_url: z.string() }).passthrough(), errors: [ { status: 400, diff --git a/routes/api.php b/routes/api.php index 2fe3a5a5..82a1ed17 100644 --- a/routes/api.php +++ b/routes/api.php @@ -192,6 +192,9 @@ Route::prefix('v1')->name('v1.')->group(static function (): void { // Export routes Route::name('export.')->prefix('/organizations/{organization}')->group(static function (): void { Route::post('/export', [ExportController::class, 'export'])->name('export'); + Route::get('/exports', [ExportController::class, 'index'])->name('exports.index'); + Route::get('/exports/{export}', [ExportController::class, 'show'])->name('exports.show'); + Route::get('/exports/{export}/download', [ExportController::class, 'download'])->name('exports.download'); }); }); diff --git a/tests/Unit/Console/Commands/Export/ExportPruneCommandTest.php b/tests/Unit/Console/Commands/Export/ExportPruneCommandTest.php new file mode 100644 index 00000000..176cddce --- /dev/null +++ b/tests/Unit/Console/Commands/Export/ExportPruneCommandTest.php @@ -0,0 +1,113 @@ + 3600, + 'export.file_retention_days' => 7, + ]); + Storage::fake(config('filesystems.private')); + } + + public function test_command_marks_stale_active_exports_as_failed(): void + { + // Arrange + $stalePending = Export::factory()->create([ + 'created_at' => now()->subHours(3), + ]); + $recentPending = Export::factory()->create([ + 'created_at' => now()->subMinutes(90), + ]); + $staleRunning = Export::factory()->running()->create([ + 'started_at' => now()->subMinutes(70), + ]); + $recentRunning = Export::factory()->running()->create([ + 'started_at' => now()->subMinutes(50), + ]); + $oldCompleted = Export::factory()->completed()->create([ + 'created_at' => now()->subHours(3), + 'started_at' => now()->subHours(3), + ]); + + // Act + $exitCode = $this->withoutMockingConsoleOutput()->artisan('export:prune'); + + // Assert + $this->assertSame(Command::SUCCESS, $exitCode); + $this->assertStringContainsString('Marked 2 stale exports as failed and deleted 0 export files.', Artisan::output()); + $this->assertSame(ExportStatus::Failed, $stalePending->refresh()->status); + $this->assertSame('Export could not be finished', $stalePending->error_message); + $this->assertSame(ExportStatus::Pending, $recentPending->refresh()->status); + $this->assertSame(ExportStatus::Failed, $staleRunning->refresh()->status); + $this->assertSame(ExportStatus::Running, $recentRunning->refresh()->status); + $this->assertSame(ExportStatus::Completed, $oldCompleted->refresh()->status); + } + + public function test_command_deletes_files_of_exports_after_retention_period(): void + { + // Arrange + $disk = Storage::disk(config('filesystems.private')); + $disk->put('export/old', 'old'); + $disk->put('export/new', 'new'); + $oldExport = Export::factory()->completed()->create([ + 'file_path' => 'export/old', + 'finished_at' => now()->subDays(8), + ]); + $newExport = Export::factory()->failed()->create([ + 'file_path' => 'export/new', + 'finished_at' => now()->subDays(6), + ]); + + // Act + $exitCode = $this->withoutMockingConsoleOutput()->artisan('export:prune'); + + // Assert + $this->assertSame(Command::SUCCESS, $exitCode); + $this->assertStringContainsString('Marked 0 stale exports as failed and deleted 1 export files.', Artisan::output()); + $this->assertNull($oldExport->refresh()->file_path); + $this->assertFalse($disk->exists('export/old')); + $this->assertSame('export/new', $newExport->refresh()->file_path); + $this->assertTrue($disk->exists('export/new')); + } + + public function test_command_does_not_change_anything_in_dry_run_mode(): void + { + // Arrange + $disk = Storage::disk(config('filesystems.private')); + $disk->put('export/old', 'old'); + $staleExport = Export::factory()->running()->create([ + 'started_at' => now()->subHours(3), + ]); + $oldExport = Export::factory()->completed()->create([ + 'file_path' => 'export/old', + 'finished_at' => now()->subDays(8), + ]); + + // Act + $exitCode = $this->withoutMockingConsoleOutput()->artisan('export:prune', ['--dry-run' => true]); + + // Assert + $this->assertSame(Command::SUCCESS, $exitCode); + $this->assertStringContainsString('Marked 1 stale exports as failed and deleted 1 export files.', Artisan::output()); + $this->assertSame(ExportStatus::Running, $staleExport->refresh()->status); + $this->assertSame('export/old', $oldExport->refresh()->file_path); + $this->assertTrue($disk->exists('export/old')); + } +} diff --git a/tests/Unit/Endpoint/Api/V1/ExportEndpointTest.php b/tests/Unit/Endpoint/Api/V1/ExportEndpointTest.php index 01b3f0c6..f485eaba 100644 --- a/tests/Unit/Endpoint/Api/V1/ExportEndpointTest.php +++ b/tests/Unit/Endpoint/Api/V1/ExportEndpointTest.php @@ -4,14 +4,14 @@ declare(strict_types=1); namespace Tests\Unit\Endpoint\Api\V1; +use App\Enums\ExportStatus; use App\Http\Controllers\Api\V1\ExportController; +use App\Jobs\ProcessExport; +use App\Models\Export; use App\Models\Organization; -use App\Service\Export\ExportException; -use App\Service\Export\ExportService; use Illuminate\Support\Carbon; -use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Queue; use Laravel\Passport\Passport; -use Mockery\MockInterface; use PHPUnit\Framework\Attributes\UsesClass; #[UsesClass(ExportController::class)] @@ -21,9 +21,7 @@ class ExportEndpointTest extends ApiEndpointTestAbstract { // Arrange $data = $this->createUserWithPermission(); - $this->mock(ExportService::class, function (MockInterface $mock): void { - $mock->shouldNotReceive('export'); - }); + Queue::fake(); Passport::actingAs($data->user); // Act @@ -31,94 +29,276 @@ class ExportEndpointTest extends ApiEndpointTestAbstract // Assert $response->assertForbidden(); + $this->assertSame(0, Export::query()->count()); + Queue::assertNothingPushed(); } - public function test_export_return_error_message_if_export_fails(): void + public function test_export_creates_pending_export_and_dispatches_job(): void { - $user = $this->createUserWithPermission([ + // Arrange + $data = $this->createUserWithPermission([ 'export', ]); - $this->mock(ExportService::class, function (MockInterface $mock) use (&$user): void { - $mock->shouldReceive('export') - ->withArgs(function (Organization $organization) use (&$user): bool { - return $organization->is($user->organization); - }) - ->andThrow(new ExportException) - ->once(); - }); - Passport::actingAs($user->user); + Queue::fake(); + Passport::actingAs($data->user); // Act - $response = $this->postJson(route('api.v1.export.export', ['organization' => $user->organization->getKey()])); + $response = $this->postJson(route('api.v1.export.export', ['organization' => $data->organization->getKey()])); + + // Assert + $response->assertStatus(202); + /** @var Export $export */ + $export = Export::query()->sole(); + $this->assertSame(ExportStatus::Pending, $export->status); + $this->assertSame($data->organization->getKey(), $export->organization_id); + $this->assertSame($data->user->getKey(), $export->user_id); + $response->assertJsonPath('data.id', $export->getKey()); + $response->assertJsonPath('data.type', 'organization'); + $response->assertJsonPath('data.status', 'pending'); + $response->assertJsonPath('data.download_available', false); + $response->assertJsonPath('data.error_message', null); + $response->assertJsonPath('data.user_id', $data->user->getKey()); + Queue::assertPushed(ProcessExport::class, fn (ProcessExport $job): bool => $job->export->is($export)); + } + + public function test_export_fails_if_export_of_organization_is_already_in_progress(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + Export::factory()->forOrganization($data->organization)->running()->create(); + Queue::fake(); + Passport::actingAs($data->user); + + // Act + $response = $this->postJson(route('api.v1.export.export', ['organization' => $data->organization->getKey()])); // Assert $response->assertStatus(400); $response->assertExactJson([ 'error' => true, - 'key' => 'export', - 'message' => 'Export failed, please try again later or contact support', + 'key' => 'export_already_in_progress', + 'message' => 'An export of this organization is already in progress', ]); + $this->assertSame(1, Export::query()->count()); + Queue::assertNothingPushed(); } - public function test_export_calls_export_service_if_user_has_permission(): void + public function test_index_fails_if_user_does_not_have_permission(): void { // Arrange - $user = $this->createUserWithPermission([ - 'export', - ]); - $filepath = 'exports/path.zip'; - Storage::fake('local'); - $now = Carbon::now(); - $this->travelTo($now); - $this->mock(ExportService::class, function (MockInterface $mock) use (&$user, $filepath): void { - $mock->shouldReceive('export') - ->withArgs(function (Organization $organization) use (&$user): bool { - return $organization->is($user->organization); - }) - ->andReturn($filepath) - ->once(); - }); - Passport::actingAs($user->user); + $data = $this->createUserWithPermission(); + Passport::actingAs($data->user); // Act - $response = $this->postJson(route('api.v1.export.export', [ - 'organization' => $user->organization->getKey(), + $response = $this->getJson(route('api.v1.export.exports.index', ['organization' => $data->organization->getKey()])); + + // Assert + $response->assertForbidden(); + } + + public function test_index_returns_exports_of_organization_newest_first(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $older = Export::factory()->forOrganization($data->organization)->completed()->create([ + 'created_at' => Carbon::now()->subDay(), + ]); + $newer = Export::factory()->forOrganization($data->organization)->failed()->create([ + 'created_at' => Carbon::now(), + ]); + Export::factory()->forOrganization(Organization::factory()->create())->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.index', ['organization' => $data->organization->getKey()])); + + // Assert + $response->assertOk(); + $response->assertJsonCount(2, 'data'); + $response->assertJsonPath('data.0.id', $newer->getKey()); + $response->assertJsonPath('data.0.status', 'failed'); + $response->assertJsonPath('data.0.error_message', 'Export failed'); + $response->assertJsonPath('data.0.download_available', false); + $response->assertJsonPath('data.1.id', $older->getKey()); + $response->assertJsonPath('data.1.download_available', true); + $response->assertJsonMissingPath('data.0.file_path'); + $response->assertJsonMissingPath('data.0.error_details'); + } + + public function test_show_fails_if_user_does_not_have_permission(): void + { + // Arrange + $data = $this->createUserWithPermission(); + $export = Export::factory()->forOrganization($data->organization)->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.show', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), ])); // Assert - $response->assertStatus(200); - $response->assertJsonPath('success', true); - $this->assertStringContainsString($filepath, $response->json('download_url')); + $response->assertForbidden(); } - public function test_export_requests_the_download_url_as_an_attachment(): void + public function test_show_fails_if_export_belongs_to_other_organization(): void { // Arrange - $user = $this->createUserWithPermission([ + $data = $this->createUserWithPermission([ 'export', ]); - $filepath = 'exports/export_test.zip'; - $this->mock(ExportService::class, function (MockInterface $mock) use (&$user, $filepath): void { - $mock->shouldReceive('export') - ->withArgs(function (Organization $organization) use (&$user): bool { - return $organization->is($user->organization); - }) - ->andReturn($filepath) - ->once(); - }); - Passport::actingAs($user->user); + $export = Export::factory()->completed()->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.show', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertForbidden(); + } + + public function test_show_returns_export(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $export = Export::factory()->forOrganization($data->organization)->running()->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.show', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertOk(); + $response->assertJsonPath('data.id', $export->getKey()); + $response->assertJsonPath('data.status', 'running'); + $response->assertJsonPath('data.download_available', false); + } + + public function test_download_fails_if_user_does_not_have_permission(): void + { + // Arrange + $data = $this->createUserWithPermission(); + $export = Export::factory()->forOrganization($data->organization)->completed()->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.download', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertForbidden(); + } + + public function test_download_fails_if_export_belongs_to_other_organization(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $export = Export::factory()->completed()->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.download', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertForbidden(); + } + + public function test_download_fails_if_export_is_not_completed(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $export = Export::factory()->forOrganization($data->organization)->running()->create(); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.download', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertStatus(400); + $response->assertJsonPath('key', 'export_file_not_available'); + } + + public function test_download_fails_if_export_file_was_pruned(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $export = Export::factory()->forOrganization($data->organization)->completed()->create([ + 'file_path' => null, + ]); + Passport::actingAs($data->user); + + // Act + $response = $this->getJson(route('api.v1.export.exports.download', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), + ])); + + // Assert + $response->assertStatus(400); + $response->assertJsonPath('key', 'export_file_not_available'); + } + + public function test_download_returns_temporary_url_as_attachment_with_readable_filename(): void + { + // Arrange + $data = $this->createUserWithPermission([ + 'export', + ]); + $data->organization->name = 'Acme GmbH'; + $data->organization->save(); + $data->user->timezone = 'Europe/Vienna'; + $data->user->save(); + $export = Export::factory()->forOrganization($data->organization)->completed()->create([ + 'id' => '1f2470b2-19d9-4d45-8fc3-eb5c1e6040e6', + 'file_path' => 'exports/test/export.zip', + 'created_at' => Carbon::parse('2026-11-18 10:20:30', 'UTC'), + ]); + Passport::actingAs($data->user); $capturedOptions = $this->captureTemporaryUrlOptions(); // Act - $response = $this->postJson(route('api.v1.export.export', [ - 'organization' => $user->organization->getKey(), + $response = $this->getJson(route('api.v1.export.exports.download', [ + 'organization' => $data->organization->getKey(), + 'export' => $export->getKey(), ])); // Assert - $response->assertStatus(200); + $response->assertOk(); + $response->assertExactJson([ + 'download_url' => 'https://storage.fake/exports/test/export.zip', + ]); $options = $capturedOptions(); $this->assertIsArray($options); - $this->assertSame('attachment; filename="export_test.zip"', $options['ResponseContentDisposition'] ?? null); - $this->assertSame('https://storage.fake/'.$filepath, $response->json('download_url')); + $this->assertSame( + 'attachment; filename="solidtime-export_acme-gmbh_2026-11-18_11-20_1f2470b2.zip"', + $options['ResponseContentDisposition'] ?? null + ); } } diff --git a/tests/Unit/Exceptions/Api/ApiExceptionTest.php b/tests/Unit/Exceptions/Api/ApiExceptionTest.php index c698913f..9ad39261 100644 --- a/tests/Unit/Exceptions/Api/ApiExceptionTest.php +++ b/tests/Unit/Exceptions/Api/ApiExceptionTest.php @@ -10,6 +10,8 @@ use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization; use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed; use App\Exceptions\Api\EntityStillInUseApiException; +use App\Exceptions\Api\ExportAlreadyInProgressApiException; +use App\Exceptions\Api\ExportFileNotAvailableApiException; use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException; use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException; use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException; @@ -44,6 +46,8 @@ class ApiExceptionTest extends TestCase yield ChangingRoleOfPlaceholderIsNotAllowed::class => [new ChangingRoleOfPlaceholderIsNotAllowed]; yield ChangingRoleToPlaceholderIsNotAllowed::class => [new ChangingRoleToPlaceholderIsNotAllowed]; yield EntityStillInUseApiException::class => [new EntityStillInUseApiException('member', 'time_entry')]; + yield ExportAlreadyInProgressApiException::class => [new ExportAlreadyInProgressApiException]; + yield ExportFileNotAvailableApiException::class => [new ExportFileNotAvailableApiException]; yield FeatureIsNotAvailableInFreePlanApiException::class => [new FeatureIsNotAvailableInFreePlanApiException]; yield InactiveUserCanNotBeUsedApiException::class => [new InactiveUserCanNotBeUsedApiException]; yield InvitationForTheEmailAlreadyExistsApiException::class => [new InvitationForTheEmailAlreadyExistsApiException]; diff --git a/tests/Unit/Filament/Resources/ExportResourceTest.php b/tests/Unit/Filament/Resources/ExportResourceTest.php new file mode 100644 index 00000000..162cc7c0 --- /dev/null +++ b/tests/Unit/Filament/Resources/ExportResourceTest.php @@ -0,0 +1,60 @@ +withPersonalOrganization()->create([ + 'email' => 'admin@example.com', + ]); + + $this->actingAs($user); + } + + public function test_can_list_exports(): void + { + // Arrange + $exports = collect([ + Export::factory()->create(), + Export::factory()->running()->create(), + Export::factory()->completed()->create(), + Export::factory()->failed()->create(), + ]); + + // Act + $response = Livewire::test(ExportResource\Pages\ListExports::class); + + // Assert + $response->assertSuccessful(); + $response->assertCanSeeTableRecords($exports); + } + + public function test_can_see_view_page_of_export(): void + { + // Arrange + $export = Export::factory()->completed()->create(); + + // Act + $response = Livewire::test(ExportResource\Pages\ViewExport::class, [ + 'record' => $export->getKey(), + ]); + + // Assert + $response->assertSuccessful(); + } +} diff --git a/tests/Unit/Jobs/ProcessExportTest.php b/tests/Unit/Jobs/ProcessExportTest.php new file mode 100644 index 00000000..7054d20d --- /dev/null +++ b/tests/Unit/Jobs/ProcessExportTest.php @@ -0,0 +1,113 @@ +create(); + $this->mock(ExportService::class, function (MockInterface $mock) use ($export): void { + $mock->shouldReceive('process') + ->withArgs(fn (Export $processedExport): bool => $processedExport->is($export)) + ->once(); + }); + + // Act + ProcessExport::dispatchSync($export); + } + + public function test_job_uses_timeout_and_queue_from_config(): void + { + // Arrange + config([ + 'export.job_timeout' => 123, + 'export.queue' => 'exports', + ]); + $export = Export::factory()->create(); + + // Act + $job = new ProcessExport($export); + + // Assert + $this->assertSame(123, $job->timeout); + $this->assertSame(1, $job->tries); + $this->assertSame('exports', $job->queue); + } + + public function test_failed_marks_active_export_as_failed(): void + { + // Arrange + $export = Export::factory()->running()->create(); + $job = new ProcessExport($export); + + // Act + $job->failed(new RuntimeException('Worker crashed')); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Failed, $export->status); + $this->assertSame('Export could not be finished', $export->error_message); + $this->assertNotNull($export->finished_at); + } + + public function test_failed_marks_export_as_failed_on_timeout(): void + { + // Arrange + $export = Export::factory()->running()->create(); + $job = new ProcessExport($export); + + // Act + $job->failed(new TimeoutExceededException('App\\Jobs\\ProcessExport has timed out.')); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Failed, $export->status); + $this->assertSame('Export could not be finished', $export->error_message); + } + + public function test_failed_does_not_change_finished_export(): void + { + // Arrange + $export = Export::factory()->completed()->create(); + $job = new ProcessExport($export); + + // Act + $job->failed(new RuntimeException('Worker crashed')); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Completed, $export->status); + $this->assertNull($export->error_message); + } + + public function test_failed_does_not_mark_export_as_failed_if_job_was_handed_out_again_while_still_running(): void + { + // Arrange + $export = Export::factory()->running()->create(); + $job = new ProcessExport($export); + + // Act + $job->failed(new MaxAttemptsExceededException('App\\Jobs\\ProcessExport has been attempted too many times.')); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Running, $export->status); + $this->assertNull($export->error_message); + } +} diff --git a/tests/Unit/Model/ExportModelTest.php b/tests/Unit/Model/ExportModelTest.php new file mode 100644 index 00000000..88bee3c1 --- /dev/null +++ b/tests/Unit/Model/ExportModelTest.php @@ -0,0 +1,72 @@ +create([ + 'name' => $organizationName, + ]); + + return Export::factory()->forOrganization($organization)->completed()->create([ + 'id' => '1f2470b2-19d9-4d45-8fc3-eb5c1e6040e6', + 'created_at' => Carbon::parse('2026-11-18 10:20:30', 'UTC'), + ]); + } + + /** + * @return iterable + */ + public static function organizationNameProvider(): iterable + { + yield 'simple name' => ['Acme GmbH', 'acme-gmbh']; + yield 'umlauts and special characters' => ['Müller & Söhne GmbH', 'muller-sohne-gmbh']; + yield 'emoji only name falls back' => ['🚀🚀', 'organization']; + yield 'long name is truncated without trailing dash' => [ + 'The Quite Long Organization Name Of Example Industries International', + 'the-quite-long-organization-name-of-exam', + ]; + yield 'truncation at a dash is trimmed' => [ + str_repeat('a', 39).' bbb', + str_repeat('a', 39), + ]; + } + + #[DataProvider('organizationNameProvider')] + public function test_download_filename_contains_slug_of_organization_name(string $organizationName, string $expectedSlug): void + { + // Arrange + $export = $this->createExport($organizationName); + + // Act + $filename = $export->getDownloadFilename('UTC'); + + // Assert + $this->assertSame('solidtime-export_'.$expectedSlug.'_2026-11-18_10-20_1f2470b2.zip', $filename); + } + + public function test_download_filename_uses_date_in_given_timezone(): void + { + // Arrange + $export = $this->createExport('Acme'); + $export->created_at = Carbon::parse('2026-11-18 23:30:00', 'UTC'); + + // Act + $filename = $export->getDownloadFilename('Europe/Vienna'); + + // Assert + $this->assertSame('solidtime-export_acme_2026-11-19_00-30_1f2470b2.zip', $filename); + $this->assertSame('UTC', $export->created_at->getTimezone()->getName()); + } +} diff --git a/tests/Unit/Service/DeletionServiceTest.php b/tests/Unit/Service/DeletionServiceTest.php index 741b87a4..5f8325ee 100644 --- a/tests/Unit/Service/DeletionServiceTest.php +++ b/tests/Unit/Service/DeletionServiceTest.php @@ -10,6 +10,7 @@ use App\Events\BeforeUserDeletion; use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers; use App\Models\Audit; use App\Models\Client; +use App\Models\Export; use App\Models\Goal; use App\Models\Import; use App\Models\Member; @@ -67,7 +68,8 @@ class DeletionServiceTest extends TestCaseWithDatabase * owner: User, * reports: Collection, * goals: Collection, - * imports: Collection + * imports: Collection, + * exports: Collection * } */ private function createOrganizationWithAllRelations(): object @@ -123,6 +125,13 @@ class DeletionServiceTest extends TestCaseWithDatabase $importWithoutFile = Import::factory()->forOrganization($organization)->forUser($userEmployee)->failed()->create(); $imports = collect([$importWithFile, $importWithoutFile]); + $exportWithFile = Export::factory()->forOrganization($organization)->forUser($userOwner)->completed()->create([ + 'file_path' => 'exports/'.$organization->getKey().'/'.Str::uuid().'.zip', + ]); + Storage::disk(config('filesystems.private'))->put($exportWithFile->file_path, 'export data'); + $exportWithoutFile = Export::factory()->forOrganization($organization)->forUser($userEmployee)->failed()->create(); + $exports = collect([$exportWithFile, $exportWithoutFile]); + $timeEntries = TimeEntry::factory()->forOrganization($organization)->forMember($memberOwner)->createMany(2); $timeEntriesWithTask = TimeEntry::factory()->forTask($task1)->forOrganization($organization)->forMember($memberEmployee)->createMany(2); $timeEntriesWithProject = TimeEntry::factory()->forProject($projectWithClient)->forOrganization($organization)->forMember($memberPlaceholder)->createMany(2); @@ -141,6 +150,7 @@ class DeletionServiceTest extends TestCaseWithDatabase 'reports' => $reports, 'goals' => $goals, 'imports' => $imports, + 'exports' => $exports, ]; } @@ -160,6 +170,8 @@ class DeletionServiceTest extends TestCaseWithDatabase $this->assertSame(0, Goal::query()->whereBelongsTo($organization, 'organization')->count()); $this->assertSame(0, Import::query()->whereBelongsTo($organization, 'organization')->count()); $this->assertSame([], Storage::disk(config('filesystems.private'))->allFiles('import/'.$organization->getKey())); + $this->assertSame(0, Export::query()->whereBelongsTo($organization, 'organization')->count()); + $this->assertSame([], Storage::disk(config('filesystems.private'))->allFiles('exports/'.$organization->getKey())); $this->assertSame(0, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count()); } @@ -176,6 +188,8 @@ class DeletionServiceTest extends TestCaseWithDatabase $this->assertSame(2, Goal::query()->whereBelongsTo($organization, 'organization')->count()); $this->assertSame(2, Import::query()->whereBelongsTo($organization, 'organization')->count()); $this->assertCount(1, Storage::disk(config('filesystems.private'))->allFiles('import/'.$organization->getKey())); + $this->assertSame(2, Export::query()->whereBelongsTo($organization, 'organization')->count()); + $this->assertCount(1, Storage::disk(config('filesystems.private'))->allFiles('exports/'.$organization->getKey())); $this->assertSame($specialCase ? 7 : 6, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count()); } diff --git a/tests/Unit/Service/Export/ExportServiceTest.php b/tests/Unit/Service/Export/ExportServiceTest.php index ae1919f7..bc4c5df0 100644 --- a/tests/Unit/Service/Export/ExportServiceTest.php +++ b/tests/Unit/Service/Export/ExportServiceTest.php @@ -4,7 +4,12 @@ declare(strict_types=1); namespace Tests\Unit\Service\Export; +use App\Enums\ExportStatus; +use App\Enums\ExportType; +use App\Exceptions\Api\ExportAlreadyInProgressApiException; +use App\Jobs\ProcessExport; use App\Models\Client; +use App\Models\Export; use App\Models\Member; use App\Models\Organization; use App\Models\OrganizationInvitation; @@ -14,10 +19,15 @@ use App\Models\Tag; use App\Models\Task; use App\Models\TimeEntry; use App\Models\User; +use App\Service\Export\ExportException; use App\Service\Export\ExportService; +use Illuminate\Database\UniqueConstraintViolationException; +use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Storage; use League\Csv\Reader; +use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; +use RuntimeException; use Tests\TestCaseWithDatabase; use ZipArchive; @@ -92,4 +102,147 @@ class ExportServiceTest extends TestCaseWithDatabase $this->assertSame('work', $typesById[$workEntry->getKey()]); $this->assertSame('break', $typesById[$breakEntry->getKey()]); } + + public function test_create_organization_export_creates_pending_export_and_dispatches_job(): void + { + // Arrange + Queue::fake(); + $user = User::factory()->create(); + $organization = Organization::factory()->create(); + + // Act + $export = app(ExportService::class)->createOrganizationExport($organization, $user); + + // Assert + $export->refresh(); + $this->assertSame(ExportType::Organization, $export->type); + $this->assertSame(ExportStatus::Pending, $export->status); + $this->assertSame($organization->getKey(), $export->organization_id); + $this->assertSame($user->getKey(), $export->user_id); + $this->assertNull($export->file_path); + Queue::assertPushed(ProcessExport::class, fn (ProcessExport $job): bool => $job->export->is($export)); + } + + public function test_create_organization_export_throws_exception_if_export_is_already_in_progress(): void + { + // Arrange + Queue::fake(); + $organization = Organization::factory()->create(); + Export::factory()->forOrganization($organization)->create(); + + // Act + try { + app(ExportService::class)->createOrganizationExport($organization, null); + $this->fail('Expected exception was not thrown'); + } catch (ExportAlreadyInProgressApiException) { + // Assert + $this->assertSame(1, Export::query()->count()); + Queue::assertNothingPushed(); + } + } + + public function test_create_organization_export_allows_new_export_if_previous_exports_are_finished(): void + { + // Arrange + Queue::fake(); + $organization = Organization::factory()->create(); + Export::factory()->forOrganization($organization)->completed()->create(); + Export::factory()->forOrganization($organization)->failed()->create(); + + // Act + $export = app(ExportService::class)->createOrganizationExport($organization, null); + + // Assert + $this->assertSame(3, Export::query()->count()); + Queue::assertPushed(ProcessExport::class, fn (ProcessExport $job): bool => $job->export->is($export)); + } + + public function test_database_allows_only_one_active_export_per_organization(): void + { + // Arrange + $organization = Organization::factory()->create(); + Export::factory()->forOrganization($organization)->create(); + + // Assert + $this->expectException(UniqueConstraintViolationException::class); + + // Act + Export::factory()->forOrganization($organization)->running()->create(); + } + + public function test_process_creates_export_file_and_marks_export_as_completed(): void + { + // Arrange + $this->mockPrivateStorage(); + $organization = $this->getFullOrganization(); + $export = Export::factory()->forOrganization($organization)->create(); + + // Act + app(ExportService::class)->process($export); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Completed, $export->status); + $this->assertSame('exports/'.$organization->getKey().'/'.$export->getKey().'.zip', $export->file_path); + $this->assertNotNull($export->started_at); + $this->assertNotNull($export->finished_at); + $this->assertNull($export->error_message); + Storage::disk(config('filesystems.private'))->assertExists($export->file_path); + } + + public function test_process_marks_export_as_failed_with_error_details_if_export_fails(): void + { + // Arrange + $organization = Organization::factory()->create(); + $export = Export::factory()->forOrganization($organization)->create(); + $this->partialMock(ExportService::class, function (MockInterface $mock): void { + $mock->shouldReceive('export') + ->once() + ->andThrow(new ExportException(new RuntimeException('Disk is full'))); + }); + + // Act + app(ExportService::class)->process($export); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Failed, $export->status); + $this->assertSame('Export failed, please try again later or contact support', $export->error_message); + $this->assertNull($export->file_path); + $this->assertNotNull($export->finished_at); + $this->assertStringContainsString('RuntimeException: Disk is full', (string) $export->error_details); + } + + public function test_process_skips_export_that_is_not_pending(): void + { + // Arrange + $export = Export::factory()->completed()->create(); + $filePath = $export->file_path; + $this->partialMock(ExportService::class, function (MockInterface $mock): void { + $mock->shouldNotReceive('export'); + }); + + // Act + app(ExportService::class)->process($export); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Completed, $export->status); + $this->assertSame($filePath, $export->file_path); + } + + public function test_mark_as_failed_sets_status_message_and_finished_at(): void + { + // Arrange + $export = Export::factory()->running()->create(); + + // Act + app(ExportService::class)->markAsFailed($export, 'Export could not be finished'); + + // Assert + $export->refresh(); + $this->assertSame(ExportStatus::Failed, $export->status); + $this->assertSame('Export could not be finished', $export->error_message); + $this->assertNotNull($export->finished_at); + } }