Store exports in the database and process them in a queued job

This commit is contained in:
Constantin Graf
2026-11-18 17:18:15 +01:00
committed by Constantin Graf
parent a440687a41
commit 4c8215a889
36 changed files with 2248 additions and 108 deletions

View File

@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Export;
use App\Enums\ExportStatus;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ExportPruneCommand extends Command
{
/**
* Time in seconds a running export can exceed the job timeout before it is considered stale.
* The queue worker kills the job after the timeout, so this only needs to cover small delays.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending export can exceed the job timeout before it is considered stale,
* this covers the time the job waits in the queue.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'export:prune '.
' { --dry-run : Do not actually save or delete anything, just output what would happen }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Marks stale exports as failed and deletes export files after the retention period.';
/**
* Execute the console command.
*/
public function handle(ExportService $exportService): int
{
$dryRun = (bool) $this->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<int, Export> $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<int, Export> $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;
}
}

View File

@@ -48,6 +48,10 @@ class Kernel extends ConsoleKernel
->when(fn (): bool => config('scheduling.tasks.import_prune')) ->when(fn (): bool => config('scheduling.tasks.import_prune'))
->everyFiveMinutes(); ->everyFiveMinutes();
$schedule->command('export:prune')
->when(fn (): bool => config('scheduling.tasks.export_prune'))
->everyFiveMinutes();
$schedule->command('self-host:database-consistency') $schedule->command('self-host:database-consistency')
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency')) ->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))
->everySixHours(); ->everySixHours();

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ExportStatus: string
{
use LaravelEnumHelper;
case Pending = 'pending';
case Running = 'running';
case Completed = 'completed';
case Failed = 'failed';
/**
* Statuses of exports that are not finished yet, only one export per organization can have one of these statuses.
*
* @return array<ExportStatus>
*/
public static function active(): array
{
return [self::Pending, self::Running];
}
public function isActive(): bool
{
return in_array($this, self::active(), true);
}
}

17
app/Enums/ExportType.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ExportType: string
{
use LaravelEnumHelper;
/**
* Full export of all data of an organization (ZIP with CSV files), can be imported with the solidtime importer
*/
case Organization = 'organization';
}

View File

@@ -8,14 +8,15 @@ use Exception;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use LogicException; use LogicException;
use Throwable;
abstract class ApiException extends Exception abstract class ApiException extends Exception
{ {
public const string KEY = 'api_exception'; public const string KEY = 'api_exception';
public function __construct() public function __construct(?Throwable $previous = null)
{ {
parent::__construct(static::KEY); parent::__construct(static::KEY, 0, $previous);
} }
/** /**

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class ExportAlreadyInProgressApiException extends ApiException
{
public const string KEY = 'export_already_in_progress';
public function report(): bool
{
return true;
}
}

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class ExportFileNotAvailableApiException extends ApiException
{
public const string KEY = 'export_file_not_available';
public function report(): bool
{
return true;
}
}

View File

@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Filament\Resources\ExportResource\Pages\ListExports;
use App\Filament\Resources\ExportResource\Pages\ViewExport;
use App\Models\Export;
use Carbon\CarbonInterface;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ExportResource extends Resource
{
protected static ?string $model = Export::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-archive-box-arrow-down';
protected static string|\UnitEnum|null $navigationGroup = 'Timetracking';
protected static ?int $navigationSort = 10;
public static function form(Schema $schema): Schema
{
return $schema
->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}'),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ExportResource\Pages;
use App\Filament\Resources\ExportResource;
use Filament\Resources\Pages\ListRecords;
class ListExports extends ListRecords
{
protected static string $resource = ExportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\ExportResource\Pages;
use App\Filament\Resources\ExportResource;
use Filament\Resources\Pages\ViewRecord;
class ViewExport extends ViewRecord
{
protected static string $resource = ExportResource::class;
protected function getHeaderActions(): array
{
return [
];
}
}

View File

@@ -4,8 +4,14 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1; namespace App\Http\Controllers\Api\V1;
use App\Enums\ExportStatus;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Exceptions\Api\ExportFileNotAvailableApiException;
use App\Http\Requests\V1\Export\ExportIndexRequest;
use App\Http\Resources\V1\Export\ExportCollection;
use App\Http\Resources\V1\Export\ExportResource;
use App\Models\Export;
use App\Models\Organization; use App\Models\Organization;
use App\Service\Export\ExportException;
use App\Service\Export\ExportService; use App\Service\Export\ExportService;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -17,8 +23,11 @@ class ExportController extends Controller
/** /**
* Export data of an organization * Export data of an organization
* *
* 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.
*
* @throws AuthorizationException * @throws AuthorizationException
* @throws ExportException * @throws ExportAlreadyInProgressApiException
* *
* @operationId exportOrganization * @operationId exportOrganization
*/ */
@@ -26,15 +35,85 @@ class ExportController extends Controller
{ {
$this->checkPermission($organization, 'export'); $this->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')) $downloadUrl = Storage::disk(config('filesystems.private'))
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [ ->temporaryUrl($export->file_path, Carbon::now()->addMinutes(10), [
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"', 'ResponseContentDisposition' => 'attachment; filename="'.$export->getDownloadFilename($this->user()->timezone).'"',
]); ]);
return new JsonResponse([ return new JsonResponse([
'success' => true, /** @var string $download_url Temporary download URL of the export file, valid for 10 minutes */
'download_url' => $downloadUrl, 'download_url' => $downloadUrl,
], 200); ], 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');
}
}
} }

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Export;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Contracts\Validation\ValidationRule;
class ExportIndexRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}

