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

This commit is contained in:
Constantin Graf
2026-11-03 16:27:05 +01:00
committed by Constantin Graf
parent 1a589a9552
commit a83eeb0222
33 changed files with 1897 additions and 215 deletions

View File

@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Import;
use App\Models\Import;
use App\Service\Import\ImportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ImportPruneCommand extends Command
{
/**
* Time in seconds an active import can exceed the job timeout before it is considered stale,
* this covers the time the job waits in the queue.
*/
private const int STALE_BUFFER_SECONDS = 3600;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import: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 imports as failed and deletes import files after the retention period.';
/**
* Execute the console command.
*/
public function handle(ImportService $importService): int
{
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. Nothing will be saved or deleted.');
}
$staleBefore = Carbon::now()->subSeconds((int) config('import.job_timeout') + self::STALE_BUFFER_SECONDS);
$staleImports = 0;
Import::query()
->active()
->where('updated_at', '<', $staleBefore)
->orderBy('created_at', 'asc')
->chunkById(500, function (Collection $imports) use ($dryRun, $importService, &$staleImports): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {
$this->info('Mark stale import '.$import->getKey().' ('.$import->status->value.') as failed');
$staleImports++;
if (! $dryRun) {
$importService->markAsFailed($import, 'Import could not be finished');
}
}
});
$retentionBefore = Carbon::now()->subDays((int) config('import.file_retention_days'));
$prunedFiles = 0;
Import::query()
->whereNotNull('file_path')
->whereNotNull('finished_at')
->where('finished_at', '<', $retentionBefore)
->orderBy('created_at', 'asc')
->chunkById(500, function (Collection $imports) use ($dryRun, &$prunedFiles): void {
/** @var Collection<int, Import> $imports */
foreach ($imports as $import) {
$this->info('Delete file of import '.$import->getKey().' ('.$import->file_path.')');
$prunedFiles++;
if (! $dryRun) {
Storage::disk(config('filesystems.private'))->delete((string) $import->file_path);
$import->file_path = null;
$import->save();
}
}
});
$this->comment('Marked '.$staleImports.' stale imports as failed and deleted '.$prunedFiles.' import files.');
return self::SUCCESS;
}
}

View File

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

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum ImportSource: string
{
use LaravelEnumHelper;
/**
* Import of an uploaded file (CSV, JSON or ZIP)
*/
case File = 'file';
/**
* Import via the API of a third party service
*/
case Api = 'api';
}

View File

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

View File

@@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Filament\Resources\ImportResource\Pages\ListImports;
use App\Filament\Resources\ImportResource\Pages\ViewImport;
use App\Models\Import;
use App\Service\Import\Importers\ImporterProvider;
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 Novadaemon\FilamentPrettyJson\Form\PrettyJsonField;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ImportResource extends Resource
{
protected static ?string $model = Import::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-inbox-arrow-down';
protected static string|\UnitEnum|null $navigationGroup = 'Timetracking';
protected static ?int $navigationSort = 9;
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')
->disabled(),
Select::make('user_id')
->label('User')
->relationship(name: 'user', titleAttribute: 'email')
->disabled(),
TextInput::make('type')
->label('Type')
->disabled(),
Select::make('source')
->label('Source')
->options(ImportSource::class)
->disabled(),
Select::make('status')
->label('Status')
->options(ImportStatus::class)
->disabled(),
TextInput::make('timezone')
->label('Timezone')
->disabled(),
TextInput::make('file_path')
->label('File path')
->disabled(),
Textarea::make('error_message')
->label('Error message')
->columnSpanFull()
->disabled(),
PrettyJsonField::make('report')
->formatStateUsing(fn (Import $record): ?string => $record->getRawOriginal('report'))
->columnSpanFull()
->disabled(),
PrettyJsonField::make('options')
->formatStateUsing(fn (Import $record): ?string => $record->getRawOriginal('options'))
->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')
->searchable()
->sortable(),
TextColumn::make('user.email')
->label('User')
->searchable()
->toggleable(),
TextColumn::make('type')
->sortable(),
TextColumn::make('source')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('status')
->badge()
->color(fn (Import $record): string => match ($record->status) {
ImportStatus::Pending => 'gray',
ImportStatus::Running => 'info',
ImportStatus::Completed => 'success',
ImportStatus::Failed => 'danger',
})
->sortable(),
TextColumn::make('error_message')
->limit(80)
->toggleable(),
TextColumn::make('created_at')
->dateTime()
->sortable(),
TextColumn::make('duration')
->label('Duration')
->state(function (Import $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(ImportStatus::class),
SelectFilter::make('type')
->options(function (): array {
$options = [];
foreach (app(ImporterProvider::class)->getImporterKeys() as $key) {
$options[$key] = $key;
}
return $options;
}),
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 (Import $record): bool => $record->file_path === null)
->action(fn (Import $record): StreamedResponse => Storage::disk(config('filesystems.private'))
->download((string) $record->file_path, 'import-'.$record->getKey())),
ViewAction::make(),
])
->toolbarActions([
]);
}
public static function canCreate(): bool
{
return false;
}
public static function getPages(): array
{
return [
'index' => ListImports::route('/'),
'view' => ViewImport::route('/{record}'),
];
}
}

View File

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

View File

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

View File

