Limit the number of records a single import can create

This commit is contained in:
Constantin Graf
2026-11-03 16:49:37 +01:00
committed by Constantin Graf
parent a83eeb0222
commit cecaa429c9
10 changed files with 139 additions and 4 deletions

View File

@@ -17,6 +17,7 @@ use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
@@ -69,6 +70,9 @@ class ImportResource extends Resource
TextInput::make('file_path')
->label('File path')
->disabled(),
Toggle::make('ignore_limits')
->label('Ignore limits (admin import)')
->disabled(),
Textarea::make('error_message')
->label('Error message')
->columnSpanFull()

View File

@@ -200,7 +200,8 @@ class OrganizationResource extends Resource
$user,
$data['type'],
$file,
$timezone
$timezone,
ignoreLimits: true
);
Notification::make()
->title('Import queued')

View File

@@ -23,6 +23,7 @@ use Illuminate\Support\Carbon;
* @property string|null $file_path
* @property array<string, mixed>|null $credentials
* @property array<string, mixed>|null $options
* @property bool $ignore_limits
* @property array<string, mixed>|null $report
* @property string|null $error_message
* @property Carbon|null $started_at
@@ -53,6 +54,7 @@ class Import extends Model
'status' => ImportStatus::class,
'credentials' => 'encrypted:array',
'options' => 'array',
'ignore_limits' => 'bool',
'report' => 'array',
'started_at' => 'datetime',
'finished_at' => 'datetime',

View File

@@ -13,6 +13,7 @@ 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\DB;
@@ -26,9 +27,11 @@ class ImportService
/**
* Stores the import file and queues the import.
*
* @param bool $ignoreLimits Skip the import limits, only for imports started by a super admin (admin panel)
*
* @throws ImportException
*/
public function createFileImport(Organization $organization, ?User $user, string $importerType, string $data, string $timezone): Import
public function createFileImport(Organization $organization, ?User $user, string $importerType, string $data, string $timezone, bool $ignoreLimits = false): Import
{
// Throws an InvalidArgumentException if the importer type is unknown
app(ImporterProvider::class)->getImporter($importerType);
@@ -42,6 +45,7 @@ class ImportService
$import->source = ImportSource::File;
$import->status = ImportStatus::Pending;
$import->timezone = $timezone;
$import->ignore_limits = $ignoreLimits;
$import->organization()->associate($organization);
$import->user()->associate($user);
$import->id = $import->newUniqueId();
@@ -88,6 +92,8 @@ class ImportService
$data = $this->getImportData($import);
DB::transaction(function () use (&$importer, &$data, $import): void {
$importer->importData($data, $import->timezone);
// Note: The limit is checked after the import, the exception rolls back all created records
$this->checkLimits($import, $importer->getReport());
});
$import->status = ImportStatus::Completed;
@@ -119,6 +125,22 @@ class ImportService
$import->save();
}
/**
* @throws ImportException
*/
private function checkLimits(Import $import, ReportDto $report): void
{
$maxRecords = config('import.max_records');
if ($import->ignore_limits || $maxRecords === null) {
return;
}
$totalCreated = $report->getTotalCreated();
if ($totalCreated > $maxRecords) {
throw new ImportException('The import would create '.$totalCreated.' records, but imports are limited to '.
$maxRecords.' records. Bigger imports are possible, please contact the support.');
}
}
/**
* @throws ImportException
*/

View File