View File

@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Export;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ExportCollection extends ResourceCollection
{
/**
* The resource that this resource collects.
*
* @var string
*/
public $collects = ExportResource::class;
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Export;
use App\Enums\ExportStatus;
use App\Http\Resources\V1\BaseResource;
use App\Models\Export;
use Illuminate\Http\Request;
/**
* @property Export $resource
*/
class ExportResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
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),
];
}
}

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\TimeoutExceededException;
use Throwable;
class ProcessExport implements ShouldDispatchAfterCommit, ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Delete the job if its models no longer exist.
*/
public bool $deleteWhenMissingModels = true;
/**
* Exports are not retried, the user can start a new export.
*/
public int $tries = 1;
public int $timeout;
public Export $export;
/**
* Create a new job instance.
*/
public function __construct(Export $export)
{
$this->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');
}
}
}

111
app/Models/Export.php Normal file
View File

@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Models\Concerns\HasUuids;
use Database\Factories\ExportFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* @property string $id
* @property ExportType $type
* @property ExportStatus $status
* @property string|null $file_path
* @property string|null $error_message
* @property string|null $error_details
* @property Carbon|null $started_at
* @property Carbon|null $finished_at
* @property string $organization_id
* @property string|null $user_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Organization $organization
* @property-read User|null $user
*
* @method static ExportFactory factory()
*/
class Export extends Model
{
/** @use HasFactory<ExportFactory> */
use HasFactory;
use HasUuids;
private const int DOWNLOAD_FILENAME_SLUG_MAX_LENGTH = 40;
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'type' => ExportType::class,
'status' => ExportStatus::class,
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'error_details',
];
/**
* @return BelongsTo<Organization, $this>
*/
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<User, $this>
*/
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<Export> $builder
* @return Builder<Export>
*/
public function scopeActive(Builder $builder): Builder
{
return $builder->whereIn('status', ExportStatus::active());
}
}

View File

@@ -9,6 +9,7 @@ use App\Events\BeforeOrganizationDeletion;
use App\Events\BeforeUserDeletion; use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers; use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Client; use App\Models\Client;
use App\Models\Export;
use App\Models\Goal; use App\Models\Goal;
use App\Models\Import; use App\Models\Import;
use App\Models\Member; 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 // Reset the current organization
$organization->owner() $organization->owner()
->where('current_team_id', $organization->getKey()) ->where('current_team_id', $organization->getKey())

View File