@@ -16,11 +16,11 @@ use App\Filament\Resources\OrganizationResource\Pages\ViewOrganization;
use App\Filament\Resources\OrganizationResource\RelationManagers\InvitationsRelationManager;
use App\Filament\Resources\OrganizationResource\RelationManagers\UsersRelationManager;
use App\Models\Organization;
use App\Models\User;
use App\Service\DeletionService;
use App\Service\Export\ExportService;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use App\Service\Import\ImportService;
use App\Service\TimezoneService;
use Brick\Money\IsoCurrencyProvider;
@@ -39,6 +39,7 @@ use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\UnableToReadFile;
@@ -192,30 +193,29 @@ class OrganizationResource extends Resource
}
/** @var string $timezone */
$timezone = $data['timezone'];
/** @var ReportDto $report */
$report = app(ImportService::class)->import(
/** @var User|null $user */
$user = Auth::user();
$import = app(ImportService::class)->createFileImport(
$record,
$user,
$data['type'],
$file,
$timezone
);
Notification::make()
->title('Import successful')
->title('Import queued')
->success()
->body(
'Imported time entries: '.$report->timeEntriesCreated.'<br>'.
'Imported clients: '.$report->clientsCreated.'<br>'.
'Imported projects: '.$report->projectsCreated.'<br>'.
'Imported tasks: '.$report->tasksCreated.'<br>'.
'Imported tags: '.$report->tagsCreated.'<br>'.
'Imported users: '.$report->usersCreated
)
->body('The import is processed in the background, see the imports for the result.')
->actions([
Action::make('view')
->label('View import')
->url(ImportResource::getUrl('view', ['record' => $import])),
])
->persistent()
->send();
} catch (ImportException $exception) {
report($exception);
Notification::make()
->title('Import failed, changes rolled back')
->title('Import failed')
->danger()
->body('Message: '.$exception->getMessage())
->persistent()

View File

@@ -4,7 +4,11 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Requests\V1\Import\ImportIndexRequest;
use App\Http\Requests\V1\Import\ImportRequest;
use App\Http\Resources\V1\Import\ImportCollection;
use App\Http\Resources\V1\Import\ImportResource;
use App\Models\Import;
use App\Models\Organization;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
@@ -51,11 +55,13 @@ class ImportController extends Controller
/**
* Import data into the organization
*
* The import is processed in the background. Use the returned import ID to poll the status of the import.
*
* @throws AuthorizationException
*
* @operationId importData
*/
public function import(Organization $organization, ImportRequest $request, ImportService $importService): JsonResponse
public function import(Organization $organization, ImportRequest $request, ImportService $importService): JsonResponse|ImportResource
{
$this->checkPermission($organization, 'import');
@@ -67,43 +73,59 @@ class ImportController extends Controller
], 400);
}
$timezone = $this->user()->timezone;
$report = $importService->import(
$user = $this->user();
$import = $importService->createFileImport(
$organization,
$user,
$request->input('type'),
$importData,
$timezone
$user->timezone
);
return new JsonResponse([
/** @var array{
* clients: array{
* created: int,
* },
* projects: array{
* created: int,
* },
* tasks: array{
* created: int,
* },
* time_entries: array{
* created: int,
* },
* tags: array{
* created: int,
* },
* users: array{
* created: int,
* }
* } $report Import report */
'report' => $report->toArray(),
], 200);
return (new ImportResource($import->refresh()))
->response()
->setStatusCode(202);
} catch (ImportException $exception) {
report($exception);
return new JsonResponse([
'message' => $exception->getMessage(),
], 400);
}
}
/**
* Get imports
*
* @throws AuthorizationException
*
* @operationId getImports
*/
public function indexImports(Organization $organization, ImportIndexRequest $request): ImportCollection
{
$this->checkPermission($organization, 'import');
$imports = Import::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc')
->orderBy('id')
->paginate(config('app.pagination_per_page_default'));
return new ImportCollection($imports);
}
/**
* Get import
*
* @throws AuthorizationException
*
* @operationId getImport
*/
public function show(Organization $organization, Import $import): ImportResource
{
$this->checkPermission($organization, 'import');
if ($import->organization_id !== $organization->getKey()) {
throw new AuthorizationException('Import does not belong to organization');
}
return new ImportResource($import);
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Import;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Contracts\Validation\ValidationRule;
class ImportIndexRequest 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\Import;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ImportCollection extends ResourceCollection
{
/**
* The resource that this resource collects.
*
* @var string
*/
public $collects = ImportResource::class;
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\V1\Import;
use App\Http\Resources\V1\BaseResource;
use App\Models\Import;
use Illuminate\Http\Request;
/**
* @property Import $resource
*/
class ImportResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
/** ID of the import */
'id' => $this->resource->id,
/** Importer key, see the importers endpoint */
'type' => $this->resource->type,
/** Source of the import data */
'source' => $this->resource->source,
/** Status of the import */
'status' => $this->resource->status,
/** @var array{
* clients: array{
* created: int,
* },
* projects: array{
* created: int,
* },
* tasks: array{
* created: int,
* },
* time_entries: array{
* created: int,
* },
* tags: array{
* created: int,
* },
* users: array{
* created: int,
* }
* }|null $report Import report, only set if the import is completed */
'report' => $this->resource->report,
/** Error message, only set if the import failed */
'error_message' => $this->resource->error_message,
/** ID of the user that started the import */
'user_id' => $this->resource->user_id,
/** @var string|null $started_at Date when the import was started */
'started_at' => $this->formatDateTime($this->resource->started_at),
/** @var string|null $finished_at Date when the import was finished */
'finished_at' => $this->formatDateTime($this->resource->finished_at),
/** @var string|null $created_at Date when the import was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
];
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Import;
use App\Service\Import\ImportService;
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\SerializesModels;
use Throwable;
class ProcessImport implements ShouldDispatchAfterCommit, ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Delete the job if its models no longer exist.
*/
public bool $deleteWhenMissingModels = true;
/**
* Imports are not retried, since a failed import is rolled back and the user has to fix the import data.
* Note: The "retry_after" of the queue connection needs to be higher than the timeout,
* otherwise a long-running import is started a second time.
*/
public int $tries = 1;
public int $timeout;
public Import $import;
/**
* Create a new job instance.
*/
public function __construct(Import $import)
{
$this->import = $import;
$this->timeout = (int) config('import.job_timeout');
$this->onQueue(config('import.queue'));
}
/**
* Execute the job.
*/
public function handle(ImportService $importService): void
{
$importService->process($this->import);
}
/**
* Handle a job failure, for example a timeout.
*/
public function failed(?Throwable $exception): void
{
$this->import->refresh();
if ($this->import->status->isActive()) {
app(ImportService::class)->markAsFailed($this->import, 'Import could not be finished');
}
}
}

96
app/Models/Import.php Normal file
View File

@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Models\Concerns\HasUuids;
use Database\Factories\ImportFactory;
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;
/**
* @property string $id
* @property string $type
* @property ImportSource $source
* @property ImportStatus $status
* @property string $timezone
* @property string|null $file_path
* @property array<string, mixed>|null $credentials
* @property array<string, mixed>|null $options
* @property array<string, mixed>|null $report
* @property string|null $error_message
* @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 ImportFactory factory()
*/
class Import extends Model
{
/** @use HasFactory<ImportFactory> */
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'source' => ImportSource::class,
'status' => ImportStatus::class,
'credentials' => 'encrypted:array',
'options' => 'array',
'report' => 'array',
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'credentials',
];
/**
* @return BelongsTo<Organization, $this>
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* The user that started the import, null if the user was deleted.
*
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @param Builder<Import> $builder
* @return Builder<Import>
*/
public function scopeActive(Builder $builder): Builder
{
return $builder->whereIn('status', ImportStatus::active());
}
}

View File