@@ -28,6 +28,12 @@ class ReportDto
$this->usersCreated = $usersCreated;
}
public function getTotalCreated(): int
{
return $this->clientsCreated + $this->projectsCreated + $this->tasksCreated +
$this->timeEntriesCreated + $this->tagsCreated + $this->usersCreated;
}
/**
* @return array{
* clients: array{

View File

@@ -16,6 +16,20 @@ return [
'max_data_size' => (int) (env('IMPORT_MAX_DATA_SIZE') ?: 50 * 1024 * 1024),
/*
|--------------------------------------------------------------------------
| Import record limit
|--------------------------------------------------------------------------
|
| Maximum number of records (clients, projects, tasks, time entries, tags
| and users) a single import can create. Imports that exceed the limit
| fail and are rolled back. Imports started via the admin panel are not
| limited. Null disables the limit.
|
*/
'max_records' => is_numeric(env('IMPORT_MAX_RECORDS')) ? (int) env('IMPORT_MAX_RECORDS') : null,
/*
|--------------------------------------------------------------------------
| ZIP extraction limits

View File

@@ -32,6 +32,7 @@ class ImportFactory extends Factory
'file_path' => null,
'credentials' => null,
'options' => null,
'ignore_limits' => false,
'report' => null,
'error_message' => null,
'started_at' => null,

View File

@@ -27,6 +27,8 @@ return new class extends Migration
// Encrypted credentials for imports via a third party API, removed after the import finished
$table->text('credentials')->nullable();
$table->jsonb('options')->nullable();
// Imports started by a super admin (admin panel) are not limited by the configured import limits
$table->boolean('ignore_limits')->default(false);
$table->jsonb('report')->nullable();
$table->text('error_message')->nullable();
$table->dateTime('started_at')->nullable();

View File

@@ -177,12 +177,13 @@ class OrganizationResourceTest extends FilamentTestCase
$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 {
->withArgs(function (Organization $organizationArg, ?User $user, string $importerType, string $data, string $timezone, bool $ignoreLimits) use ($organization): bool {
return $organizationArg->is($organization)
&& $user?->email === 'admin@example.com'
&& $importerType === 'toggl_time_entries'
&& $data === 'csv-content'
&& $timezone === 'Europe/Vienna';
&& $timezone === 'Europe/Vienna'
&& $ignoreLimits;
})
->once()
->andReturn($import);
@@ -206,6 +207,8 @@ class OrganizationResourceTest extends FilamentTestCase
public function test_import_into_an_organization_creates_import_with_copy_of_import_data_and_deletes_upload(): void
{
// Arrange
// Note: Imports started via the admin panel are not limited
Config::set('import.max_records', 1);
Storage::fake(config('filesystems.private'));
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
$organization = Organization::factory()->create();
@@ -225,6 +228,7 @@ class OrganizationResourceTest extends FilamentTestCase
/** @var Import $import */
$import = Import::query()->whereBelongsTo($organization, 'organization')->firstOrFail();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertTrue($import->ignore_limits);
$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));

View File

@@ -211,6 +211,85 @@ class ImportServiceTest extends TestCase
$this->assertSame(0, TimeEntry::query()->count());
}
public function test_process_fails_and_rolls_back_if_import_exceeds_record_limit(): void
{
// Arrange
config(['import.max_records' => 8]);
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
Storage::disk(config('filesystems.private'))->put('import/test', $data);
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
]);
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('The import would create 9 records, but imports are limited to 8 records. '.
'Bigger imports are possible, please contact the support.', $import->error_message);
$this->assertNull($import->report);
$this->assertSame(0, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
}
public function test_process_succeeds_if_import_is_exactly_at_record_limit(): void
{
// Arrange
config(['import.max_records' => 9]);
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
Storage::disk(config('filesystems.private'))->put('import/test', $data);
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
]);
// Act
app(ImportService::class)->process($import);
// Assert
$this->assertSame(ImportStatus::Completed, $import->refresh()->status);
}
public function test_process_ignores_record_limit_if_import_ignores_limits(): void
{
// Arrange
config(['import.max_records' => 1]);
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
$data = Storage::disk('testfiles')->get('toggl_time_entries_import_test_1.csv');
Storage::disk(config('filesystems.private'))->put('import/test', $data);
$import = Import::factory()->forOrganization($organization)->create([
'file_path' => 'import/test',
'ignore_limits' => true,
]);
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Completed, $import->status);
$this->assertSame(2, TimeEntry::query()->whereBelongsTo($organization, 'organization')->count());
}
public function test_create_file_import_stores_ignore_limits_flag(): void
{
// Arrange
Queue::fake();
Storage::fake(config('filesystems.private'));
$organization = Organization::factory()->create();
// Act
$import = app(ImportService::class)->createFileImport($organization, null, 'toggl_time_entries', 'data', 'Europe/Vienna', ignoreLimits: true);
// Assert
$this->assertTrue($import->refresh()->ignore_limits);
}
public function test_process_marks_import_as_failed_if_file_does_not_exist(): void
{
// Arrange