@@ -4,7 +4,12 @@ declare(strict_types=1);
namespace App\Service\Export; 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\Client;
use App\Models\Export;
use App\Models\Member; use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Models\OrganizationInvitation; use App\Models\OrganizationInvitation;
@@ -13,8 +18,10 @@ use App\Models\ProjectMember;
use App\Models\Tag; use App\Models\Tag;
use App\Models\Task; use App\Models\Task;
use App\Models\TimeEntry; use App\Models\TimeEntry;
use App\Models\User;
use Exception; use Exception;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\File; use Illuminate\Http\File;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@@ -25,18 +32,117 @@ use League\Csv\Exception as LeagueCsvException;
use League\Csv\UnavailableStream; use League\Csv\UnavailableStream;
use League\Csv\Writer; use League\Csv\Writer;
use Spatie\TemporaryDirectory\TemporaryDirectory; use Spatie\TemporaryDirectory\TemporaryDirectory;
use Throwable;
use ZipArchive; use ZipArchive;
class ExportService class ExportService
{ {
public const string VERSION = '1.0'; 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 * @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(); $timeStamp = Carbon::now();
$temporaryDirectory = TemporaryDirectory::make(); $temporaryDirectory = TemporaryDirectory::make();
Log::debug('Start exporting organization', [ Log::debug('Start exporting organization', [
@@ -365,9 +471,10 @@ class ExportService
$zip->close(); $zip->close();
// Upload ZIP file to private storage // 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( Storage::disk(config('filesystems.private'))->putFileAs(
'exports', $folder,
new File($temporaryDirectoryZip->path('export.zip')), new File($temporaryDirectoryZip->path('export.zip')),
$filename $filename
); );
@@ -381,11 +488,11 @@ class ExportService
'export_id' => $exportId, 'export_id' => $exportId,
]); ]);
return 'exports/'.$filename; return $folder.'/'.$filename;
} catch (UnavailableStream|CannotInsertRecord|Exception|LeagueCsvException $exception) { } catch (UnavailableStream|CannotInsertRecord|Exception|LeagueCsvException $exception) {
report($exception); report($exception);
throw new ExportException; throw new ExportException(previous: $exception);
} }
} }
} }

34
config/export.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Export job
|--------------------------------------------------------------------------
|
| Exports are processed by a queued job. The timeout is in seconds. The
| queue is the queue name the job is pushed to, null means the default
| queue of the connection.
|
*/
'job_timeout' => (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),
];

View File

@@ -10,6 +10,7 @@ return [
'self_hosting_check_for_update' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_CHECK_FOR_UPDATE', true), '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), 'self_hosting_telemetry' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_TELEMETRY', true),
'import_prune' => (bool) env('SCHEDULING_TASK_IMPORT_PRUNE', 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), 'self_hosting_database_consistency' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_DATABASE_CONSISTENCY', false),
], ],
]; ];

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Models\Export;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
/**
* @extends Factory<Export>
*/
class ExportFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
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',
]);
}
}

View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('exports', function (Blueprint $table): void {
$table->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');
}
};

View File