@@ -40,6 +40,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
* @property Collection<int, User> $users
* @property Collection<int, User> $realUsers
* @property-read Collection<int, OrganizationInvitation> $organizationInvitations
* @property-read Collection<int, Import> $imports
* @property Member $membership
* @property NumberFormat $number_format
* @property CurrencyFormat $currency_format
@@ -158,6 +159,14 @@ class Organization extends Model implements AuditableContract
return $this->hasMany(OrganizationInvitation::class, 'organization_id');
}
/**
* @return HasMany<Import, $this>
*/
public function imports(): HasMany
{
return $this->hasMany(Import::class, 'organization_id');
}
/**
* Find a model by its primary key or throw an exception.
*

View File

@@ -10,6 +10,7 @@ use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Client;
use App\Models\Goal;
use App\Models\Import;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
@@ -22,6 +23,7 @@ use App\Models\TimeEntry;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class DeletionService
{
@@ -80,6 +82,20 @@ class DeletionService
// Delete all goals
Goal::query()->whereBelongsTo($organization, 'organization')->delete();
// Delete all imports, the stored import files are deleted after the transaction is committed,
// since the deletion of files is not reversible via a database rollback
$importFilePaths = Import::query()
->whereBelongsTo($organization, 'organization')
->whereNotNull('file_path')
->pluck('file_path')
->all();
Import::query()->whereBelongsTo($organization, 'organization')->delete();
if (count($importFilePaths) > 0) {
DB::afterCommit(function () use ($importFilePaths): void {
Storage::disk(config('filesystems.private'))->delete($importFilePaths);
});
}
// Reset the current organization
$organization->owner()
->where('current_team_id', $organization->getKey())

View File

@@ -4,44 +4,138 @@ declare(strict_types=1);
namespace App\Service\Import;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Models\Organization;
use App\Models\User;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LogicException;
use Throwable;
class ImportService
{
/**
* Stores the import file and queues the import.
*
* @throws ImportException
*/
public function import(Organization $organization, string $importerType, string $data, string $timezone): ReportDto
public function createFileImport(Organization $organization, ?User $user, string $importerType, string $data, string $timezone): Import
{
/** @var ImporterContract $importer */
$importer = app(ImporterProvider::class)->getImporter($importerType);
$importer->init($organization);
Storage::disk(config('filesystems.private'))
->put('import/'.Carbon::now()->toDateString().'-'.$organization->getKey().'-'.Str::uuid(), $data);
// Throws an InvalidArgumentException if the importer type is unknown
app(ImporterProvider::class)->getImporter($importerType);
$lock = Cache::lock('import:'.$organization->getKey(), config('octane.max_execution_time', 60) + 1);
if ($lock->get()) {
try {
DB::transaction(function () use (&$importer, &$data, &$timezone): void {
$importer->importData($data, $timezone);
});
} finally {
$lock->release();
}
} else {
if (Import::query()->whereBelongsTo($organization, 'organization')->active()->exists()) {
throw new ImportException('Import is already in progress');
}
return $importer->getReport();
$import = new Import;
$import->type = $importerType;
$import->source = ImportSource::File;
$import->status = ImportStatus::Pending;
$import->timezone = $timezone;
$import->organization()->associate($organization);
$import->user()->associate($user);
$import->id = $import->newUniqueId();
$import->file_path = 'import/'.$organization->getKey().'/'.$import->getKey();
Storage::disk(config('filesystems.private'))->put($import->file_path, $data);
try {
$import->save();
} catch (UniqueConstraintViolationException) {
// Another import of the organization was created in the meantime
Storage::disk(config('filesystems.private'))->delete($import->file_path);
throw new ImportException('Import is already in progress');
}
ProcessImport::dispatch($import);
return $import;
}
/**
* Runs the import, the result (report or error message) is stored on the import.
*/
public function process(Import $import): void
{
if ($import->status !== ImportStatus::Pending) {
Log::warning('Skipping import that is not pending', [
'import_id' => $import->getKey(),
'status' => $import->status->value,
]);
return;
}
$import->status = ImportStatus::Running;
$import->started_at = Carbon::now();
$import->save();
try {
/** @var ImporterContract $importer */
$importer = app(ImporterProvider::class)->getImporter($import->type);
$importer->init($import->organization);
$data = $this->getImportData($import);
DB::transaction(function () use (&$importer, &$data, $import): void {
$importer->importData($data, $import->timezone);
});
$import->status = ImportStatus::Completed;
$import->report = $importer->getReport()->toArray();
} catch (ImportException $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = $exception->getMessage();
} catch (Throwable $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = 'Unexpected error during import';
} finally {
$import->credentials = null;
$import->finished_at = Carbon::now();
$import->save();
}
}
/**
* Marks an import as failed that could not be finished, for example because the job timed out or the worker crashed.
*/
public function markAsFailed(Import $import, string $errorMessage): void
{
$import->status = ImportStatus::Failed;
$import->error_message = $errorMessage;
$import->credentials = null;
$import->finished_at = Carbon::now();
$import->save();
}
/**
* @throws ImportException
*/
private function getImportData(Import $import): string
{
if ($import->source !== ImportSource::File) {
throw new LogicException('Import source "'.$import->source->value.'" is not supported yet');
}
$disk = Storage::disk(config('filesystems.private'));
if ($import->file_path === null || ! $disk->exists($import->file_path)) {
throw new ImportException('Import file does not exist anymore');
}
$data = $disk->get($import->file_path);
if ($data === null) {
throw new ImportException('Import file does not exist anymore');
}
return $data;
}
}

View File

@@ -31,4 +31,32 @@ return [
'zip_max_uncompressed_size' => (int) (env('IMPORT_ZIP_MAX_UNCOMPRESSED_SIZE') ?: 500 * 1024 * 1024),
/*
|--------------------------------------------------------------------------
| Import job
|--------------------------------------------------------------------------
|
| Imports are processed by a queued job. The timeout is in seconds, the
| "retry_after" of the queue connection needs to be higher than the
| timeout. The queue is the queue name the job is pushed to, null
| means the default queue of the connection.
|
*/
'job_timeout' => (int) (env('IMPORT_JOB_TIMEOUT') ?: 3600),
'queue' => env('IMPORT_QUEUE'),
/*
|--------------------------------------------------------------------------
| Import file retention
|--------------------------------------------------------------------------
|
| Number of days the uploaded import files are kept after the import
| finished. The import itself is kept, only the file is deleted.
|
*/
'file_retention_days' => (int) (env('IMPORT_FILE_RETENTION_DAYS') ?: 30),
];

View File

@@ -9,6 +9,7 @@ return [
'auth_send_mails_expiring_api_tokens' => (bool) env('SCHEDULING_TASK_AUTH_SEND_MAILS_EXPIRING_API_TOKENS', 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),
'import_prune' => (bool) env('SCHEDULING_TASK_IMPORT_PRUNE', true),
'self_hosting_database_consistency' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_DATABASE_CONSISTENCY', false),
],
];

View File

@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Models\Import;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
/**
* @extends Factory<Import>
*/
class ImportFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'type' => 'toggl_time_entries',
'source' => ImportSource::File,
'status' => ImportStatus::Pending,
'timezone' => 'Europe/Vienna',
'file_path' => null,
'credentials' => null,
'options' => null,
'report' => null,
'error_message' => 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' => ImportStatus::Running,
'started_at' => Carbon::now(),
]);
}
public function completed(): self
{
return $this->state(fn (array $attributes): array => [
'status' => ImportStatus::Completed,
'started_at' => Carbon::now()->subMinute(),
'finished_at' => Carbon::now(),
'report' => [
'clients' => ['created' => 1],
'projects' => ['created' => 2],
'tasks' => ['created' => 3],
'time_entries' => ['created' => 4],
'tags' => ['created' => 5],
'users' => ['created' => 6],
],
]);
}
public function failed(): self
{
return $this->state(fn (array $attributes): array => [
'status' => ImportStatus::Failed,
'started_at' => Carbon::now()->subMinute(),
'finished_at' => Carbon::now(),
'error_message' => 'Import failed',
]);
}
}

View File

@@ -0,0 +1,63 @@
<?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('imports', function (Blueprint $table): void {
$table->uuid('id')->primary();
// Importer key, see ImporterProvider
$table->string('type');
$table->string('source');
$table->string('status');
// Timezone of the user that started the import, used to interpret dates without timezone
$table->string('timezone');
// Path of the uploaded file on the private disk, null for non-file imports or after the file was pruned
$table->string('file_path')->nullable();
// Encrypted credentials for imports via a third party API, removed after the import finished
$table->text('credentials')->nullable();
$table->jsonb('options')->nullable();
$table->jsonb('report')->nullable();
$table->text('error_message')->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 import, this is not necessarily a member of the organization (admin panel)
$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 import per organization can be pending or running at the same time
DB::statement("CREATE UNIQUE INDEX imports_organization_id_active_unique ON imports (organization_id) WHERE status IN ('pending', 'running')");
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('imports');
}
};