@@ -72,7 +72,7 @@ test('test that export button triggers export and shows success modal', async ({
(response) => (response) =>
response.url().includes('/export') && response.url().includes('/export') &&
response.request().method() === 'POST' && response.request().method() === 'POST' &&
response.status() === 200, response.status() === 202,
{ timeout: 60000 } { timeout: 60000 }
), ),
page.getByRole('button', { name: 'Export Organization Data' }).click(), 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 // Success modal should appear after export completes
await expect(page.getByText('The export was successful!')).toBeVisible(); 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 }) => { test('test that import type dropdown has multiple options', async ({ page }) => {

View File

@@ -7,6 +7,8 @@ use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization;
use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed;
use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed;
use App\Exceptions\Api\EntityStillInUseApiException; use App\Exceptions\Api\EntityStillInUseApiException;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Exceptions\Api\ExportFileNotAvailableApiException;
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException; use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException; use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException;
use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException; use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException;
@@ -43,6 +45,8 @@ return [
OrganizationNeedsAtLeastOneOwner::KEY => 'Organization needs at least one owner', OrganizationNeedsAtLeastOneOwner::KEY => 'Organization needs at least one owner',
ChangingRoleToPlaceholderIsNotAllowed::KEY => 'Changing role to placeholder is not allowed', ChangingRoleToPlaceholderIsNotAllowed::KEY => 'Changing role to placeholder is not allowed',
ExportException::KEY => 'Export failed, please try again later or contact support', 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', OrganizationHasNoSubscriptionButMultipleMembersException::KEY => 'Organization has no subscription but multiple members',
PdfRendererIsNotConfiguredException::KEY => 'PDF renderer is not configured', PdfRendererIsNotConfiguredException::KEY => 'PDF renderer is not configured',
FeatureIsNotAvailableInFreePlanApiException::KEY => 'Feature is not available in free plan', FeatureIsNotAvailableInFreePlanApiException::KEY => 'Feature is not available in free plan',

View File

@@ -1,8 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue'; import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { ref } from 'vue'; import { computed, onMounted, onUnmounted, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useNotificationsStore } from '@/utils/notification'; import { useNotificationsStore } from '@/utils/notification';
import { api, type OrganizationExportResponse } from '@/packages/api/src'; import { api, type Export } from '@/packages/api/src';
import { getCurrentOrganizationId } from '@/utils/useUser'; import { getCurrentOrganizationId } from '@/utils/useUser';
import DialogModal from '@/packages/ui/src/DialogModal.vue'; import DialogModal from '@/packages/ui/src/DialogModal.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue'; import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
@@ -10,38 +11,170 @@ import { ArrowUpOnSquareIcon, InformationCircleIcon } from '@heroicons/vue/24/ou
import { CardTitle } from '@/packages/ui/src'; import { CardTitle } from '@/packages/ui/src';
import Card from '@/Components/Common/Card.vue'; import Card from '@/Components/Common/Card.vue';
import { useOrganizationStore } from '@/utils/useOrganization'; import { useOrganizationStore } from '@/utils/useOrganization';
import { formatDateTimeLocalized } from '@/packages/ui/src/utils/time';
const EXPORT_POLL_INTERVAL_MS = 2000;
const showResultModal = ref(false); const showResultModal = ref(false);
const loading = ref(false); const loading = ref(false);
const exportResponse = ref<OrganizationExportResponse | null>(null); const downloadUrl = ref<string | null>(null);
const exports = ref<Export[]>([]);
const { organization } = useOrganizationStore(); const { organization } = storeToRefs(useOrganizationStore());
const { handleApiRequestNotifications } = useNotificationsStore(); const { handleApiRequestNotifications, addNotification } = useNotificationsStore();
const exportInProgress = computed(() =>
exports.value.some((item) => item.status === 'pending' || item.status === 'running')
);
let isUnmounted = false;
onUnmounted(() => {
isUnmounted = true;
});
onMounted(async () => {
const organizationId = getCurrentOrganizationId();
if (organizationId === null) {
return;
}
await loadExports(organizationId);
// Resume waiting for an export that was started before the page was opened
const activeExport = exports.value.find(
(item) => item.status === 'pending' || item.status === 'running'
);
if (activeExport) {
await waitAndDownload(organizationId, activeExport, false);
}
});
async function loadExports(organizationId: string) {
exports.value = (
await api.getExports({
params: {
organization: organizationId,
},
})
).data;
}
function upsertExport(updatedExport: Export) {
const index = exports.value.findIndex((item) => item.id === updatedExport.id);
if (index === -1) {
exports.value = [updatedExport, ...exports.value];
} else {
exports.value[index] = updatedExport;
}
}
async function exportData() { async function exportData() {
loading.value = true;
const organizationId = getCurrentOrganizationId(); const organizationId = getCurrentOrganizationId();
if (organizationId) { if (organizationId === null) {
try { return;
const response = await handleApiRequestNotifications(
() =>
api.exportOrganization(undefined, {
params: {
organization: organizationId,
},
}),
'Organization data exported successfully.',
'Exporting organization data failed.'
);
if (response) {
showResultModal.value = true;
exportResponse.value = response;
window.open(response.download_url, '_self')?.focus();
}
} finally {
loading.value = false;
}
} }
loading.value = true;
try {
const response = await handleApiRequestNotifications(
() =>
api.exportOrganization(undefined, {
params: {
organization: organizationId,
},
}),
undefined,
'Exporting organization data failed.'
);
if (response === undefined) {
return;
}
upsertExport(response.data);
await waitAndDownload(organizationId, response.data, true);
} finally {
loading.value = false;
}
}
/**
* The export is processed in the background, poll it until it is completed or failed.
*/
async function waitForExport(organizationId: string, currentExport: Export): Promise<Export> {
while (
(currentExport.status === 'pending' || currentExport.status === 'running') &&
!isUnmounted
) {
await new Promise((resolve) => setTimeout(resolve, EXPORT_POLL_INTERVAL_MS));
currentExport = (
await api.getExport({
params: {
organization: organizationId,
export: currentExport.id,
},
})
).data;
upsertExport(currentExport);
}
return currentExport;
}
async function waitAndDownload(organizationId: string, startedExport: Export, showModal: boolean) {
loading.value = true;
try {
const finishedExport = await handleApiRequestNotifications(() =>
waitForExport(organizationId, startedExport)
);
if (finishedExport === undefined || isUnmounted) {
return;
}
if (finishedExport.status === 'failed') {
addNotification(
'error',
'Export failed',
finishedExport.error_message ?? 'The export failed, please try again.'
);
return;
}
if (finishedExport.status === 'completed') {
await download(finishedExport, showModal);
}
} finally {
loading.value = false;
}
}
async function download(completedExport: Export, showModal: boolean = false) {
const organizationId = getCurrentOrganizationId();
if (organizationId === null) {
return;
}
const response = await handleApiRequestNotifications(() =>
api.downloadExport({
params: {
organization: organizationId,
export: completedExport.id,
},
})
);
if (response === undefined) {
return;
}
downloadUrl.value = response.download_url;
if (showModal) {
showResultModal.value = true;
}
window.open(response.download_url, '_self')?.focus();
}
function statusLabel(item: Export): string {
switch (item.status) {
case 'pending':
return 'Waiting';
case 'running':
return 'In progress';
case 'completed':
return item.download_available ? 'Completed' : 'Expired';
case 'failed':
return 'Failed';
}
return item.status;
} }
</script> </script>
@@ -54,7 +187,7 @@ async function exportData() {
<a <a
class="font-semibold text-accent-200 hover:text-accent-300" class="font-semibold text-accent-200 hover:text-accent-300"
target="_self" target="_self"
:href="exportResponse?.download_url" :href="downloadUrl ?? undefined"
>click here</a >click here</a
> >
</div> </div>
@@ -70,8 +203,9 @@ async function exportData() {
<InformationCircleIcon class="h-5 min-w-0 w-5 text-bg-tertiary" /> <InformationCircleIcon class="h-5 min-w-0 w-5 text-bg-tertiary" />
<p class="flex-1"> <p class="flex-1">
Export your solidtime organization data. This will include all clients, Export your solidtime organization data. This will include all clients,
projects, tasks, and time entries. You will receive a zip file with json files projects, tasks, and time entries. You will receive a zip file with CSV files
for each entity. for each entity. The export is prepared in the background, you can leave this
page and download it later.
</p> </p>
</div> </div>
</Card> </Card>
@@ -81,9 +215,43 @@ async function exportData() {
The following organization will be exported: <br /> The following organization will be exported: <br />
<strong class="font-semibold">{{ organization?.name }}</strong> <strong class="font-semibold">{{ organization?.name }}</strong>
</div> </div>
<PrimaryButton :loading @click="exportData" <PrimaryButton :loading="loading || exportInProgress" @click="exportData"
>Export Organization Data >Export Organization Data
</PrimaryButton> </PrimaryButton>
<div v-if="exportInProgress" class="text-text-secondary">
The export is being prepared, the download starts automatically when it is
ready.
</div>
</div>
<div
v-if="exports.length > 0"
class="border-t border-card-background-separator px-4 py-3 sm:px-5 text-sm">
<div class="font-semibold text-text-primary pb-2">Recent exports</div>
<ul>
<li
v-for="item in exports"
:key="item.id"
class="flex items-center justify-between py-2 border-t first:border-t-0 border-card-background-separator">
<div class="text-text-primary">
<span v-if="item.created_at">
{{
formatDateTimeLocalized(
item.created_at,
organization?.date_format,
organization?.time_format
)
}}
</span>
<span class="pl-3 text-text-tertiary">{{ statusLabel(item) }}</span>
</div>
<SecondaryButton
v-if="item.download_available"
size="small"
@click="download(item)">
Download
</SecondaryButton>
</li>
</ul>
</div> </div>
</Card> </Card>
</div> </div>

View File

@@ -100,7 +100,7 @@ export type MyMemberships = ZodiosResponseByAlias<SolidTimeApi, 'getMyMembership
export type MyMembership = MyMemberships[0]; export type MyMembership = MyMemberships[0];
export type OrganizationExportResponse = ZodiosResponseByAlias<SolidTimeApi, 'exportOrganization'>; export type Export = ZodiosResponseByAlias<SolidTimeApi, 'getExport'>['data'];
export type ReportIndexResponse = ZodiosResponseByAlias<SolidTimeApi, 'getReports'>; export type ReportIndexResponse = ZodiosResponseByAlias<SolidTimeApi, 'getReports'>;

View File

@@ -42,6 +42,22 @@ const DestroyWithPasswordRequest = z
password: z.string().nullish(), password: z.string().nullish(),
}) })
.passthrough(); .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 ImportRequest = z.object({ type: z.string(), data: z.string().max(52428800) }).passthrough();
const ImportSource = z.enum(['file', 'api']); const ImportSource = z.enum(['file', 'api']);
const ImportStatus = z.enum(['pending', 'running', 'completed', 'failed']); const ImportStatus = z.enum(['pending', 'running', 'completed', 'failed']);
@@ -871,6 +887,10 @@ export const schemas = {
ClientResource, ClientResource,
ClientStoreRequest, ClientStoreRequest,
ClientUpdateRequest, ClientUpdateRequest,
ExportType,
ExportStatus,
ExportResource,
ExportCollection,
ImportRequest, ImportRequest,
ImportSource, ImportSource,
ImportStatus, ImportStatus,
@@ -1643,6 +1663,8 @@ const endpoints = makeApi([
method: 'post', method: 'post',
path: '/v1/organizations/:organization/export', path: '/v1/organizations/:organization/export',
alias: 'exportOrganization', 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', requestFormat: 'json',
parameters: [ parameters: [
{ {
@@ -1651,7 +1673,162 @@ const endpoints = makeApi([
schema: z.string(), 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: [ errors: [
{ {
status: 400, status: 400,

View File

@@ -192,6 +192,9 @@ Route::prefix('v1')->name('v1.')->group(static function (): void {
// Export routes // Export routes
Route::name('export.')->prefix('/organizations/{organization}')->group(static function (): void { Route::name('export.')->prefix('/organizations/{organization}')->group(static function (): void {
Route::post('/export', [ExportController::class, 'export'])->name('export'); 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');
}); });
}); });

View File

@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Console\Commands\Export;
use App\Console\Commands\Export\ExportPruneCommand;
use App\Enums\ExportStatus;
use App\Models\Export;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCaseWithDatabase;
#[CoversClass(ExportPruneCommand::class)]
class ExportPruneCommandTest extends TestCaseWithDatabase
{
protected function setUp(): void
{
parent::setUp();
config([
'export.job_timeout' => 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'));
}
}

View File

@@ -4,14 +4,14 @@ declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1; namespace Tests\Unit\Endpoint\Api\V1;
use App\Enums\ExportStatus;
use App\Http\Controllers\Api\V1\ExportController; use App\Http\Controllers\Api\V1\ExportController;
use App\Jobs\ProcessExport;
use App\Models\Export;
use App\Models\Organization; use App\Models\Organization;
use App\Service\Export\ExportException;
use App\Service\Export\ExportService;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Queue;
use Laravel\Passport\Passport; use Laravel\Passport\Passport;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\Attributes\UsesClass;
#[UsesClass(ExportController::class)] #[UsesClass(ExportController::class)]
@@ -21,9 +21,7 @@ class ExportEndpointTest extends ApiEndpointTestAbstract
{ {
// Arrange // Arrange
$data = $this->createUserWithPermission(); $data = $this->createUserWithPermission();
$this->mock(ExportService::class, function (MockInterface $mock): void { Queue::fake();
$mock->shouldNotReceive('export');
});
Passport::actingAs($data->user); Passport::actingAs($data->user);
// Act // Act
@@ -31,94 +29,276 @@ class ExportEndpointTest extends ApiEndpointTestAbstract
// Assert // Assert
$response->assertForbidden(); $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', 'export',
]); ]);
$this->mock(ExportService::class, function (MockInterface $mock) use (&$user): void { Queue::fake();
$mock->shouldReceive('export') Passport::actingAs($data->user);
->withArgs(function (Organization $organization) use (&$user): bool {
return $organization->is($user->organization);
})
->andThrow(new ExportException)
->once();
});
Passport::actingAs($user->user);
// Act // 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 // Assert
$response->assertStatus(400); $response->assertStatus(400);
$response->assertExactJson([ $response->assertExactJson([
'error' => true, 'error' => true,
'key' => 'export', 'key' => 'export_already_in_progress',
'message' => 'Export failed, please try again later or contact support', '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 // Arrange
$user = $this->createUserWithPermission([ $data = $this->createUserWithPermission();
'export', Passport::actingAs($data->user);
]);
$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);
// Act // Act
$response = $this->postJson(route('api.v1.export.export', [ $response = $this->getJson(route('api.v1.export.exports.index', ['organization' => $data->organization->getKey()]));
'organization' => $user->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 // Assert
$response->assertStatus(200); $response->assertForbidden();
$response->assertJsonPath('success', true);
$this->assertStringContainsString($filepath, $response->json('download_url'));
} }
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 // Arrange
$user = $this->createUserWithPermission([ $data = $this->createUserWithPermission([
'export', 'export',
]); ]);
$filepath = 'exports/export_test.zip'; $export = Export::factory()->completed()->create();
$this->mock(ExportService::class, function (MockInterface $mock) use (&$user, $filepath): void { Passport::actingAs($data->user);
$mock->shouldReceive('export')
->withArgs(function (Organization $organization) use (&$user): bool { // Act
return $organization->is($user->organization); $response = $this->getJson(route('api.v1.export.exports.show', [
}) 'organization' => $data->organization->getKey(),
->andReturn($filepath) 'export' => $export->getKey(),
->once(); ]));
});
Passport::actingAs($user->user); // 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(); $capturedOptions = $this->captureTemporaryUrlOptions();
// Act // Act
$response = $this->postJson(route('api.v1.export.export', [ $response = $this->getJson(route('api.v1.export.exports.download', [
'organization' => $user->organization->getKey(), 'organization' => $data->organization->getKey(),
'export' => $export->getKey(),
])); ]));
// Assert // Assert
$response->assertStatus(200); $response->assertOk();
$response->assertExactJson([
'download_url' => 'https://storage.fake/exports/test/export.zip',
]);
$options = $capturedOptions(); $options = $capturedOptions();
$this->assertIsArray($options); $this->assertIsArray($options);
$this->assertSame('attachment; filename="export_test.zip"', $options['ResponseContentDisposition'] ?? null); $this->assertSame(
$this->assertSame('https://storage.fake/'.$filepath, $response->json('download_url')); 'attachment; filename="solidtime-export_acme-gmbh_2026-11-18_11-20_1f2470b2.zip"',
$options['ResponseContentDisposition'] ?? null
);
} }
} }

View File

@@ -10,6 +10,8 @@ use App\Exceptions\Api\CanNotRemoveOwnerFromOrganization;
use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleOfPlaceholderIsNotAllowed;
use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed; use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed;
use App\Exceptions\Api\EntityStillInUseApiException; use App\Exceptions\Api\EntityStillInUseApiException;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Exceptions\Api\ExportFileNotAvailableApiException;
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException; use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException; use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException;
use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException; use App\Exceptions\Api\InvitationForTheEmailAlreadyExistsApiException;
@@ -44,6 +46,8 @@ class ApiExceptionTest extends TestCase
yield ChangingRoleOfPlaceholderIsNotAllowed::class => [new ChangingRoleOfPlaceholderIsNotAllowed]; yield ChangingRoleOfPlaceholderIsNotAllowed::class => [new ChangingRoleOfPlaceholderIsNotAllowed];
yield ChangingRoleToPlaceholderIsNotAllowed::class => [new ChangingRoleToPlaceholderIsNotAllowed]; yield ChangingRoleToPlaceholderIsNotAllowed::class => [new ChangingRoleToPlaceholderIsNotAllowed];
yield EntityStillInUseApiException::class => [new EntityStillInUseApiException('member', 'time_entry')]; yield EntityStillInUseApiException::class => [new EntityStillInUseApiException('member', 'time_entry')];
yield ExportAlreadyInProgressApiException::class => [new ExportAlreadyInProgressApiException];
yield ExportFileNotAvailableApiException::class => [new ExportFileNotAvailableApiException];
yield FeatureIsNotAvailableInFreePlanApiException::class => [new FeatureIsNotAvailableInFreePlanApiException]; yield FeatureIsNotAvailableInFreePlanApiException::class => [new FeatureIsNotAvailableInFreePlanApiException];
yield InactiveUserCanNotBeUsedApiException::class => [new InactiveUserCanNotBeUsedApiException]; yield InactiveUserCanNotBeUsedApiException::class => [new InactiveUserCanNotBeUsedApiException];
yield InvitationForTheEmailAlreadyExistsApiException::class => [new InvitationForTheEmailAlreadyExistsApiException]; yield InvitationForTheEmailAlreadyExistsApiException::class => [new InvitationForTheEmailAlreadyExistsApiException];

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Filament\Resources;
use App\Filament\Resources\ExportResource;
use App\Models\Export;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\UsesClass;
use Tests\Unit\Filament\FilamentTestCase;
#[UsesClass(ExportResource::class)]
class ExportResourceTest extends FilamentTestCase
{
protected function setUp(): void
{
parent::setUp();
Config::set('auth.super_admins', ['admin@example.com']);
$user = User::factory()->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();
}
}

View File

@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Jobs;
use App\Enums\ExportStatus;
use App\Jobs\ProcessExport;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Queue\TimeoutExceededException;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use RuntimeException;
use Tests\TestCaseWithDatabase;
#[CoversClass(ProcessExport::class)]
class ProcessExportTest extends TestCaseWithDatabase
{
public function test_job_processes_export_via_export_service(): void
{
// Arrange
$export = Export::factory()->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);
}
}

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Model;
use App\Models\Export;
use App\Models\Organization;
use Illuminate\Support\Carbon;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
#[CoversClass(Export::class)]
class ExportModelTest extends ModelTestAbstract
{
private function createExport(string $organizationName): Export
{
$organization = Organization::factory()->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<string, array{string, string}>
*/
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());
}
}

View File

@@ -10,6 +10,7 @@ use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers; use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Audit; use App\Models\Audit;
use App\Models\Client; use App\Models\Client;
use App\Models\Export;
use App\Models\Goal; use App\Models\Goal;
use App\Models\Import; use App\Models\Import;
use App\Models\Member; use App\Models\Member;
@@ -67,7 +68,8 @@ class DeletionServiceTest extends TestCaseWithDatabase
* owner: User, * owner: User,
* reports: Collection<Report>, * reports: Collection<Report>,
* goals: Collection<Goal>, * goals: Collection<Goal>,
* imports: Collection<Import> * imports: Collection<Import>,
* exports: Collection<Export>
* } * }
*/ */
private function createOrganizationWithAllRelations(): object private function createOrganizationWithAllRelations(): object
@@ -123,6 +125,13 @@ class DeletionServiceTest extends TestCaseWithDatabase
$importWithoutFile = Import::factory()->forOrganization($organization)->forUser($userEmployee)->failed()->create(); $importWithoutFile = Import::factory()->forOrganization($organization)->forUser($userEmployee)->failed()->create();
$imports = collect([$importWithFile, $importWithoutFile]); $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); $timeEntries = TimeEntry::factory()->forOrganization($organization)->forMember($memberOwner)->createMany(2);
$timeEntriesWithTask = TimeEntry::factory()->forTask($task1)->forOrganization($organization)->forMember($memberEmployee)->createMany(2); $timeEntriesWithTask = TimeEntry::factory()->forTask($task1)->forOrganization($organization)->forMember($memberEmployee)->createMany(2);
$timeEntriesWithProject = TimeEntry::factory()->forProject($projectWithClient)->forOrganization($organization)->forMember($memberPlaceholder)->createMany(2); $timeEntriesWithProject = TimeEntry::factory()->forProject($projectWithClient)->forOrganization($organization)->forMember($memberPlaceholder)->createMany(2);
@@ -141,6 +150,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
'reports' => $reports, 'reports' => $reports,
'goals' => $goals, 'goals' => $goals,
'imports' => $imports, 'imports' => $imports,
'exports' => $exports,
]; ];
} }
@@ -160,6 +170,8 @@ class DeletionServiceTest extends TestCaseWithDatabase
$this->assertSame(0, Goal::query()->whereBelongsTo($organization, 'organization')->count()); $this->assertSame(0, Goal::query()->whereBelongsTo($organization, 'organization')->count());
$this->assertSame(0, Import::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([], 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()); $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, Goal::query()->whereBelongsTo($organization, 'organization')->count());
$this->assertSame(2, Import::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->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()); $this->assertSame($specialCase ? 7 : 6, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
} }

View File

@@ -4,7 +4,12 @@ declare(strict_types=1);
namespace Tests\Unit\Service\Export; 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\Client;
use App\Models\Export;
use App\Models\Member; use App\Models\Member;
use App\Models\Organization; use App\Models\Organization;
use App\Models\OrganizationInvitation; use App\Models\OrganizationInvitation;
@@ -14,10 +19,15 @@ use App\Models\Tag;
use App\Models\Task; use App\Models\Task;
use App\Models\TimeEntry; use App\Models\TimeEntry;
use App\Models\User; use App\Models\User;
use App\Service\Export\ExportException;
use App\Service\Export\ExportService; use App\Service\Export\ExportService;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use League\Csv\Reader; use League\Csv\Reader;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversClass;
use RuntimeException;
use Tests\TestCaseWithDatabase; use Tests\TestCaseWithDatabase;
use ZipArchive; use ZipArchive;
@@ -92,4 +102,147 @@ class ExportServiceTest extends TestCaseWithDatabase
$this->assertSame('work', $typesById[$workEntry->getKey()]); $this->assertSame('work', $typesById[$workEntry->getKey()]);
$this->assertSame('break', $typesById[$breakEntry->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);
}
} }