View File

@@ -112,13 +112,13 @@ test('test that importing a generic time entries CSV works', async ({ page }) =>
const csvPath = path.resolve('resources/testfiles/generic_time_entries_import_test_1.csv');
await page.locator('#file-upload').setInputFiles(csvPath);
// Click Import and wait for the API response
// Click Import and wait for the API response, the import is queued and processed in the background
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/import') &&
response.request().method() === 'POST' &&
response.status() === 200,
response.status() === 202,
{ timeout: 30000 }
),
page.getByRole('button', { name: 'Import Data' }).click(),

View File

@@ -1,6 +1,6 @@
<script setup lang="ts">
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { computed, onMounted, ref } from 'vue';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useNotificationsStore } from '@/utils/notification';
import { api } from '@/packages/api/src';
import { Field, FieldLabel } from '@/packages/ui/src/field';
@@ -13,7 +13,7 @@ import {
import { canUseBillableRates } from '@/utils/billing';
import { getCurrentOrganizationId } from '@/utils/useUser';
import type { ImportReport, ImportType } from '@/packages/api/src';
import type { Import, ImportReport, ImportType } from '@/packages/api/src';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import { initializeStores } from '@/utils/init';
@@ -60,7 +60,7 @@ async function importData() {
const { handleApiRequestNotifications } = useNotificationsStore();
loading.value = true;
try {
reportResult.value = await handleApiRequestNotifications(() => {
const response = await handleApiRequestNotifications(() => {
if (importType.value) {
return api.importData(
{
@@ -74,11 +74,29 @@ async function importData() {
}
);
}
return new Promise((resolve, reject) => {
return new Promise<never>((resolve, reject) => {
reject('Import type is null');
});
});
if (response === undefined) {
return;
}
const finishedImport = await handleApiRequestNotifications(() =>
waitForImport(organizationId, response.data)
);
if (finishedImport === undefined || isUnmounted) {
return;
}
if (finishedImport.status === 'failed') {
addNotification(
'error',
'Import failed',
finishedImport.error_message ?? 'The import failed, no data was imported.'
);
return;
}
initializeStores();
reportResult.value = finishedImport.report;
if (reportResult.value) {
showResultModal.value = true;
}
@@ -88,6 +106,34 @@ async function importData() {
}
}
const IMPORT_POLL_INTERVAL_MS = 2000;
let isUnmounted = false;
onUnmounted(() => {
isUnmounted = true;
});
/**
* The import is processed in the background, poll it until it is completed or failed.
*/
async function waitForImport(organizationId: string, currentImport: Import): Promise<Import> {
while (
(currentImport.status === 'pending' || currentImport.status === 'running') &&
!isUnmounted
) {
await new Promise((resolve) => setTimeout(resolve, IMPORT_POLL_INTERVAL_MS));
currentImport = (
await api.getImport({
params: {
organization: organizationId,
import: currentImport.id,
},
})
).data;
}
return currentImport;
}
const importFile = ref<HTMLInputElement | null>();
function toBase64(file: File): Promise<string> {
@@ -137,19 +183,19 @@ const showResultModal = ref(false);
<div class="py-2.5 px-3 border-t border-t-card-background-separator">
<span class="text-text-primary font-semibold">Clients created:</span>
{{ reportResult?.report.clients.created }}
{{ reportResult?.clients.created }}
</div>
<div class="py-2.5 px-3 border-t border-t-card-background-separator">
<span class="text-text-primary font-semibold">Projects created:</span>
{{ reportResult?.report.projects.created }}
{{ reportResult?.projects.created }}
</div>
<div class="py-2.5 px-3 border-t border-t-card-background-separator">
<span class="text-text-primary font-semibold">Tasks created:</span>
{{ reportResult?.report.tasks.created }}
{{ reportResult?.tasks.created }}
</div>
<div class="py-2.5 px-3 border-t border-t-card-background-separator">
<span class="text-text-primary font-semibold">Time entries created:</span>
{{ reportResult?.report.time_entries.created }}
{{ reportResult?.time_entries.created }}
</div>
</template>
<template #footer>

View File

@@ -70,7 +70,8 @@ export type CreateTagBody = ZodiosBodyByAlias<SolidTimeApi, 'createTag'>;
export type UpdateTagBody = ZodiosBodyByAlias<SolidTimeApi, 'updateTag'>;
export type ImportType = ZodiosResponseByAlias<SolidTimeApi, 'getImporters'>['data'][0];
export type ImportReport = ZodiosResponseByAlias<SolidTimeApi, 'importData'>;
export type Import = ZodiosResponseByAlias<SolidTimeApi, 'getImport'>['data'];
export type ImportReport = NonNullable<Import['report']>;
export type ReportingResponse = ZodiosResponseByAlias<SolidTimeApi, 'getAggregatedTimeEntries'>;

View File

@@ -42,7 +42,36 @@ const DestroyWithPasswordRequest = z
password: z.string().nullish(),
})
.passthrough();
const ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
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']);
const ImportResource = z
.object({
id: z.string(),
type: z.string(),
source: ImportSource,
status: ImportStatus,
report: z.union([
z
.object({
clients: z.object({ created: z.number().int() }).passthrough(),
projects: z.object({ created: z.number().int() }).passthrough(),
tasks: z.object({ created: z.number().int() }).passthrough(),
time_entries: z.object({ created: z.number().int() }).passthrough(),
tags: z.object({ created: z.number().int() }).passthrough(),
users: z.object({ created: z.number().int() }).passthrough(),
})
.passthrough(),
z.null(),
]),
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 ImportCollection = z.array(ImportResource);
const InvitationResource = z
.object({ id: z.string(), email: z.string(), role: z.string() })
.passthrough();
@@ -843,6 +872,10 @@ export const schemas = {
ClientStoreRequest,
ClientUpdateRequest,
ImportRequest,
ImportSource,
ImportStatus,
ImportResource,
ImportCollection,
InvitationResource,
InvitationStoreRequest,
InvoiceResource,
@@ -1648,6 +1681,7 @@ const endpoints = makeApi([
method: 'post',
path: '/v1/organizations/:organization/import',
alias: 'importData',
description: `The import is processed in the background. Use the returned import ID to poll the status of the import.`,
requestFormat: 'json',
parameters: [
{
@@ -1661,26 +1695,13 @@ const endpoints = makeApi([
schema: z.string(),
},
],
response: z
.object({
report: z
.object({
clients: z.object({ created: z.number().int() }).passthrough(),
projects: z.object({ created: z.number().int() }).passthrough(),
tasks: z.object({ created: z.number().int() }).passthrough(),
time_entries: z.object({ created: z.number().int() }).passthrough(),
tags: z.object({ created: z.number().int() }).passthrough(),
users: z.object({ created: z.number().int() }).passthrough(),
})
.passthrough(),
})
.passthrough(),
response: z.object({ data: ImportResource }).passthrough(),
errors: [
{
status: 400,
schema: z.union([
z.object({ message: z.string() }).passthrough(),
z.object({ message: z.literal('Invalid base64 encoded data') }).passthrough(),
z.object({ message: z.string() }).passthrough(),
]),
},
{
@@ -1746,6 +1767,117 @@ const endpoints = makeApi([
},
],
},
{
method: 'get',
path: '/v1/organizations/:organization/imports',
alias: 'getImports',
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: ImportCollection,
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/imports/:import',
alias: 'getImport',
requestFormat: 'json',
parameters: [
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'import',
type: 'Path',
schema: z.string(),
},
],
response: z.object({ data: ImportResource }).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/invitations',

View File

@@ -185,6 +185,8 @@ Route::prefix('v1')->name('v1.')->group(static function (): void {
Route::name('import.')->prefix('/organizations/{organization}')->group(static function (): void {
Route::get('/importers', [ImportController::class, 'index'])->name('index');
Route::post('/import', [ImportController::class, 'import'])->name('import')->middleware('check-organization-blocked');
Route::get('/imports', [ImportController::class, 'indexImports'])->name('imports.index');
Route::get('/imports/{import}', [ImportController::class, 'show'])->name('imports.show');
});
// Export routes

View File

@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Console\Commands\Import;
use App\Console\Commands\Import\ImportPruneCommand;
use App\Enums\ImportStatus;
use App\Models\Import;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCaseWithDatabase;
#[CoversClass(ImportPruneCommand::class)]
class ImportPruneCommandTest extends TestCaseWithDatabase
{
protected function setUp(): void
{
parent::setUp();
config([
'import.job_timeout' => 3600,
'import.file_retention_days' => 30,
]);
Storage::fake(config('filesystems.private'));
}
public function test_command_marks_stale_active_imports_as_failed(): void
{
// Arrange
$stalePending = Import::factory()->create([
'updated_at' => now()->subHours(3),
]);
$staleRunning = Import::factory()->running()->create([
'updated_at' => now()->subHours(3),
]);
$recentRunning = Import::factory()->running()->create([
'updated_at' => now()->subHour(),
]);
$oldCompleted = Import::factory()->completed()->create([
'updated_at' => now()->subHours(3),
]);
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('import:prune');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
$this->assertStringContainsString('Marked 2 stale imports as failed and deleted 0 import files.', Artisan::output());
$this->assertSame(ImportStatus::Failed, $stalePending->refresh()->status);
$this->assertSame('Import could not be finished', $stalePending->error_message);
$this->assertSame(ImportStatus::Failed, $staleRunning->refresh()->status);
$this->assertSame(ImportStatus::Running, $recentRunning->refresh()->status);
$this->assertSame(ImportStatus::Completed, $oldCompleted->refresh()->status);
}
public function test_command_deletes_files_of_imports_after_retention_period(): void
{
// Arrange
$disk = Storage::disk(config('filesystems.private'));
$disk->put('import/old', 'old');
$disk->put('import/new', 'new');
$oldImport = Import::factory()->completed()->create([
'file_path' => 'import/old',
'finished_at' => now()->subDays(31),
]);
$newImport = Import::factory()->failed()->create([
'file_path' => 'import/new',
'finished_at' => now()->subDays(29),
]);
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('import:prune');
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
$this->assertStringContainsString('Marked 0 stale imports as failed and deleted 1 import files.', Artisan::output());
$this->assertNull($oldImport->refresh()->file_path);
$this->assertFalse($disk->exists('import/old'));
$this->assertSame('import/new', $newImport->refresh()->file_path);
$this->assertTrue($disk->exists('import/new'));
}
public function test_command_does_not_change_anything_in_dry_run_mode(): void
{
// Arrange
$disk = Storage::disk(config('filesystems.private'));
$disk->put('import/old', 'old');
$staleImport = Import::factory()->running()->create([
'updated_at' => now()->subHours(3),
]);
$oldImport = Import::factory()->completed()->create([
'file_path' => 'import/old',
'finished_at' => now()->subDays(31),
]);
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('import:prune', ['--dry-run' => true]);
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
$this->assertStringContainsString('Marked 1 stale imports as failed and deleted 1 import files.', Artisan::output());
$this->assertSame(ImportStatus::Running, $staleImport->refresh()->status);
$this->assertSame('import/old', $oldImport->refresh()->file_path);
$this->assertTrue($disk->exists('import/old'));
}
}

View File

@@ -4,11 +4,14 @@ declare(strict_types=1);
namespace Tests\Unit\Endpoint\Api\V1;
use App\Enums\ImportStatus;
use App\Http\Controllers\Api\V1\ImportController;
use App\Models\Import;
use App\Models\Organization;
use App\Models\User;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use App\Service\Import\ImportService;
use Illuminate\Support\Facades\Storage;
use Laravel\Passport\Passport;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\UsesClass;
@@ -105,7 +108,7 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
'import',
]);
$this->mock(ImportService::class, function (MockInterface $mock): void {
$mock->shouldNotReceive('import');
$mock->shouldNotReceive('createFileImport');
});
Passport::actingAs($user->user);
@@ -120,18 +123,18 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
$response->assertJsonValidationErrors(['data']);
}
public function test_import_return_error_message_if_import_fails(): void
public function test_import_returns_error_message_if_import_can_not_be_created(): void
{
// Arrange
$user = $this->createUserWithPermission([
'import',
]);
$this->mock(ImportService::class, function (MockInterface $mock) use (&$user): void {
$mock->shouldReceive('import')
->withArgs(function (Organization $organization, string $importerType, string $data) use (&$user): bool {
return $organization->is($user->organization) && $importerType === 'toggl_time_entries' && $data === 'some data';
$mock->shouldReceive('createFileImport')
->withArgs(function (Organization $organization, ?User $importUser, string $importerType, string $data) use (&$user): bool {
return $organization->is($user->organization) && $importUser->is($user->user) && $importerType === 'toggl_time_entries' && $data === 'some data';
})
->andThrow(new ImportException('This is a test error!'))
->andThrow(new ImportException('Import is already in progress'))
->once();
});
Passport::actingAs($user->user);
@@ -145,29 +148,26 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'message' => 'This is a test error!',
'message' => 'Import is already in progress',
]);
}
public function test_import_calls_import_service_if_user_has_permission(): void
public function test_import_creates_import_via_import_service_and_returns_it(): void
{
// Arrange
$user = $this->createUserWithPermission([
'import',
]);
$this->mock(ImportService::class, function (MockInterface $mock) use (&$user): void {
$mock->shouldReceive('import')
->withArgs(function (Organization $organization, string $importerType, string $data) use (&$user): bool {
return $organization->is($user->organization) && $importerType === 'toggl_time_entries' && $data === 'some data';
$user->user->timezone = 'America/New_York';
$user->user->save();
$import = Import::factory()->forOrganization($user->organization)->forUser($user->user)->create();
$this->mock(ImportService::class, function (MockInterface $mock) use (&$user, $import): void {
$mock->shouldReceive('createFileImport')
->withArgs(function (Organization $organization, ?User $importUser, string $importerType, string $data, string $timezone) use (&$user): bool {
return $organization->is($user->organization) && $importUser->is($user->user) &&
$importerType === 'toggl_time_entries' && $data === 'some data' && $timezone === 'America/New_York';
})
->andReturn(new ReportDto(
clientsCreated: 1,
projectsCreated: 2,
tasksCreated: 3,
timeEntriesCreated: 4,
tagsCreated: 5,
usersCreated: 6,
))
->andReturn($import)
->once();
});
Passport::actingAs($user->user);
@@ -179,28 +179,136 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
]);
// Assert
$response->assertStatus(200);
$response->assertExactJson([
'report' => [
'clients' => [
'created' => 1,
],
'projects' => [
'created' => 2,
],
'tasks' => [
'created' => 3,
],
'time_entries' => [
'created' => 4,
],
'tags' => [
'created' => 5,
],
'users' => [
'created' => 6,
],
],
$response->assertStatus(202);
$response->assertJsonPath('data.id', $import->getKey());
$response->assertJsonPath('data.status', 'pending');
$response->assertJsonPath('data.report', null);
}
public function test_import_processes_import_if_queue_is_sync(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
$user = $this->createUserWithPermission([
'import',
]);
Passport::actingAs($user->user);
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
// Act
$response = $this->postJson(route('api.v1.import.import', ['organization' => $user->organization->getKey()]), [
'type' => 'toggl_time_entries',
'data' => base64_encode($data),
]);
// Assert
$response->assertStatus(202);
$response->assertJsonPath('data.type', 'toggl_time_entries');
$response->assertJsonPath('data.source', 'file');
$response->assertJsonPath('data.status', 'completed');
$response->assertJsonPath('data.user_id', $user->user->getKey());
$response->assertJsonPath('data.report.time_entries.created', 2);
$response->assertJsonPath('data.error_message', null);
$response->assertJsonMissingPath('data.credentials');
$response->assertJsonMissingPath('data.file_path');
}
public function test_imports_index_fails_if_user_does_not_have_permission(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.import.imports.index', ['organization' => $data->organization->getKey()]));
// Assert
$response->assertForbidden();
}
public function test_imports_index_returns_imports_of_organization_newest_first(): void
{
// Arrange
$data = $this->createUserWithPermission([
'import',
]);
$olderImport = Import::factory()->forOrganization($data->organization)->failed()->create([
'created_at' => now()->subDay(),
]);
$newerImport = Import::factory()->forOrganization($data->organization)->completed()->create([
'created_at' => now(),
]);
Import::factory()->completed()->create();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.import.imports.index', ['organization' => $data->organization->getKey()]));
// Assert
$response->assertOk();
$response->assertJsonCount(2, 'data');
$response->assertJsonPath('data.0.id', $newerImport->getKey());
$response->assertJsonPath('data.0.status', ImportStatus::Completed->value);
$response->assertJsonPath('data.1.id', $olderImport->getKey());
$response->assertJsonPath('data.1.error_message', 'Import failed');
}
public function test_imports_show_fails_if_user_does_not_have_permission(): void
{
// Arrange
$data = $this->createUserWithPermission();
$import = Import::factory()->forOrganization($data->organization)->create();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.import.imports.show', [
'organization' => $data->organization->getKey(),
'import' => $import->getKey(),
]));
// Assert
$response->assertForbidden();
}
public function test_imports_show_fails_if_import_belongs_to_different_organization(): void
{
// Arrange
$data = $this->createUserWithPermission([
'import',
]);
$import = Import::factory()->create();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.import.imports.show', [
'organization' => $data->organization->getKey(),
'import' => $import->getKey(),
]));
// Assert
$response->assertForbidden();
}
public function test_imports_show_returns_import(): void
{
// Arrange
$data = $this->createUserWithPermission([
'import',
]);
$import = Import::factory()->forOrganization($data->organization)->forUser($data->user)->completed()->create();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.import.imports.show', [
'organization' => $data->organization->getKey(),
'import' => $import->getKey(),
]));
// Assert
$response->assertOk();
$response->assertJsonPath('data.id', $import->getKey());
$response->assertJsonPath('data.status', 'completed');
$response->assertJsonPath('data.user_id', $data->user->getKey());
$response->assertJsonPath('data.report.users.created', 6);
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Filament\Resources;
use App\Filament\Resources\ImportResource;
use App\Models\Import;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\UsesClass;
use Tests\Unit\Filament\FilamentTestCase;
#[UsesClass(ImportResource::class)]
class ImportResourceTest 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_imports(): void
{
// Arrange
$imports = collect([
Import::factory()->create(),
Import::factory()->running()->create(),
Import::factory()->completed()->create(),
Import::factory()->failed()->create(),
]);
// Act
$response = Livewire::test(ImportResource\Pages\ListImports::class);
// Assert
$response->assertSuccessful();
$response->assertCanSeeTableRecords($imports);
}
public function test_can_see_view_page_of_import(): void
{
// Arrange
$import = Import::factory()->completed()->create();
// Act
$response = Livewire::test(ImportResource\Pages\ViewImport::class, [
'record' => $import->getKey(),
]);
// Assert
$response->assertSuccessful();
}
}

View File

@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace Tests\Unit\Filament\Resources;
use App\Enums\ImportStatus;
use App\Enums\Role;
use App\Events\OrganizationInvitationAdding;
use App\Filament\Resources\OrganizationResource;
use App\Filament\Resources\UserResource;
use App\Mail\OrganizationInvitationMail;
use App\Models\Import;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
@@ -17,12 +19,11 @@ use App\Models\User;
use App\Service\DeletionService;
use App\Service\Export\ExportService;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\Importers\ReportDto;
use App\Service\Import\ImportService;
use Exception;
use Filament\Notifications\Notification;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
@@ -173,23 +174,18 @@ class OrganizationResourceTest extends FilamentTestCase
// Arrange
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock) use ($organization): void {
$mock->shouldReceive('import')
->withArgs(function (Organization $organizationArg, string $importerType, string $data, string $timezone) use ($organization): bool {
$import = Import::factory()->forOrganization($organization)->create();
$this->mock(ImportService::class, function (MockInterface $mock) use ($organization, $import): void {
$mock->shouldReceive('createFileImport')
->withArgs(function (Organization $organizationArg, ?User $user, string $importerType, string $data, string $timezone) use ($organization): bool {
return $organizationArg->is($organization)
&& $user?->email === 'admin@example.com'
&& $importerType === 'toggl_time_entries'
&& $data === 'csv-content'
&& $timezone === 'Europe/Vienna';
})
->once()
->andReturn(new ReportDto(
clientsCreated: 1,
projectsCreated: 2,
tasksCreated: 3,
timeEntriesCreated: 4,
tagsCreated: 5,
usersCreated: 6,
));
->andReturn($import);
});
// Act
@@ -203,24 +199,11 @@ class OrganizationResourceTest extends FilamentTestCase
// Assert
$response->assertHasNoTableActionErrors();
$response->assertSuccessful();
$response->assertNotified(
Notification::make()
->title('Import successful')
->success()
->body(
'Imported time entries: 4<br>'.
'Imported clients: 1<br>'.
'Imported projects: 2<br>'.
'Imported tasks: 3<br>'.
'Imported tags: 5<br>'.
'Imported users: 6'
)
->persistent()
);
$response->assertNotified('Import queued');
Storage::disk(config('filesystems.private'))->assertDirectoryEmpty('admin-import-uploads');
}
public function test_import_into_an_organization_stores_copy_of_import_data_for_debugging_and_deletes_upload(): void
public function test_import_into_an_organization_creates_import_with_copy_of_import_data_and_deletes_upload(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
@@ -239,13 +222,12 @@ class OrganizationResourceTest extends FilamentTestCase
$response->assertHasNoTableActionErrors();
$response->assertSuccessful();
Storage::disk(config('filesystems.private'))->assertDirectoryEmpty('admin-import-uploads');
$storedFiles = Storage::disk(config('filesystems.private'))->files('import');
$this->assertCount(1, $storedFiles);
$this->assertMatchesRegularExpression(
'/^import\/'.preg_quote(Carbon::now()->toDateString(), '/').'-'.preg_quote($organization->getKey(), '/').'-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/',
$storedFiles[0]
);
$this->assertSame($data, Storage::disk(config('filesystems.private'))->get($storedFiles[0]));
/** @var Import $import */
$import = Import::query()->whereBelongsTo($organization, 'organization')->firstOrFail();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertSame('Europe/Vienna', $import->timezone);
$this->assertSame(Auth::id(), $import->user_id);
$this->assertSame($data, Storage::disk(config('filesystems.private'))->get((string) $import->file_path));
}
public function test_import_into_organization_shows_error_notification_on_import_exception(): void
@@ -254,9 +236,9 @@ class OrganizationResourceTest extends FilamentTestCase
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock): void {
$mock->shouldReceive('import')
$mock->shouldReceive('createFileImport')
->once()
->andThrow(new ImportException('Invalid CSV'));
->andThrow(new ImportException('Import is already in progress'));
});
// Act
@@ -271,9 +253,9 @@ class OrganizationResourceTest extends FilamentTestCase
$response->assertSuccessful();
$response->assertNotified(
Notification::make()
->title('Import failed, changes rolled back')
->title('Import failed')
->danger()
->body('Message: Invalid CSV')
->body('Message: Import is already in progress')
->persistent()
);
Storage::disk(config('filesystems.private'))->assertDirectoryEmpty('admin-import-uploads');
@@ -285,7 +267,7 @@ class OrganizationResourceTest extends FilamentTestCase
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock): void {
$mock->shouldNotReceive('import');
$mock->shouldNotReceive('createFileImport');
});
// Act
@@ -300,7 +282,7 @@ class OrganizationResourceTest extends FilamentTestCase
$response->assertSuccessful();
$response->assertNotified(
Notification::make()
->title('Import failed, changes rolled back')
->title('Import failed')
->danger()
->body('Message: File not found')
->persistent()
@@ -313,7 +295,7 @@ class OrganizationResourceTest extends FilamentTestCase
Storage::fake(config('filesystems.private'), ['throw' => false]);
$organization = Organization::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock): void {
$mock->shouldNotReceive('import');
$mock->shouldNotReceive('createFileImport');
});
// Act
@@ -328,7 +310,7 @@ class OrganizationResourceTest extends FilamentTestCase
$response->assertSuccessful();
$response->assertNotified(
Notification::make()
->title('Import failed, changes rolled back')
->title('Import failed')
->danger()
->body('Message: File not found')
->persistent()
@@ -340,7 +322,7 @@ class OrganizationResourceTest extends FilamentTestCase
// Arrange
$organization = Organization::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock): void {
$mock->shouldNotReceive('import');
$mock->shouldNotReceive('createFileImport');
});
// Act

View File

@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Jobs;
use App\Enums\ImportStatus;
use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Service\Import\ImportService;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use RuntimeException;
use Tests\TestCaseWithDatabase;
#[CoversClass(ProcessImport::class)]
class ProcessImportTest extends TestCaseWithDatabase
{
public function test_job_processes_import_via_import_service(): void
{
// Arrange
$import = Import::factory()->create();
$this->mock(ImportService::class, function (MockInterface $mock) use ($import): void {
$mock->shouldReceive('process')
->withArgs(fn (Import $processedImport): bool => $processedImport->is($import))
->once();
});
// Act
ProcessImport::dispatchSync($import);
}
public function test_job_uses_timeout_and_queue_from_config(): void
{
// Arrange
config([
'import.job_timeout' => 123,
'import.queue' => 'imports',
]);
$import = Import::factory()->create();
// Act
$job = new ProcessImport($import);
// Assert
$this->assertSame(123, $job->timeout);
$this->assertSame(1, $job->tries);
$this->assertSame('imports', $job->queue);
}
public function test_failed_marks_active_import_as_failed(): void
{
// Arrange
$import = Import::factory()->running()->create();
$job = new ProcessImport($import);
// Act
$job->failed(new RuntimeException('Timeout'));
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Import could not be finished', $import->error_message);
}
public function test_failed_does_not_change_finished_import(): void
{
// Arrange
$import = Import::factory()->completed()->create();
$job = new ProcessImport($import);
// Act
$job->failed(new RuntimeException('Timeout'));
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertNull($import->error_message);
}
}

View File

@@ -11,6 +11,7 @@ use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembe
use App\Models\Audit;
use App\Models\Client;
use App\Models\Goal;
use App\Models\Import;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Passport\Client as PassportClient;
@@ -46,6 +47,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
BeforeOrganizationDeletion::class,
BeforeUserDeletion::class,
]);
Storage::fake(config('filesystems.private'));
$this->deletionService = app(DeletionService::class);
}
@@ -64,7 +66,8 @@ class DeletionServiceTest extends TestCaseWithDatabase
* timeEntries: Collection<TimeEntry>,
* owner: User,
* reports: Collection<Report>,
* goals: Collection<Goal>
* goals: Collection<Goal>,
* imports: Collection<Import>
* }
*/
private function createOrganizationWithAllRelations(): object
@@ -113,6 +116,13 @@ class DeletionServiceTest extends TestCaseWithDatabase
$goal2 = Goal::factory()->forMember($memberEmployee)->create();
$goals = collect([$goal1, $goal2]);
$importWithFile = Import::factory()->forOrganization($organization)->forUser($userOwner)->completed()->create([
'file_path' => 'import/'.$organization->getKey().'/'.Str::uuid(),
]);
Storage::disk(config('filesystems.private'))->put($importWithFile->file_path, 'import data');
$importWithoutFile = Import::factory()->forOrganization($organization)->forUser($userEmployee)->failed()->create();
$imports = collect([$importWithFile, $importWithoutFile]);
$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);
@@ -130,6 +140,7 @@ class DeletionServiceTest extends TestCaseWithDatabase
'owner' => $userOwner,
'reports' => $reports,
'goals' => $goals,
'imports' => $imports,
];
}
@@ -147,6 +158,8 @@ class DeletionServiceTest extends TestCaseWithDatabase
$this->assertSame(0, Task::query()->whereBelongsTo($organization, 'organization')->count());
$this->assertSame(0, Report::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([], Storage::disk(config('filesystems.private'))->allFiles('import/'.$organization->getKey()));
$this->assertSame(0, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
}
@@ -161,6 +174,8 @@ class DeletionServiceTest extends TestCaseWithDatabase
$this->assertSame(2, Task::query()->whereBelongsTo($organization, 'organization')->count());
$this->assertSame(2, Report::query()->whereBelongsTo($organization, 'organization')->count());
$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($specialCase ? 7 : 6, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
}

View File

@@ -4,15 +4,25 @@ declare(strict_types=1);
namespace Tests\Unit\Service\Import;
use App\Enums\ImportSource;
use App\Enums\ImportStatus;
use App\Jobs\ProcessImport;
use App\Models\Import;
use App\Models\Organization;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\Import\Importers\ImporterContract;
use App\Service\Import\Importers\ImporterProvider;
use App\Service\Import\Importers\ImportException;
use App\Service\Import\ImportService;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use RuntimeException;
use Tests\TestCase;
#[CoversClass(ImportService::class)]
@@ -21,68 +31,233 @@ class ImportServiceTest extends TestCase
{
use RefreshDatabase;
public function test_import_gets_importer_from_provider_runs_importer_and_returns_report(): void
public function test_create_file_import_stores_file_creates_pending_import_and_dispatches_job(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$timezone = 'Europe/Vienna';
$user = User::factory()->create();
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
// Act
$importService = app(ImportService::class);
$report = $importService->import($organization, 'toggl_time_entries', $data, $timezone);
$import = app(ImportService::class)->createFileImport($organization, $user, 'toggl_time_entries', $data, 'Europe/Vienna');
// Assert
$lock = Cache::lock('import:'.$organization->getKey());
$this->assertTrue($lock->get());
$this->assertSame(2, $report->timeEntriesCreated);
$this->assertSame(2, $report->tagsCreated);
$this->assertSame(1, $report->tasksCreated);
$this->assertSame(1, $report->usersCreated);
$this->assertSame(2, $report->projectsCreated);
$this->assertSame(1, $report->clientsCreated);
$storedFiles = Storage::disk(config('filesystems.private'))->files('import');
$this->assertCount(1, $storedFiles);
$this->assertStringStartsWith('import/'.Carbon::now()->toDateString().'-'.$organization->getKey().'-', $storedFiles[0]);
$this->assertSame($data, Storage::disk(config('filesystems.private'))->get($storedFiles[0]));
$import->refresh();
$this->assertSame('toggl_time_entries', $import->type);
$this->assertSame(ImportSource::File, $import->source);
$this->assertSame(ImportStatus::Pending, $import->status);
$this->assertSame('Europe/Vienna', $import->timezone);
$this->assertSame($organization->getKey(), $import->organization_id);
$this->assertSame($user->getKey(), $import->user_id);
$this->assertSame('import/'.$organization->getKey().'/'.$import->getKey(), $import->file_path);
$this->assertSame($data, Storage::disk(config('filesystems.private'))->get($import->file_path));
Queue::assertPushed(ProcessImport::class, fn (ProcessImport $job): bool => $job->import->is($import));
}
public function test_import_releases_lock_if_an_exception_happens_during_the_import(): void
public function test_create_file_import_throws_exception_if_import_is_already_in_progress(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$timezone = 'Europe/Vienna';
$data = 'Invalid CSV data';
Import::factory()->forOrganization($organization)->running()->create();
// Act
$importService = app(ImportService::class);
try {
$importService->import($organization, 'toggl_time_entries', $data, $timezone);
} catch (ImportException) {
app(ImportService::class)->createFileImport($organization, null, 'toggl_time_entries', 'data', 'Europe/Vienna');
$this->fail('Expected ImportException');
} catch (ImportException $exception) {
// Assert
$lock = Cache::lock('import:'.$organization->getKey());
$this->assertTrue($lock->get());
$this->assertSame('Import is already in progress', $exception->getMessage());
}
$this->assertSame(1, Import::query()->count());
$this->assertSame([], Storage::disk(config('filesystems.private'))->allFiles());
Queue::assertNothingPushed();
}
public function test_import_throws_exception_if_import_is_already_in_progress(): void
public function test_create_file_import_allows_new_import_if_previous_imports_are_finished(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
Import::factory()->forOrganization($organization)->completed()->create();
Import::factory()->forOrganization($organization)->failed()->create();
// Act
$import = app(ImportService::class)->createFileImport($organization, null, 'toggl_time_entries', 'data', 'Europe/Vienna');
// Assert
$this->assertSame(ImportStatus::Pending, $import->status);
$this->assertSame(3, Import::query()->count());
}
public function test_create_file_import_throws_exception_if_importer_type_is_unknown(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
// Assert
$this->expectException(InvalidArgumentException::class);
// Act
app(ImportService::class)->createFileImport($organization, null, 'unknown', 'data', 'Europe/Vienna');
}
public function test_database_allows_only_one_active_import_per_organization(): void
{
// Arrange
$organization = Organization::factory()->create();
Import::factory()->forOrganization($organization)->create();
// Assert
$this->expectException(UniqueConstraintViolationException::class);
// Act
Import::factory()->forOrganization($organization)->running()->create();
}
public function test_process_runs_importer_and_stores_report(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$timezone = 'Europe/Vienna';
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
Cache::lock('import:'.$organization->getKey(), 10)->get();
Storage::disk(config('filesystems.private'))->put('import/test', $data);
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
'credentials' => ['token' => 'secret'],
]);
// Act
$importService = app(ImportService::class);
try {
$importService->import($organization, 'toggl_time_entries', $data, $timezone);
} catch (ImportException $e) {
// Assert
$this->assertSame('Import is already in progress', $e->getMessage());
}
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertNotNull($import->started_at);
$this->assertNotNull($import->finished_at);
$this->assertNull($import->error_message);
$this->assertNull($import->credentials);
// Note: jsonb does not preserve the key order
$this->assertEquals([
'clients' => ['created' => 1],
'projects' => ['created' => 2],
'tasks' => ['created' => 1],
'time_entries' => ['created' => 2],
'tags' => ['created' => 2],
'users' => ['created' => 1],
], $import->report);
$this->assertSame(2, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
}
public function test_process_marks_import_as_failed_with_message_if_importer_throws_import_exception(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
Storage::disk(config('filesystems.private'))->put('import/test', 'Invalid CSV data');
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
'credentials' => ['token' => 'secret'],
]);
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertNotNull($import->error_message);
$this->assertNotSame('Unexpected error during import', $import->error_message);
$this->assertNull($import->report);
$this->assertNull($import->credentials);
$this->assertNotNull($import->finished_at);
}
public function test_process_marks_import_as_failed_with_generic_message_and_rolls_back_on_unexpected_error(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
Storage::disk(config('filesystems.private'))->put('import/test', 'data');
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
]);
$importer = $this->mock(ImporterContract::class, function (MockInterface $mock) use ($organization): void {
$mock->shouldReceive('init')->once();
$mock->shouldReceive('importData')
->once()
->andReturnUsing(function () use ($organization): void {
TimeEntry::factory()->forOrganization($organization)->create();
throw new RuntimeException('Something went wrong');
});
});
$this->mock(ImporterProvider::class, function (MockInterface $mock) use ($importer): void {
$mock->shouldReceive('getImporter')->with('toggl_time_entries')->andReturn($importer);
});
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Unexpected error during import', $import->error_message);
$this->assertSame(0, TimeEntry::query()->count());
}
public function test_process_marks_import_as_failed_if_file_does_not_exist(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
$import = Import::factory()->create([
'file_path' => 'import/does-not-exist',
]);
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Import file does not exist anymore', $import->error_message);
}
public function test_process_skips_import_that_is_not_pending(): void
{
// Arrange
$import = Import::factory()->completed()->create();
$finishedAt = $import->finished_at;
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertEquals($finishedAt, $import->finished_at);
}
public function test_mark_as_failed_sets_status_message_and_removes_credentials(): void
{
// Arrange
$import = Import::factory()->running()->create([
'credentials' => ['token' => 'secret'],
]);
// Act
app(ImportService::class)->markAsFailed($import, 'Some error');
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Some error', $import->error_message);
$this->assertNull($import->credentials);
$this->assertNotNull($import->finished_at);
}
}