Compare commits

...

21 Commits

Author SHA1 Message Date
dependabot[bot]
acc0fdd10b Bump sigstore/cosign-installer from 4.1.3 to 4.1.4
Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 4.1.3 to 4.1.4.
- [Release notes](https://github.com/sigstore/cosign-installer/releases)
- [Commits](756fe2d284...881c63bd87)

---
updated-dependencies:
- dependency-name: sigstore/cosign-installer
  dependency-version: 4.1.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-12-04 16:09:40 +01:00
Constantin Graf
81a0cf8aac Load existing time entries per member and compare the type when deduplicating imports
Existing time entries are now loaded per member and month (backed by the
member_id/start index) and streamed with a cursor, so only the members an
import touches are loaded. The type is part of the fingerprint, so a break is
no longer matched against a work entry.
2026-12-04 16:02:06 +01:00
Constantin Graf
a166f8ef44 Skip time entries that already exist when importing
Re-importing the same data duplicated all time entries, because only
clients, projects, tasks, tags and users were matched with existing
records. Time entries are now matched by member, start, end, project,
task and description. Matches are counted, so identical time entries
within one import are still kept.

Fixes #894
2026-12-04 16:02:06 +01:00
Gregor Vostrak
7fd9f36d69 Request uncompressed imports response in running import e2e test 2026-12-04 15:48:42 +01:00
Gregor Vostrak
e2dc40a305 keep black solidtime logo in guided import 2026-12-04 15:48:42 +01:00
Gregor Vostrak
c448955838 fix hover colors in light mode for ghost and outline buttons 2026-12-04 15:48:42 +01:00
Gregor Vostrak
51f594d0a5 add importer wizard with guided steps for each type 2026-12-04 15:48:42 +01:00
Constantin Graf
bd851e4edf Run the project's pint version in the linting workflow
The laravel-pint-action builds on composer:latest, whose current image lacks
mbstring and crashes pint. Run vendor/bin/pint after setting up PHP instead,
which also uses the pint version from composer.lock. Remove an unused import
that the newer pint version reports.
2026-12-04 15:48:42 +01:00
Constantin Graf
1b6ca3e00f Reject import files that are not UTF-8 encoded
Invalid UTF-8 (for example CSV files saved as Windows-1252 by Excel) was only
rejected by the database on insert, which failed the import with a generic
unexpected error. The CSV importers and the CSV files in solidtime exports are
now checked up front and fail with a clear message.
2026-12-04 15:48:42 +01:00
Constantin Graf
463182666b Wait for background import in e2e helper and fix coverage metadata of import and export tests 2026-12-04 15:48:42 +01:00
Constantin Graf
cbc7261a12 Only report unexpected errors of imports 2026-12-04 15:48:42 +01:00
Constantin Graf
eb1e89a91d Mark stale imports and exports as failed before creating new ones and fix review findings
- Mark stale imports/exports of the organization as failed when a new one is created, so they do not block until the prune command runs
- Move the stale check into a stale() scope on the Import and Export models
- Remove orderBy(created_at) from chunkById queries in the prune commands, it skipped rows with random UUIDs
- Delete the export file if the export was deleted while it was running
- Extract the error details formatting into ErrorDetailsFormatter
- Add the exports() relation to Organization
2026-12-04 15:48:42 +01:00
Constantin Graf
b5aa2f7e1a Rename import controller methods to match the export controller 2026-12-04 15:48:42 +01:00
Constantin Graf
89d004f88c Detect project members of another organization in the database consistency check 2026-12-04 15:48:42 +01:00
Constantin Graf
50c028ee23 Reject solidtime imports with project members that reference missing records 2026-12-04 15:48:42 +01:00
Constantin Graf
e44a3733e1 Store error details of failed imports and show them in the admin panel
The importers keep the original exception as the previous exception, so the
exception chain and stack trace can be stored in the new error_details column.
The details are only visible in the admin panel, which now also links the
organization and user of an import.
2026-12-04 15:48:42 +01:00
Constantin Graf
4c8215a889 Store exports in the database and process them in a queued job 2026-12-04 15:48:42 +01:00
Constantin Graf
a440687a41 Mark timed out and stale imports as failed in the prune command
The job's failed() handler can not mark a timed out import as failed, since
the timeout handler runs while the import transaction is still open and the
change is rolled back when the worker is killed. It also must not mark the
import as failed when the queue hands out the job a second time after
retry_after, while the first attempt is still running.

Running imports are now considered stale shortly after the job timeout and
the prune command runs every five minutes.
2026-12-04 15:48:42 +01:00
Constantin Graf
cecaa429c9 Limit the number of records a single import can create 2026-12-04 15:48:42 +01:00
Constantin Graf
a83eeb0222 Store imports in the database and process them in a queued job 2026-12-04 15:48:42 +01:00
Constantin Graf
1a589a9552 Wait for minio before creating the bucket and update the playwright image 2026-12-04 15:48:42 +01:00
126 changed files with 7702 additions and 668 deletions

View File

@@ -265,7 +265,7 @@ jobs:
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
# Keyless signing via GitHub OIDC; the signature is recorded in the public Sigstore transparency log.
- name: "Sign image"

View File

@@ -264,7 +264,7 @@ jobs:
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
# Keyless signing via GitHub OIDC; the deploy script verifies this signature before rollout.
- name: "Sign image"

View File

@@ -222,7 +222,7 @@ jobs:
- name: "Install cosign"
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
# Keyless signing via GitHub OIDC; the signature is recorded in the public Sigstore transparency log.
- name: "Sign image"

View File

@@ -11,7 +11,15 @@ jobs:
- name: "Checkout code"
uses: actions/checkout@v7
- name: "Check code style"
uses: aglipanci/laravel-pint-action@2.6
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
configPath: "pint.json"
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
coverage: none
- name: "Run composer install"
run: composer install -n --prefer-dist
- name: "Check code style"
run: vendor/bin/pint --test --config pint.json

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands\Export;
use App\Models\Export;
use App\Service\Export\ExportService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
class ExportPruneCommand extends Command
{
/**
* 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.');
}
$staleExports = 0;
Export::query()
->stale()
->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)
->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

@@ -0,0 +1,78 @@
<?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
{
/**
* 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.');
}
$staleImports = 0;
Import::query()
->stale()
->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)
->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

@@ -106,6 +106,15 @@ class SelfHostDatabaseConsistency extends Command
})->get();
$this->logProblems($problems, 'Users have a current organization that they are not a member of', $hadAProblem);
// Project members need to be a member of the organization of the project
$problems = DB::table('project_members')
->select(['project_members.id as id'])
->join('projects', 'project_members.project_id', '=', 'projects.id')
->join('members', 'project_members.member_id', '=', 'members.id')
->whereColumn('members.organization_id', '!=', 'projects.organization_id')
->get();
$this->logProblems($problems, 'Project members have a member that does not belong to the organization of the project', $hadAProblem);
return $hadAProblem ? self::FAILURE : self::SUCCESS;
}

View File

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

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

@@ -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

@@ -8,14 +8,15 @@ use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use LogicException;
use Throwable;
abstract class ApiException extends 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

@@ -0,0 +1,222 @@
<?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\Forms\Components\Toggle;
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')
->hintAction(
Action::make('open-organization')
->label('Open organization')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (?Import $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 (?Import $record): bool => $record?->user_id === null)
->url(fn (?Import $record): ?string => $record?->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
)
->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(),
Toggle::make('ignore_limits')
->label('Ignore limits (admin import)')
->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 (Import $record): ?string => $record->error_details)
->rows(15)
->extraInputAttributes(['style' => 'font-family: monospace; font-size: 80%;'])
->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')
->url(fn (Import $record): string => OrganizationResource::getUrl('view', ['record' => $record->organization_id]))
->searchable()
->sortable(),
TextColumn::make('user.email')
->label('User')
->url(fn (Import $record): ?string => $record->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
->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,30 @@ 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
$timezone,
ignoreLimits: true
);
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,8 +4,14 @@ declare(strict_types=1);
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\Service\Export\ExportException;
use App\Service\Export\ExportService;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
@@ -17,8 +23,11 @@ class ExportController extends Controller
/**
* 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 ExportException
* @throws ExportAlreadyInProgressApiException
*
* @operationId exportOrganization
*/
@@ -26,15 +35,85 @@ class ExportController extends Controller
{
$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'))
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"',
->temporaryUrl($export->file_path, Carbon::now()->addMinutes(10), [
'ResponseContentDisposition' => 'attachment; filename="'.$export->getDownloadFilename($this->user()->timezone).'"',
]);
return new JsonResponse([
'success' => true,
/** @var string $download_url Temporary download URL of the export file, valid for 10 minutes */
'download_url' => $downloadUrl,
], 200);
}
/**
* @throws AuthorizationException
*/
private function checkExportBelongsToOrganization(Organization $organization, Export $export): void
{
if ($export->organization_id !== $organization->getKey()) {
throw new AuthorizationException('Export does not belong to organization');
}
}
}

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;
@@ -24,7 +28,7 @@ class ImportController extends Controller
*
* @response array{data: array<array{ key: string, name: string, description: string }>}
*/
public function index(Organization $organization, ImporterProvider $importerProvider): JsonResponse
public function importers(Organization $organization, ImporterProvider $importerProvider): JsonResponse
{
$this->checkPermission($organization, 'import');
@@ -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 index(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

@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Http\Middleware;
use Filament\Http\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class AuthenticateFilamentPanel extends Middleware
{

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,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\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,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,66 @@
<?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,
* skipped: 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,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');
}
}
}

View File

@@ -0,0 +1,77 @@
<?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\MaxAttemptsExceededException;
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.
*/
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.
*/
public function failed(?Throwable $exception): void
{
// A MaxAttemptsExceededException is thrown in two cases where the import must not be marked as failed here:
// - The import 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 import timed out (TimeoutExceededException). The timeout handler runs while the import transaction
// is still open, so the change would be rolled back when the worker is killed.
// In both cases the import:prune command marks the import as failed if it is really stale.
if ($exception instanceof MaxAttemptsExceededException) {
return;
}
$this->import->refresh();
if ($this->import->status->isActive()) {
app(ImportService::class)->markAsFailed($this->import, 'Import could not be finished');
}
}
}

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

@@ -0,0 +1,145 @@
<?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;
/**
* Time in seconds a running export can exceed the job timeout before it is considered stale.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending export can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
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());
}
/**
* Active exports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Export> $builder
* @return Builder<Export>
*/
public function scopeStale(Builder $builder): Builder
{
$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);
return $builder->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);
});
});
}
}

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

@@ -0,0 +1,136 @@
<?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 bool $ignore_limits
* @property array<string, mixed>|null $report
* @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 ImportFactory factory()
*/
class Import extends Model
{
/** @use HasFactory<ImportFactory> */
use HasFactory;
use HasUuids;
/**
* Time in seconds a running import can exceed the job timeout before it is considered stale.
* Note: The job itself can not mark a timed out import as failed, since the timeout handler runs while the
* import transaction is still open and the change is rolled back when the worker is killed.
*/
private const int RUNNING_STALE_BUFFER_SECONDS = 300;
/**
* Time in seconds a pending import can exceed the job timeout before it is considered stale.
*/
private const int PENDING_STALE_BUFFER_SECONDS = 3600;
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'source' => ImportSource::class,
'status' => ImportStatus::class,
'credentials' => 'encrypted:array',
'options' => 'array',
'ignore_limits' => 'bool',
'report' => 'array',
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'credentials',
'error_details',
];
/**
* @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());
}
/**
* Active imports that are not finished in time, for example because the worker crashed or the job timed out.
* The buffers cover small delays after the job timeout (running) and the time the job waits in the queue (pending).
*
* @param Builder<Import> $builder
* @return Builder<Import>
*/
public function scopeStale(Builder $builder): Builder
{
$jobTimeout = (int) config('import.job_timeout');
$runningStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::RUNNING_STALE_BUFFER_SECONDS);
$pendingStaleBefore = Carbon::now()->subSeconds($jobTimeout + self::PENDING_STALE_BUFFER_SECONDS);
return $builder->where(function (Builder $query) use ($runningStaleBefore, $pendingStaleBefore): void {
$query->where(function (Builder $query) use ($runningStaleBefore): void {
$query->where('status', ImportStatus::Running)
->where('started_at', '<', $runningStaleBefore);
})->orWhere(function (Builder $query) use ($pendingStaleBefore): void {
$query->where('status', ImportStatus::Pending)
->where('created_at', '<', $pendingStaleBefore);
});
});
}
}

View File

@@ -40,6 +40,8 @@ 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-read Collection<int, Export> $exports
* @property Member $membership
* @property NumberFormat $number_format
* @property CurrencyFormat $currency_format
@@ -158,6 +160,22 @@ 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');
}
/**
* @return HasMany<Export, $this>
*/
public function exports(): HasMany
{
return $this->hasMany(Export::class, 'organization_id');
}
/**
* Find a model by its primary key or throw an exception.
*

View File

@@ -9,7 +9,9 @@ use App\Events\BeforeOrganizationDeletion;
use App\Events\BeforeUserDeletion;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Models\Client;
use App\Models\Export;
use App\Models\Goal;
use App\Models\Import;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
@@ -22,6 +24,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 +83,34 @@ 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);
});
}
// Delete all exports, the stored export files are deleted after the transaction is committed,
// since the deletion of files is not reversible via a database rollback
$exportFilePaths = Export::query()
->whereBelongsTo($organization, 'organization')
->whereNotNull('file_path')
->pluck('file_path')
->all();
Export::query()->whereBelongsTo($organization, 'organization')->delete();
if (count($exportFilePaths) > 0) {
DB::afterCommit(function () use ($exportFilePaths): void {
Storage::disk(config('filesystems.private'))->delete($exportFilePaths);
});
}
// Reset the current organization
$organization->owner()
->where('current_team_id', $organization->getKey())

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Illuminate\Support\Str;
use Throwable;
class ErrorDetailsFormatter
{
private const int MAX_LENGTH = 50000;
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
public static function format(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::MAX_LENGTH);
}
}

View File

@@ -4,7 +4,12 @@ declare(strict_types=1);
namespace App\Service\Export;
use App\Enums\ExportStatus;
use App\Enums\ExportType;
use App\Exceptions\Api\ExportAlreadyInProgressApiException;
use App\Jobs\ProcessExport;
use App\Models\Client;
use App\Models\Export;
use App\Models\Member;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
@@ -13,8 +18,11 @@ use App\Models\ProjectMember;
use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\ErrorDetailsFormatter;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\File;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
@@ -25,6 +33,7 @@ use League\Csv\Exception as LeagueCsvException;
use League\Csv\UnavailableStream;
use League\Csv\Writer;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use Throwable;
use ZipArchive;
class ExportService
@@ -32,11 +41,102 @@ class ExportService
public const string VERSION = '1.0';
/**
* Creates an export of all data of the organization and queues it.
*
* @throws ExportAlreadyInProgressApiException
*/
public function createOrganizationExport(Organization $organization, ?User $user): Export
{
// Stale exports would block new exports until the export:prune command runs
Export::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Export $staleExport) => $this->markAsFailed($staleExport, 'Export could not be finished'));
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 = ErrorDetailsFormatter::format($exception->getPrevious() ?? $exception);
} finally {
$export->finished_at = Carbon::now();
$export->save();
}
// The export (and its organization) can be deleted while the export is running, the file would be orphaned
if ($export->file_path !== null && ! Export::query()->whereKey($export->getKey())->exists()) {
Log::warning('Deleting file of export that was deleted while it was running', [
'export_id' => $export->getKey(),
]);
Storage::disk(config('filesystems.private'))->delete($export->file_path);
}
}
/**
* 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();
}
/**
* Creates the export ZIP file and stores it on the private disk.
*
* @return string Path of the ZIP file on the private disk
*
* @throws ExportException
*/
public function export(Organization $organization): string
public function export(Organization $organization, ?string $exportId = null): string
{
$exportId = Str::uuid();
$exportId ??= (string) Str::uuid();
$timeStamp = Carbon::now();
$temporaryDirectory = TemporaryDirectory::make();
Log::debug('Start exporting organization', [
@@ -365,9 +465,10 @@ class ExportService
$zip->close();
// Upload ZIP file to private storage
$filename = 'export_'.$organization->getKey().'_'.$timeStamp->format('Y-m-d_H-i-s').'_'.$exportId.'.zip';
$folder = 'exports/'.$organization->getKey();
$filename = $exportId.'.zip';
Storage::disk(config('filesystems.private'))->putFileAs(
'exports',
$folder,
new File($temporaryDirectoryZip->path('export.zip')),
$filename
);
@@ -381,11 +482,11 @@ class ExportService
'export_id' => $exportId,
]);
return 'exports/'.$filename;
return $folder.'/'.$filename;
} catch (UnavailableStream|CannotInsertRecord|Exception|LeagueCsvException $exception) {
report($exception);
throw new ExportException;
throw new ExportException(previous: $exception);
}
}
}

View File

@@ -4,44 +4,168 @@ 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\ErrorDetailsFormatter;
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.
*
* @param bool $ignoreLimits Skip the import limits, only for imports started by a super admin (admin panel)
*
* @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, bool $ignoreLimits = false): 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);
// Stale imports would block new imports until the import:prune command runs
Import::query()->whereBelongsTo($organization, 'organization')->stale()->get()
->each(fn (Import $staleImport) => $this->markAsFailed($staleImport, 'Import could not be finished'));
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->ignore_limits = $ignoreLimits;
$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);
// Note: The limit is checked after the import, the exception rolls back all created records
$this->checkLimits($import, $importer->getReport());
});
$import->status = ImportStatus::Completed;
$import->report = $importer->getReport()->toArray();
} catch (ImportException $exception) {
// Import exceptions are not reported, they are caused by invalid import data or the importers already
// reported the underlying unexpected error
$import->status = ImportStatus::Failed;
$import->error_message = $exception->getMessage();
$import->error_details = ErrorDetailsFormatter::format($exception);
} catch (Throwable $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = 'Unexpected error during import';
$import->error_details = ErrorDetailsFormatter::format($exception);
} 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 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
*/
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

@@ -20,6 +20,7 @@ class ClockifyProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -67,10 +68,10 @@ class ClockifyProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -49,6 +49,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -202,6 +203,9 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -214,10 +218,10 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -12,10 +12,12 @@ use App\Models\Project;
use App\Models\ProjectMember;
use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\BillableRateService;
use App\Service\ColorService;
use App\Service\Import\ImportDatabaseHelper;
use App\Service\Import\TimeEntryDeduplicator;
use App\Service\TimezoneService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
@@ -60,6 +62,10 @@ abstract class DefaultImporter implements ImporterContract
protected int $timeEntriesCreated;
protected int $timeEntriesSkipped;
protected TimeEntryDeduplicator $timeEntryDeduplicator;
protected ColorService $colorService;
protected TimezoneService $timezoneService;
@@ -205,6 +211,8 @@ abstract class DefaultImporter implements ImporterContract
],
]);
$this->timeEntriesCreated = 0;
$this->timeEntriesSkipped = 0;
$this->timeEntryDeduplicator = new TimeEntryDeduplicator($organization->getKey());
$this->colorService = app(ColorService::class);
$this->timezoneService = app(TimezoneService::class);
}
@@ -235,6 +243,52 @@ abstract class DefaultImporter implements ImporterContract
}
}
/**
* @throws ImportException
*/
protected function checkUtf8(string $data, string $fileName = 'The file'): void
{
if (! mb_check_encoding($data, 'UTF-8')) {
throw new ImportException($fileName.' is not UTF-8 encoded, please export or save it as UTF-8 and try again');
}
}
/**
* Checks the file line by line, so large files are not loaded into memory at once. A line break is a single byte
* that never occurs inside a multibyte UTF-8 character, so splitting at line breaks is safe.
*
* @throws ImportException
*/
protected function checkFileUtf8(string $path, string $fileName): void
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new ImportException('File "'.$fileName.'" can not be opened');
}
try {
while (($line = fgets($handle)) !== false) {
$this->checkUtf8($line, 'File "'.$fileName.'"');
}
} finally {
fclose($handle);
}
}
/**
* Returns true if an equal time entry already exists in the organization, for example because the same data was
* imported before. The time entry is counted as skipped and should not be saved.
*/
protected function skipIfAlreadyExists(TimeEntry $timeEntry): bool
{
if ($this->timeEntryDeduplicator->claimExisting($timeEntry)) {
$this->timeEntriesSkipped++;
return true;
}
return false;
}
#[Override]
public function getReport(): ReportDto
{
@@ -243,6 +297,7 @@ abstract class DefaultImporter implements ImporterContract
projectsCreated: $this->projectImportHelper->getCreatedCount(),
tasksCreated: $this->taskImportHelper->getCreatedCount(),
timeEntriesCreated: $this->timeEntriesCreated,
timeEntriesSkipped: $this->timeEntriesSkipped,
tagsCreated: $this->tagImportHelper->getCreatedCount(),
usersCreated: $this->userImportHelper->getCreatedCount(),
);

View File

@@ -28,6 +28,7 @@ class GenericProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -70,10 +71,10 @@ class GenericProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -64,6 +64,7 @@ class GenericTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -166,6 +167,9 @@ class GenericTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -178,10 +182,10 @@ class GenericTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -25,6 +25,7 @@ class HarvestClientsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -42,10 +43,10 @@ class HarvestClientsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -29,6 +29,7 @@ class HarvestProjectsImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -73,10 +74,10 @@ class HarvestProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -40,6 +40,7 @@ class HarvestTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -148,6 +149,9 @@ class HarvestTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -160,10 +164,10 @@ class HarvestTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -14,20 +14,29 @@ class ReportDto
public int $timeEntriesCreated;
public int $timeEntriesSkipped;
public int $tagsCreated;
public int $usersCreated;
public function __construct(int $clientsCreated, int $projectsCreated, int $tasksCreated, int $timeEntriesCreated, int $tagsCreated, int $usersCreated)
public function __construct(int $clientsCreated, int $projectsCreated, int $tasksCreated, int $timeEntriesCreated, int $timeEntriesSkipped, int $tagsCreated, int $usersCreated)
{
$this->clientsCreated = $clientsCreated;
$this->projectsCreated = $projectsCreated;
$this->tasksCreated = $tasksCreated;
$this->timeEntriesCreated = $timeEntriesCreated;
$this->timeEntriesSkipped = $timeEntriesSkipped;
$this->tagsCreated = $tagsCreated;
$this->usersCreated = $usersCreated;
}
public function getTotalCreated(): int
{
return $this->clientsCreated + $this->projectsCreated + $this->tasksCreated +
$this->timeEntriesCreated + $this->tagsCreated + $this->usersCreated;
}
/**
* @return array{
* clients: array{
@@ -41,6 +50,7 @@ class ReportDto
* },
* time_entries: array{
* created: int,
* skipped: int,
* },
* tags: array{
* created: int,
@@ -64,6 +74,7 @@ class ReportDto
],
'time_entries' => [
'created' => $this->timeEntriesCreated,
'skipped' => $this->timeEntriesSkipped,
],
'tags' => [
'created' => $this->tagsCreated,

View File

@@ -53,6 +53,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('clients.csv'))) {
throw new ImportException('File "clients.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('clients.csv'), 'clients.csv');
$clientsReader = Reader::createFromPath($temporaryDirectory->path('clients.csv'));
$clientsReader->setHeaderOffset(0);
$clientsReader->setDelimiter(',');
@@ -62,6 +63,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('members.csv'))) {
throw new ImportException('File "members.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('members.csv'), 'members.csv');
$membersReader = Reader::createFromPath($temporaryDirectory->path('members.csv'));
$membersReader->setHeaderOffset(0);
$membersReader->setDelimiter(',');
@@ -71,6 +73,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('organization_invitations.csv'))) {
throw new ImportException('File "organization_invitations.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('organization_invitations.csv'), 'organization_invitations.csv');
$organizationInvitationsReader = Reader::createFromPath($temporaryDirectory->path('organization_invitations.csv'));
$organizationInvitationsReader->setHeaderOffset(0);
$organizationInvitationsReader->setDelimiter(',');
@@ -80,6 +83,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('project_members.csv'))) {
throw new ImportException('File "project_members.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('project_members.csv'), 'project_members.csv');
$projectMembersReader = Reader::createFromPath($temporaryDirectory->path('project_members.csv'));
$projectMembersReader->setHeaderOffset(0);
$projectMembersReader->setDelimiter(',');
@@ -89,6 +93,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('projects.csv'))) {
throw new ImportException('File "projects.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('projects.csv'), 'projects.csv');
$projectsReader = Reader::createFromPath($temporaryDirectory->path('projects.csv'));
$projectsReader->setHeaderOffset(0);
$projectsReader->setDelimiter(',');
@@ -98,6 +103,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('tags.csv'))) {
throw new ImportException('File "tags.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('tags.csv'), 'tags.csv');
$tagsReader = Reader::createFromPath($temporaryDirectory->path('tags.csv'));
$tagsReader->setHeaderOffset(0);
$tagsReader->setDelimiter(',');
@@ -107,6 +113,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('tasks.csv'))) {
throw new ImportException('File "tasks.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('tasks.csv'), 'tasks.csv');
$tasksReader = Reader::createFromPath($temporaryDirectory->path('tasks.csv'));
$tasksReader->setHeaderOffset(0);
$tasksReader->setDelimiter(',');
@@ -116,6 +123,7 @@ class SolidtimeImporter extends DefaultImporter
if (! file_exists($temporaryDirectory->path('time_entries.csv'))) {
throw new ImportException('File "time_entries.csv" missing in ZIP');
}
$this->checkFileUtf8($temporaryDirectory->path('time_entries.csv'), 'time_entries.csv');
$timeEntriesReader = Reader::createFromPath($temporaryDirectory->path('time_entries.csv'));
$timeEntriesReader->setHeaderOffset(0);
$timeEntriesReader->setDelimiter(',');
@@ -160,7 +168,7 @@ class SolidtimeImporter extends DefaultImporter
if ($project['client_id'] !== '') {
$clientId = $this->clientImportHelper->getKeyByExternalIdentifier($project['client_id']);
if ($clientId === null) {
throw new Exception('Client does not exist');
throw new ImportException('Project references a client that does not exist in the import');
}
}
@@ -183,8 +191,17 @@ class SolidtimeImporter extends DefaultImporter
foreach ($projectMembersReader as $projectMember) {
$userId = $this->userImportHelper->getKeyByExternalIdentifier($projectMember['user_id']);
if ($userId === null) {
throw new ImportException('Project member references a user that does not exist in the import');
}
$memberId = $this->memberImportHelper->getKeyByExternalIdentifier($projectMember['member_id']);
if ($memberId === null) {
throw new ImportException('Project member references a member that does not exist in the import');
}
$projectId = $this->projectImportHelper->getKeyByExternalIdentifier($projectMember['project_id']);
if ($projectId === null) {
throw new ImportException('Project member references a project that does not exist in the import');
}
$this->projectMemberImportHelper->getKey([
'project_id' => $projectId,
'member_id' => $memberId,
@@ -197,7 +214,7 @@ class SolidtimeImporter extends DefaultImporter
foreach ($tasksReader as $task) {
$projectId = $this->projectImportHelper->getKeyByExternalIdentifier($task['project_id']);
if ($projectId === null) {
throw new Exception('Project does not exist');
throw new ImportException('Task references a project that does not exist in the import');
}
$this->checkTaskNameLength($task['name']);
$this->taskImportHelper->getKey([
@@ -320,6 +337,9 @@ class SolidtimeImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -333,7 +353,7 @@ class SolidtimeImporter extends DefaultImporter
throw $exception;
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
} finally {
$temporaryDirectory?->delete();
$temporaryDirectoryZip?->delete();

View File

@@ -205,7 +205,7 @@ class TogglDataImporter extends DefaultImporter
throw $exception;
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
} finally {
$temporaryDirectory?->delete();
$temporaryDirectoryZip?->delete();

View File

@@ -48,6 +48,7 @@ class TogglTimeEntriesImporter extends DefaultImporter
public function importData(string $data, string $timezone): void
{
try {
$this->checkUtf8($data);
$reader = Reader::createFromString($data);
$reader->setHeaderOffset(0);
$reader->setDelimiter(',');
@@ -150,6 +151,9 @@ class TogglTimeEntriesImporter extends DefaultImporter
$member,
$this->organization
);
if ($this->skipIfAlreadyExists($timeEntry)) {
continue;
}
$timeEntry->save();
$this->timeEntriesCreated++;
}
@@ -162,10 +166,10 @@ class TogglTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace App\Service\Import;
use App\Models\TimeEntry;
use Illuminate\Support\Carbon;
use RuntimeException;
/**
* Detects imported time entries that already exist in the organization, so importing the same data twice does not
* duplicate time entries.
*
* Matches are counted: if the organization already contains a time entry N times, the first N equal time entries of
* an import are skipped and every further one is created. Re-importing the same data therefore creates nothing,
* while identical time entries within one import are still kept.
*
* Existing time entries are loaded lazily per member and UTC month of their start, so only the members and months an
* import touches are queried (backed by the (member_id, start) index). A member month is always loaded before the
* first time entry of that member month is created by the import, so time entries created by the import itself are
* never counted as existing.
*/
class TimeEntryDeduplicator
{
private const string DATE_FORMAT = 'Y-m-d H:i:s';
/**
* Remaining number of existing time entries per fingerprint, grouped by member and month ("<member_id>|Y-m")
*
* @var array<string, array<string, int>>
*/
private array $existingCounts = [];
public function __construct(private readonly string $organizationId) {}
/**
* Returns true if an equal time entry already exists in the organization and was not matched by an earlier
* time entry of this import. The match is consumed, so the caller should skip creating the time entry.
*/
public function claimExisting(TimeEntry $timeEntry): bool
{
// Note: The raw attributes contain the values exactly as they will be stored (timestamps in UTC as
// "Y-m-d H:i:s", the type as its enum value). Reading them directly is also much faster than going through
// the casts.
$attributes = $timeEntry->getAttributes();
$start = $attributes['start'] ?? null;
$end = $attributes['end'] ?? null;
if (! is_string($start) || ! is_string($end)) {
return false;
}
$memberId = $timeEntry->member_id;
$month = substr($start, 0, 7);
$bucket = $memberId.'|'.$month;
if (! isset($this->existingCounts[$bucket])) {
$this->existingCounts[$bucket] = $this->loadMemberMonth($memberId, $month);
}
$fingerprint = $this->getFingerprint(
$start,
$end,
$timeEntry->project_id,
$timeEntry->task_id,
$timeEntry->description,
(string) ($attributes['type'] ?? 'work')
);
$remaining = $this->existingCounts[$bucket][$fingerprint] ?? 0;
if ($remaining === 0) {
return false;
}
$this->existingCounts[$bucket][$fingerprint] = $remaining - 1;
return true;
}
/**
* @param string $month Month in the format "Y-m"
* @return array<string, int>
*/
private function loadMemberMonth(string $memberId, string $month): array
{
$monthStart = Carbon::createFromFormat('Y-m-d H:i:s', $month.'-01 00:00:00', 'UTC');
if ($monthStart === null) {
throw new RuntimeException('Invalid month');
}
$monthEnd = $monthStart->copy()->addMonth();
$counts = [];
// The query builder (without models) returns the values exactly as stored, so they can be compared with the
// raw attributes of the imported time entries. The cursor avoids holding all rows in memory at once.
$rows = TimeEntry::query()
->where('organization_id', '=', $this->organizationId)
->where('member_id', '=', $memberId)
->where('start', '>=', $monthStart->format(self::DATE_FORMAT))
->where('start', '<', $monthEnd->format(self::DATE_FORMAT))
->whereNotNull('end')
->toBase()
->select(['start', 'end', 'project_id', 'task_id', 'description', 'type'])
->cursor();
foreach ($rows as $row) {
/** @var object{start: string, end: string, project_id: string|null, task_id: string|null, description: string, type: string} $row */
$fingerprint = $this->getFingerprint(
$row->start,
$row->end,
$row->project_id,
$row->task_id,
$row->description,
$row->type
);
$counts[$fingerprint] = ($counts[$fingerprint] ?? 0) + 1;
}
return $counts;
}
private function getFingerprint(string $start, string $end, ?string $projectId, ?string $taskId, string $description, string $type): string
{
$json = json_encode([$start, $end, $projectId, $taskId, $description, $type], JSON_INVALID_UTF8_SUBSTITUTE);
if ($json === false) {
throw new RuntimeException('Failed to encode time entry fingerprint');
}
return md5($json);
}
}

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

@@ -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
@@ -31,4 +45,31 @@ 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
| 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,8 @@ 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),
'export_prune' => (bool) env('SCHEDULING_TASK_EXPORT_PRUNE', true),
'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,94 @@
<?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,
'ignore_limits' => false,
'report' => 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' => 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,68 @@
<?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();
// 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();
// Error message shown to the user
$table->text('error_message')->nullable();
// Technical error details (exception chain and stack trace), only visible in the admin panel
$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 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

@@ -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

@@ -107,7 +107,7 @@ services:
- sail
- reverse-proxy
playwright:
image: mcr.microsoft.com/playwright:v1.60.0-jammy
image: mcr.microsoft.com/playwright:v1.62.1-jammy
command: ['npx', 'playwright', 'test', '--ui-port=8080', '--ui-host=0.0.0.0']
working_dir: /src
extra_hosts:
@@ -173,7 +173,8 @@ services:
minio-create-bucket:
image: minio/mc:latest
depends_on:
- minio
minio:
condition: service_healthy
environment:
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}

View File

@@ -1,58 +1,399 @@
import { expect, test } from '../playwright/fixtures';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import type { Page } from '@playwright/test';
import fs from 'fs';
import path from 'path';
async function goToImportExport(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/import');
await expect(page.getByTestId('import_view')).toBeVisible({ timeout: 10000 });
}
test('test that import page loads with type dropdown and file upload', async ({ page }) => {
/**
* Uploads the file in the current wizard step and waits until the import was accepted.
* The import is processed in the background, the wizard polls it until it is finished.
*/
async function importFileInCurrentStep(page: Page, testFile: string) {
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/import') &&
response.request().method() === 'POST' &&
response.status() === 202,
{ timeout: 30000 }
),
page
.getByTestId('import_file_input')
.setInputFiles(path.resolve('resources/testfiles/' + testFile)),
]);
}
test('test that import page shows the import sources and the export', async ({ page }) => {
await goToImportExport(page);
await expect(page.getByTestId('import_view')).toBeVisible({ timeout: 10000 });
// Import section
await expect(page.getByRole('heading', { name: 'Import Data' })).toBeVisible();
await expect(page.locator('#importType')).toBeVisible();
for (const source of ['toggl', 'clockify', 'harvest', 'solidtime', 'generic']) {
await expect(page.getByTestId(`import_source_${source}`)).toBeVisible();
}
// Export section
await expect(page.getByRole('heading', { name: 'Export Data' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Export Organization Data' })).toBeVisible();
});
test('test that selecting an import type shows instructions', async ({ page }) => {
test('test that every step of the import wizard can be skipped and gone back to', async ({
page,
}) => {
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
const back = page.getByTestId('import_wizard_back');
const next = page.getByTestId('import_wizard_next');
// Select a Toggl import type
await page.getByLabel('Import Type').selectOption({ index: 1 });
// Preparation
await page.getByTestId('import_source_toggl').click();
await expect(wizard).toContainText('Before you export from');
await expect(wizard).toContainText('Sign in to Toggl as an Admin of the workspace');
await expect(next).toHaveText('Continue');
// Instructions should appear
await expect(page.getByText('Instructions:')).toBeVisible();
// Step 1: workspace data
await next.click();
await expect(wizard).toContainText('Step 2 of 3');
await expect(wizard).toContainText('Export the workspace data');
await expect(wizard).toContainText('Choose the ZIP file');
await expect(next).toHaveText('Skip');
// Skipping a required step without an import asks first, "Go back" stays on the step
const skipConfirm = page.getByTestId('import_wizard_skip_confirm');
await next.click();
await expect(page.getByText('Skip without importing?')).toBeVisible();
// Earlier steps have to be imported first, a later import does not update existing data
await expect(page.getByText('Import it before the next steps')).toBeVisible();
await page.getByRole('button', { name: 'Go back' }).click();
await expect(page.getByText('Skip without importing?')).toBeHidden();
await expect(wizard).toContainText('Step 2 of 3');
// Step 2: time entries
await next.click();
await skipConfirm.click();
await expect(wizard).toContainText('Step 3 of 3');
await expect(wizard).toContainText('Export the time entries');
await expect(wizard).toContainText('Choose the CSV file');
await expect(next).toHaveText('Skip and finish');
// Summary: nothing was imported, the last step can be imported later
await next.click();
await expect(page.getByText('You can come back to it later.')).toBeVisible();
await skipConfirm.click();
await expect(wizard).toContainText('Summary');
await expect(wizard.getByText('Not imported.')).toHaveCount(2);
await expect(next).toHaveText('Import from another tool');
// "Go to step" jumps back to a skipped step
await wizard.getByRole('button', { name: 'Go to step' }).first().click();
await expect(wizard).toContainText('Step 2 of 3');
// Back goes through all screens back to the source picker
await next.click();
await skipConfirm.click();
await expect(wizard).toContainText('Step 3 of 3');
await back.click();
await expect(wizard).toContainText('Step 2 of 3');
await back.click();
await expect(wizard).toContainText('Before you export from');
await back.click();
await expect(page.getByTestId('import_source_toggl')).toBeVisible();
await expect(back).not.toBeVisible();
// Change source switches to another tool
await page.getByTestId('import_source_harvest').click();
await next.click();
await expect(wizard).toContainText('Step 2 of 4');
await expect(wizard).toContainText('Export the clients');
await wizard.getByRole('button', { name: 'Change source' }).click();
await page.getByTestId('import_source_clockify').click();
await expect(wizard).toContainText('Clockify');
await expect(wizard).toContainText('Before you export from');
});
test('test that importing without selecting type shows error', async ({ page }) => {
test('test that importing a generic time entries CSV works through the wizard', async ({
page,
}) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
const next = page.getByTestId('import_wizard_next');
// Click Import Data without selecting a type
await page.getByRole('button', { name: 'Import Data' }).click();
await page.getByTestId('import_source_generic').click();
await next.click();
// Skip the projects
await expect(wizard).toContainText('Export the projects');
await next.click();
await page.getByTestId('import_wizard_skip_confirm').click();
await expect(wizard).toContainText('Export the time entries');
// Should show an error notification
await expect(page.getByText('Please select the import type')).toBeVisible();
await importFileInCurrentStep(page, 'generic_time_entries_import_test_1.csv');
// The CSV has 2 time entries, 2 projects, 1 client and 1 task
const stepImports = page.getByTestId('import_step_imports');
await expect(stepImports).toContainText(
'Created 2 time entries, 2 projects, 1 client, 1 task',
{ timeout: 30000 }
);
await expect(next).toHaveText('Finish');
// The import is listed in the summary and, once the source is closed, in the recent imports
await next.click();
await expect(wizard).toContainText('Summary');
await expect(wizard).toContainText('Created 2 time entries, 2 projects, 1 client, 1 task');
await expect(page.getByTestId('recent_imports')).toBeHidden();
await wizard.getByRole('button', { name: 'Change source' }).click();
await expect(page.getByTestId('recent_imports')).toContainText('Generic Time Entries');
await expect(page.getByTestId('recent_imports')).toContainText('Completed');
// The import created the projects, they are available in the app right away
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
await expect(page.getByTestId('projects_view')).toBeVisible({ timeout: 10000 });
await expect(page.getByTestId('project_table')).toContainText('Project without Client');
});
test('test that importing without selecting file shows error', async ({ page }) => {
test('test that a failed import is shown in the step and the step can be retried', async ({
page,
}) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const next = page.getByTestId('import_wizard_next');
// Select an import type first
await page.getByLabel('Import Type').selectOption({ index: 1 });
await page.getByTestId('import_source_generic').click();
await next.click();
await next.click();
await page.getByTestId('import_wizard_skip_confirm').click();
// Click Import Data without selecting a file
await page.getByRole('button', { name: 'Import Data' }).click();
// A Clockify export is not a valid generic CSV
await importFileInCurrentStep(page, 'clockify_projects_import_test_1.csv');
await expect(page.getByTestId('import_step_imports')).toContainText(
'Failed, nothing was imported.',
{ timeout: 30000 }
);
// Should show an error notification
// The step is not done, it can be skipped or another file can be imported
await expect(next).toHaveText('Skip and finish');
await expect(page.getByTestId('import_file_input')).toBeEnabled();
await importFileInCurrentStep(page, 'generic_time_entries_import_test_1.csv');
await expect(page.getByTestId('import_step_imports')).toContainText('Created 2 time entries', {
timeout: 30000,
});
await expect(next).toHaveText('Finish');
});
test('test that the wizard continues with the next step of a source after reloading', async ({
page,
}) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
const next = page.getByTestId('import_wizard_next');
await page.getByTestId('import_source_clockify').click();
await next.click();
await expect(wizard).toContainText('Export the projects');
await importFileInCurrentStep(page, 'clockify_projects_import_test_1.csv');
await expect(page.getByTestId('import_step_imports')).toContainText('Created', {
timeout: 30000,
});
await expect(next).toHaveText('Next');
// After a reload the source picker suggests the next step of Clockify
await goToImportExport(page);
const suggestion = page.getByTestId('import_continue_suggestion');
await expect(suggestion).toContainText('Continue with Clockify');
await expect(suggestion).toContainText('Time entries');
await suggestion.click();
await expect(wizard).toContainText('Step 3 of 3');
await expect(wizard).toContainText('Export the time entries');
// Opening the source again also skips the imported step
await wizard.getByRole('button', { name: 'Change source' }).click();
await page.getByTestId('import_source_clockify').click();
await expect(wizard).toContainText('Step 3 of 3');
});
test('test that a running import opens its step and does not block the navigation', async ({
page,
}) => {
// Imports finish within seconds in the tests, so the running import is simulated
const runningImport = {
id: '9d6b4cf1-6c11-4b6d-9f58-3e8e4f4b2a10',
type: 'clockify_time_entries',
source: 'web',
status: 'running',
report: null,
error_message: null,
user_id: null,
started_at: new Date().toISOString(),
finished_at: null,
created_at: new Date().toISOString(),
};
await page.route(/\/api\/v1\/organizations\/[^/]+\/imports(\?.*)?$/, async (route) => {
// Firefox accepts zstd, which the server uses but Playwright can not decode
const response = await route.fetch({
headers: { ...route.request().headers(), 'accept-encoding': 'identity' },
});
const json = await response.json();
json.data = [runningImport, ...json.data];
await route.fulfill({ response, json });
});
await page.route(`**/imports/${runningImport.id}`, (route) =>
route.fulfill({ json: { data: runningImport } })
);
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
// The step of the running import is opened, no other file can be added until it has finished
await expect(wizard).toContainText('Clockify');
await expect(wizard).toContainText('Step 3 of 3');
await expect(page.getByTestId('import_step_imports')).toContainText('Importing…');
await expect(page.getByTestId('import_file_input')).toBeDisabled();
await expect(wizard).toContainText('Another import is running');
// Navigation still works, the running import is shown in a banner on the other screens
await page.getByTestId('import_wizard_back').click();
await expect(wizard).toContainText('Step 2 of 3');
await expect(page.getByTestId('import_in_progress')).toBeVisible();
// Skipping the projects asks first and names what would be missing
await page.getByTestId('import_wizard_next').click();
await expect(
page.getByText('Please select the CSV or ZIP file that you want to import')
page.getByText('Billable rates, billable status and estimates of the projects')
).toBeVisible();
await page.getByTestId('import_wizard_skip_confirm').click();
await expect(wizard).toContainText('Step 3 of 3');
await page.getByTestId('import_wizard_next').click();
await expect(wizard).toContainText('Summary');
await wizard.getByRole('button', { name: 'Change source' }).click();
await page.getByTestId('import_source_toggl').click();
await expect(page.getByTestId('import_in_progress')).toBeVisible();
await page.getByTestId('import_in_progress').getByRole('button', { name: 'Show' }).click();
await expect(wizard).toContainText('Clockify');
await expect(wizard).toContainText('Step 3 of 3');
await expect(page.getByTestId('recent_imports')).toBeHidden();
await wizard.getByRole('button', { name: 'Change source' }).click();
await expect(page.getByTestId('recent_imports')).toContainText('In progress');
});
test('test that a step with one file per year takes several files', async ({ page }) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
const next = page.getByTestId('import_wizard_next');
const stepImports = page.getByTestId('import_step_imports');
await page.getByTestId('import_source_toggl').click();
await next.click();
await next.click();
await page.getByTestId('import_wizard_skip_confirm').click();
await expect(wizard).toContainText('Export the time entries');
await importFileInCurrentStep(page, 'toggl_time_entries_import_test_1.csv');
await expect(stepImports).toContainText('Created', { timeout: 30000 });
// The step asks for the next year's file instead of offering to import the same file again
await expect(wizard).toContainText('Add the next file');
await expect(next).toHaveText('Finish');
await importFileInCurrentStep(page, 'toggl_time_entries_import_test_2.csv');
await expect(stepImports.getByText(/^Created/)).toHaveCount(2, { timeout: 30000 });
// Both files are listed in the summary
await next.click();
await expect(wizard).toContainText('Summary');
await expect(wizard.getByText(/^Created/)).toHaveCount(2);
});
test('test that every Harvest step can be imported and the source reopens at the summary', async ({
page,
}) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
const next = page.getByTestId('import_wizard_next');
const stepImports = page.getByTestId('import_step_imports');
await page.getByTestId('import_source_harvest').click();
await expect(wizard).toContainText('Sign in to Harvest as an Administrator');
await next.click();
await expect(wizard).toContainText('Export the clients');
await importFileInCurrentStep(page, 'harvest_clients_import_test_1.csv');
await expect(stepImports).toContainText('Created', { timeout: 30000 });
await expect(next).toHaveText('Next');
await next.click();
await expect(wizard).toContainText('Export the projects');
await importFileInCurrentStep(page, 'harvest_projects_import_test_1.csv');
await expect(stepImports).toContainText('Created', { timeout: 30000 });
await expect(next).toHaveText('Next');
await next.click();
await expect(wizard).toContainText('Export the time entries');
await importFileInCurrentStep(page, 'harvest_time_entries_import_test_1.csv');
await expect(stepImports).toContainText('Created', { timeout: 30000 });
await expect(next).toHaveText('Finish');
await next.click();
await expect(wizard).toContainText('Summary');
await expect(wizard).toContainText('Import from Harvest done');
await expect(wizard.getByText('Not imported.')).toHaveCount(0);
// A source with every step imported opens at the summary
await wizard.getByRole('button', { name: 'Change source' }).click();
await page.getByTestId('import_source_harvest').click();
await expect(wizard).toContainText('Import from Harvest done');
});
test('test that a file can be dropped on the upload area', async ({ page }) => {
// The imports are processed in the background and polled
test.slow();
await goToImportExport(page);
const wizard = page.getByTestId('import_wizard');
await page.getByTestId('import_source_generic').click();
await page.getByTestId('import_wizard_next').click();
await expect(wizard).toContainText('Export the projects');
const fileName = 'generic_projects_import_test_1.csv';
const content = fs.readFileSync(path.resolve('resources/testfiles/' + fileName), 'utf8');
const dataTransfer = await page.evaluateHandle(
({ content, fileName }) => {
const transfer = new DataTransfer();
transfer.items.add(new File([content], fileName, { type: 'text/csv' }));
return transfer;
},
{ content, fileName }
);
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/import') &&
response.request().method() === 'POST' &&
response.status() === 202,
{ timeout: 30000 }
),
page
.locator('label', { has: page.getByTestId('import_file_input') })
.dispatchEvent('drop', { dataTransfer }),
]);
await expect(page.getByTestId('import_step_imports')).toContainText(
'Created 3 projects, 2 clients',
{
timeout: 30000,
}
);
});
test('test that export button triggers export and shows success modal', async ({ page }) => {
@@ -72,7 +413,7 @@ test('test that export button triggers export and shows success modal', async ({
(response) =>
response.url().includes('/export') &&
response.request().method() === 'POST' &&
response.status() === 200,
response.status() === 202,
{ timeout: 60000 }
),
page.getByRole('button', { name: 'Export Organization Data' }).click(),
@@ -80,59 +421,11 @@ test('test that export button triggers export and shows success modal', async ({
// Success modal should appear after export completes
await expect(page.getByText('The export was successful!')).toBeVisible();
});
await page.getByRole('button', { name: 'Close' }).click();
test('test that import type dropdown has multiple options', async ({ page }) => {
await goToImportExport(page);
// The dropdown should load with options from the API
await page.waitForResponse(
(response) =>
response.url().includes('/importers') &&
response.request().method() === 'GET' &&
response.status() === 200
);
// Verify the select has options besides the default placeholder
const options = page.getByLabel('Import Type').locator('option');
const count = await options.count();
// Should have at least the placeholder + some import types
expect(count).toBeGreaterThan(1);
});
test('test that importing a generic time entries CSV works', async ({ page }) => {
await goToImportExport(page);
await expect(page.getByTestId('import_view')).toBeVisible({ timeout: 10000 });
// Select "Generic Time Entries" import type
await page.getByLabel('Import Type').selectOption({ label: 'Generic Time Entries' });
await expect(page.getByText('Instructions:')).toBeVisible();
// Upload the test CSV file
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
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/import') &&
response.request().method() === 'POST' &&
response.status() === 200,
{ timeout: 30000 }
),
page.getByRole('button', { name: 'Import Data' }).click(),
]);
// Verify success modal with import results
await expect(page.getByRole('heading', { name: 'Import Result' })).toBeVisible();
await expect(page.getByText('The import was successful!')).toBeVisible();
// The CSV has 2 time entries, 1 client, 2 projects, 1 task
await expect(page.getByText('Time entries created:').locator('..')).toContainText('2');
await expect(page.getByText('Projects created:').locator('..')).toContainText('2');
await expect(page.getByText('Clients created:').locator('..')).toContainText('1');
await expect(page.getByText('Tasks created:').locator('..')).toContainText('1');
// 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();
});
// =============================================

View File

@@ -623,8 +623,25 @@ export async function createPlaceholderMemberViaImportApi(
},
}
);
expect(response.status()).toBe(200);
return await response.json();
expect(response.status()).toBe(202);
const body = await response.json();
const importId = body.data.id;
// Imports are processed in the background, wait until it is finished
await expect
.poll(
async () => {
const statusResponse = await ctx.request.get(
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/imports/${importId}`
);
expect(statusResponse.status()).toBe(200);
return (await statusResponse.json()).data.status;
},
{ timeout: 15000 }
)
.toBe('completed');
return body;
}
// ──────────────────────────────────────────────────

View File

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

View File

@@ -0,0 +1,29 @@
<script setup lang="ts">
import { GlobeAltIcon } from '@heroicons/vue/24/outline';
import ClockifySelect from './ClockifySelect.vue';
</script>
<template>
<div
role="img"
aria-label="Clockify preferences with the language English, the date format MM/DD/YYYY and the time format 12-hour"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Language</div>
<ClockifySelect value="English" class="mt-1.5 w-64 max-w-full">
<template #icon>
<GlobeAltIcon class="h-3.5 w-3.5 flex-none text-text-secondary" />
</template>
</ClockifySelect>
<div class="my-2.5 border-t border-card-border"></div>
<div class="grid grid-cols-2 gap-3">
<div class="min-w-0">
<div class="text-[11px] text-text-secondary">Date format</div>
<ClockifySelect value="MM/DD/YYYY" class="mt-1" />
</div>
<div class="min-w-0">
<div class="text-[11px] text-text-secondary">Time format</div>
<ClockifySelect value="12-hour" class="mt-1" />
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,67 @@
<script setup lang="ts">
// Columns of the "Project export settings" in Clockify, in the order of the two columns there
const columns = [
'Name',
'Client',
'Status',
'Visibility',
'Tasks',
'Tracked (h)',
'Estimated (h)',
'Remaining (h)',
'Overage (h)',
'Progress (%)',
'Project members',
'Project manager',
'Note',
];
</script>
<template>
<div
role="img"
aria-label="Project export settings in Clockify with all columns selected"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Project export settings</div>
<div class="my-2 border-t border-card-border"></div>
<div class="flex items-center gap-1.5 text-xs text-text-primary">
<span
class="flex h-3.5 w-3.5 flex-none items-center justify-center rounded-[2px] bg-[#03A9F4]">
<svg viewBox="0 0 16 16" fill="none" class="h-3.5 w-3.5 text-white">
<path
d="M4.2 8.4 6.8 11l5-6"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round" />
</svg>
</span>
Select all
</div>
<div class="mt-1.5 grid grid-flow-col grid-rows-7 gap-x-4 gap-y-1">
<div
v-for="column in columns"
:key="column"
class="flex items-center gap-1.5 text-xs text-text-primary">
<span
class="flex h-3.5 w-3.5 flex-none items-center justify-center rounded-[2px] bg-[#03A9F4]">
<svg viewBox="0 0 16 16" fill="none" class="h-3.5 w-3.5 text-white">
<path
d="M4.2 8.4 6.8 11l5-6"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round" />
</svg>
</span>
<span class="truncate">{{ column }}</span>
</div>
</div>
<div class="mt-3 flex justify-end">
<div
class="flex h-7 items-center rounded-sm bg-[#03A9F4] px-4 text-xs font-medium uppercase text-white">
Save
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,60 @@
<script setup lang="ts">
// Projects table in Clockify with the Export menu open
const columns = ['Name', 'Client', 'Tracked'];
const menuItems = ['Save as CSV', 'Save as Excel', 'Customize...'];
</script>
<template>
<div
role="img"
aria-label="Projects table in Clockify with the Export menu at its top right opened"
class="relative w-full max-w-md select-none">
<div class="overflow-hidden border border-card-border bg-card-background">
<div
class="flex h-8 items-center justify-between border-b border-card-border bg-card-background-active">
<span class="px-3 text-[11px] text-text-secondary">Projects</span>
<span
class="flex h-full items-center gap-1 border-l border-card-border px-3 text-[11px] text-text-primary">
Export
<svg viewBox="0 0 8 5" class="h-1 w-1.5 fill-text-secondary">
<path d="M0 0h8L4 5z" />
</svg>
</span>
</div>
<div
class="flex h-7 items-center gap-3 border-b border-card-border px-3 text-[10px] uppercase tracking-wider text-text-secondary">
<span class="h-3 w-3 flex-none rounded-[2px] border border-input-border"></span>
<span
v-for="column in columns"
:key="column"
class="flex flex-1 items-center gap-1">
{{ column }}
<svg viewBox="0 0 8 11" class="h-2 w-1.5 fill-text-tertiary">
<path d="M0 4.5h8L4 0zM0 6.5h8L4 11z" />
</svg>
</span>
</div>
<div class="flex h-8 items-center gap-3 px-3 text-xs text-text-primary">
<span class="h-3 w-3 flex-none rounded-[2px] border border-input-border"></span>
<span class="flex flex-1 items-center gap-1.5">
<span class="h-1 w-1 rounded-full bg-[#A5489B]"></span>
Website
</span>
<span class="flex-1 text-text-secondary">–</span>
<span class="flex-1 text-text-secondary">–</span>
</div>
</div>
<div
class="absolute right-px top-8 w-28 bg-card-background py-0.5 shadow-lg ring-1 ring-card-border">
<div
v-for="item in menuItems"
:key="item"
:class="[
'px-3 py-1 text-xs text-text-primary',
item === 'Customize...' && 'bg-card-background-active',
]">
{{ item }}
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,17 @@
<script setup lang="ts">
// Select of the Clockify preferences with its triangle caret, only used in the previews
defineProps<{
value: string;
}>();
</script>
<template>
<div
class="flex h-7 min-w-0 items-center gap-1.5 rounded border border-input-border bg-input-background px-2 text-xs text-text-primary">
<slot name="icon" />
<span class="flex-1 truncate">{{ value }}</span>
<svg viewBox="0 0 10 5" class="h-1.5 w-2.5 flex-none fill-text-secondary">
<path d="M0 0h10L5 5z" />
</svg>
</div>
</template>

View File

@@ -0,0 +1,22 @@
<script setup lang="ts">
import { computed } from 'vue';
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
import ClockifySelect from './ClockifySelect.vue';
import { timezoneOffset } from './timezoneOffset';
const timezone = getUserTimezone();
// Clockify lists timezones as "(UTC +01:00) Europe/Vienna"
const label = computed(() => `(UTC ${timezoneOffset(timezone)}) ${timezone}`);
</script>
<template>
<div
role="img"
:aria-label="`Time zone in the Clockify preferences set to ${label}`"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Time settings</div>
<div class="mt-1.5 text-[11px] text-text-secondary">Time zone</div>
<ClockifySelect :value="label" class="mt-1 w-64 max-w-full" />
</div>
</template>

View File

@@ -0,0 +1,58 @@
<script setup lang="ts">
// Clients page in Harvest with the Import/Export menu open
const menuGroups = [
['Import clients from CSV', 'Import contacts from CSV'],
['Export clients', 'Export contacts'],
];
</script>
<template>
<div
role="img"
aria-label="Clients page in Harvest with the Import/Export menu at the top right opened"
class="relative w-full max-w-md select-none rounded-lg border border-card-border bg-card-background">
<div class="flex items-center gap-1.5 border-b border-card-border px-3 py-2.5">
<span class="flex-1 text-sm font-medium text-text-primary">Clients</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md bg-[#188433] px-2 text-[11px] font-medium text-white">
+ New client
</span>
<span
class="flex h-6 items-center whitespace-nowrap gap-1 rounded-md border border-card-border px-2 text-[11px] text-text-primary">
Import/Export
<svg viewBox="0 0 10 6" class="h-1.5 w-2.5 stroke-text-secondary" fill="none">
<path d="M1 1l4 4 4-4" stroke-width="1.5" />
</svg>
</span>
</div>
<div class="space-y-1.5 px-3 py-3">
<div
v-for="client in ['Acme Inc.', 'Example Client', 'Globex']"
:key="client"
class="flex items-center gap-2 rounded-md border border-card-border px-2 py-1.5">
<span
class="rounded border border-card-border px-1.5 text-[10px] text-text-secondary"
>Edit</span
>
<span class="text-xs font-medium text-text-primary">{{ client }}</span>
</div>
</div>
<div
class="absolute right-2 top-10 w-44 rounded-md border border-card-border bg-card-background py-1 shadow-lg">
<template v-for="(group, index) in menuGroups" :key="index">
<div v-if="index > 0" class="my-1 border-t border-card-border"></div>
<div
v-for="item in group"
:key="item"
:class="[
'whitespace-nowrap px-3 py-1 text-[11px]',
item === 'Export clients'
? 'bg-text-primary text-card-background'
: 'text-text-primary',
]">
{{ item }}
</div>
</template>
</div>
</div>
</template>

View File

@@ -0,0 +1,57 @@
<script setup lang="ts">
// "Export projects" dialog of Harvest with the active projects and CSV selected
const selection = ['Active', 'Budgeted', 'Archived'];
const formats = ['CSV', 'Excel'];
const optionClass = (selected: boolean) => [
'flex h-6 flex-1 items-center justify-center rounded-md border text-[11px]',
selected
? 'border-[#FA5D00] bg-[#FA5D00]/15 text-text-primary'
: 'border-card-border text-text-primary',
];
</script>
<template>
<div
role="img"
aria-label="Export projects dialog in Harvest with the active projects and the CSV format selected"
class="w-full max-w-md select-none overflow-hidden rounded-lg border border-card-border bg-card-background">
<div
class="border-b border-card-border bg-card-background-active py-1.5 text-center text-xs font-medium text-text-primary">
Export projects
</div>
<div class="space-y-2.5 px-4 py-3">
<div class="space-y-1">
<div class="text-[11px] font-medium text-text-primary">
Which projects would you like to export?
</div>
<div class="flex gap-1.5">
<span
v-for="item in selection"
:key="item"
:class="optionClass(item === 'Active')">
{{ item }}
</span>
</div>
</div>
<div class="space-y-1">
<div class="text-[11px] font-medium text-text-primary">Choose a format:</div>
<div class="flex gap-1.5">
<span v-for="item in formats" :key="item" :class="optionClass(item === 'CSV')">
{{ item }}
</span>
</div>
</div>
<div class="flex gap-1.5">
<span
class="flex h-6 items-center whitespace-nowrap rounded-md bg-[#188433] px-2.5 text-[11px] font-medium text-white">
Export projects
</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md border border-card-border px-2.5 text-[11px] text-text-primary">
Cancel
</span>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,55 @@
<script setup lang="ts">
// Projects page in Harvest with the Export button at the top right
const projects = [
{ client: 'Acme Inc.', name: 'Website' },
{ client: 'Example Client', name: 'Mobile App' },
];
</script>
<template>
<div
role="img"
aria-label="Projects page in Harvest with the Export button at the top right"
class="w-full max-w-md select-none rounded-lg border border-card-border bg-card-background">
<div class="flex items-center gap-1.5 border-b border-card-border px-3 py-2.5">
<span class="flex-1 text-sm font-medium text-text-primary">Projects</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md bg-[#188433] px-2 text-[11px] font-medium text-white">
+ New project
</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md border border-card-border px-2 text-[11px] text-text-primary">
Import
</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md border border-text-secondary px-2 text-[11px] font-medium text-text-primary">
Export
</span>
</div>
<div class="px-3 py-3">
<div class="overflow-hidden rounded-md border border-card-border">
<div
class="flex items-center gap-2 border-b border-card-border bg-card-background-active px-2 py-1 text-[10px] text-text-secondary">
<span class="h-2.5 w-2.5 rounded-[2px] border border-text-quaternary"></span>
<span class="flex-1">Client</span>
<span class="w-12 text-right">Spent</span>
</div>
<template v-for="project in projects" :key="project.name">
<div
class="border-b border-card-border bg-card-background-active px-2 py-0.5 pl-6 text-[10px] text-text-secondary underline">
{{ project.client }}
</div>
<div
class="flex items-center gap-2 border-b border-card-border px-2 py-1.5 last:border-b-0">
<span
class="h-2.5 w-2.5 rounded-[2px] border border-text-quaternary"></span>
<span class="flex-1 text-xs font-medium text-text-primary">
{{ project.name }}
</span>
<span class="w-12 text-right text-xs text-text-primary">0,00</span>
</div>
</template>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,46 @@
<script setup lang="ts">
// Import/Export settings of Harvest with the "Export all time" button
const navigation = ['Billing', 'Company preferences', 'Modules', 'Import/Export', 'Bulk actions'];
</script>
<template>
<div
role="img"
aria-label="Import/Export settings in Harvest with the Export all time button"
class="w-full max-w-md select-none overflow-hidden rounded-lg border border-card-border bg-card-background">
<div class="border-b border-card-border px-3 py-2 text-sm font-medium text-text-primary">
Settings
</div>
<div class="flex">
<div class="w-32 flex-none space-y-0.5 border-r border-card-border p-2">
<div
v-for="item in navigation"
:key="item"
:class="[
'whitespace-nowrap rounded-md px-2 py-1 text-[11px]',
item === 'Import/Export'
? 'bg-[#FA5D00]/10 font-medium text-text-primary'
: 'text-text-secondary',
]">
{{ item }}
</div>
</div>
<div class="min-w-0 flex-1 space-y-1.5 px-3 py-3">
<div class="text-sm font-semibold text-text-primary">Export data</div>
<div class="text-[10px] leading-snug text-text-secondary">
Export all time and expense data from your Harvest account.
</div>
<div class="flex flex-wrap gap-1.5 pt-1">
<span
class="flex h-6 items-center whitespace-nowrap rounded-md border border-text-secondary px-2 text-[11px] font-medium text-text-primary">
Export all time
</span>
<span
class="flex h-6 items-center whitespace-nowrap rounded-md border border-card-border px-2 text-[11px] text-text-primary">
Export all expenses
</span>
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,36 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { ImportListItem } from './importSources';
import ImportLinkButton from './ImportLinkButton.vue';
import ImportText from './ImportText.vue';
const props = defineProps<{
items: (string | ImportListItem)[];
}>();
const normalizedItems = computed<ImportListItem[]>(() =>
props.items.map((item) => (typeof item === 'string' ? { text: item } : item))
);
// Lists with previews get more room between the items
const hasPreviews = computed(() => normalizedItems.value.some((item) => item.preview));
</script>
<template>
<ol :class="hasPreviews ? 'space-y-5' : 'space-y-2'">
<li v-for="(item, index) in normalizedItems" :key="item.text" class="flex gap-2.5">
<span
class="flex-none h-5 w-5 rounded-full border border-card-border bg-card-background-active text-xs font-semibold text-text-primary flex items-center justify-center"
>{{ index + 1 }}</span
>
<div class="min-w-0 flex-1 space-y-2">
<p class="max-w-md text-text-primary">
<ImportText :text="item.text" />
</p>
<div v-if="item.preview" class="max-w-md">
<component :is="item.preview" />
</div>
<ImportLinkButton v-if="item.link" v-bind="item.link" />
</div>
</li>
</ol>
</template>

View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
import { ArrowTopRightOnSquareIcon } from '@heroicons/vue/16/solid';
import { Button } from '@/packages/ui/src/Buttons';
defineProps<{
href: string;
label: string;
}>();
</script>
<template>
<Button as="a" variant="ghost" size="sm" :href="href" target="_blank" rel="noopener">
{{ label }}
<ArrowTopRightOnSquareIcon class="text-text-tertiary" />
</Button>
</template>

View File

@@ -0,0 +1,85 @@
<script setup lang="ts">
import { DocumentTextIcon, PuzzlePieceIcon } from '@heroicons/vue/24/outline';
import type { ImportSourceId } from './importSources';
withDefaults(
defineProps<{
source: ImportSourceId;
size?: 'small' | 'base';
}>(),
{
size: 'base',
}
);
</script>
<template>
<span
aria-hidden="true"
:class="[
'flex-none inline-flex items-center justify-center overflow-hidden',
size === 'small' ? 'h-6 w-6 rounded-md' : 'h-9 w-9 rounded-lg',
]">
<!-- Toggl Track mark (Simple Icons, CC0) -->
<svg
v-if="source === 'toggl'"
viewBox="0 0 40 40"
class="h-full w-full"
xmlns="http://www.w3.org/2000/svg">
<rect width="40" height="40" fill="#2C1338" />
<path
transform="translate(8 8)"
fill="#E57CD8"
d="M12 0a12 12 0 1 0 0 24 12 12 0 0 0 0-24zm-.883 4.322h1.766v8.757h-1.766zm-.74 2.053v1.789a4.448 4.448 0 1 0 3.247 0V6.375a6.146 6.146 0 1 1-5.669 10.552 6.145 6.145 0 0 1 2.421-10.552z" />
</svg>
<!-- Clockify mark (Simple Icons, CC0) -->
<svg
v-else-if="source === 'clockify'"
viewBox="0 0 40 40"
class="h-full w-full"
xmlns="http://www.w3.org/2000/svg">
<rect width="40" height="40" fill="#FFFFFF" />
<path
transform="translate(8 8)"
fill="#03A9F4"
d="M13.3512 20.4035c1.1108 0 2.169-.2217 3.139-.6157l2.6913 2.6944C17.4555 23.4458 15.4688 24 13.3512 24 6.729 24 1.3594 18.627 1.3594 12.0006 1.3594 5.3729 6.7289 0 13.3512 0c2.0964 0 4.0652.5406 5.7789 1.4865L16.4834 4.136c-.9687-.3918-2.0236-.6134-3.1322-.6134-4.6379 0-8.3976 3.779-8.3976 8.441 0 4.6609 3.7597 8.4399 8.3976 8.4399zm2.176-12.1544l5.5104-5.5139 1.5773 1.5772-5.5104 5.514zm-2.2328 5.6348c-1.0784 0-1.952-.8775-1.952-1.961 0-1.0825.8736-1.9611 1.952-1.9611 1.0784 0 1.952.8786 1.952 1.961 0 1.0836-.8736 1.9611-1.952 1.9611zm9.3462 5.6953l-1.5772 1.5783-5.5105-5.514 1.5774-1.5783z" />
</svg>
<!-- Harvest mark -->
<svg
v-else-if="source === 'harvest'"
viewBox="0 0 70 70"
class="h-full w-full"
xmlns="http://www.w3.org/2000/svg">
<rect width="70" height="70" fill="#FA5D00" />
<path
fill="#FFFFFF"
d="M55.6916 55.7791C55.6916 57.2818 54.4734 58.5 52.9707 58.5H49.353C47.8503 58.5 46.6321 57.2818 46.6321 55.7791V14.2209C46.6321 12.7182 47.8503 11.5 49.353 11.5H52.9707C54.4734 11.5 55.6916 12.7182 55.6916 14.2209L55.6916 55.7791Z" />
<path
fill="#FFFFFF"
d="M39.5008 27.4713C39.5008 29.4833 38.122 31.2332 36.1658 31.7039L30.4542 33.0781V17.8389C30.4542 16.3362 31.6724 15.118 33.1751 15.118H36.78C38.2827 15.118 39.5008 16.3362 39.5008 17.8389V27.4713Z" />
<path
fill="#FFFFFF"
d="M23.3553 47.3555C23.3552 48.8581 22.1371 50.0761 20.6345 50.0761H17.0296C15.5268 50.0761 14.3086 48.8578 14.3087 47.355L14.3108 25.2504C14.311 23.7478 15.5291 22.5298 17.0317 22.5298H20.6366C22.1394 22.5298 23.3576 23.7481 23.3574 25.2509L23.3553 47.3555Z" />
<path
fill="#FFFFFF"
d="M39.5037 53.165C39.5041 54.668 38.2859 55.8867 36.7829 55.8867H33.1779C31.6755 55.8867 30.4575 54.669 30.457 53.1667L30.4537 42.7934C30.4531 40.7809 31.832 39.0302 33.7887 38.5594L39.4993 37.1854L39.5037 53.165Z" />
</svg>
<!-- solidtime mark, light on dark in both themes like the other brand marks -->
<span
v-else-if="source === 'solidtime'"
class="h-full w-full bg-[oklch(0.25_0_0)] text-[oklch(0.97_0_0)] flex items-center justify-center">
<svg viewBox="0 0 700 700" class="h-3/4 w-3/4" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(0 700) scale(0.1 -0.1)" fill="currentColor">
<path
d="M3578 5835c-1-1-61-5-133-9-135-7-196-12-255-22-19-3-51-8-70-10-19-3-51-9-70-14-19-5-53-12-74-16-47-7-203-59-296-99-444-188-719-448-855-811-25-67-63-233-70-309-6-56-6-315-1-345 2-14 7-50 11-80 22-176 93-359 192-498 213-299 588-491 1338-687 215-56 395-129 462-188 41-36 73-95 75-140 5-87-32-146-117-186-114-53-385-60-627-15-97 17-262 72-367 121-117 54-362 216-389 257-4 6-21 24-38 39l-32 29-225-229c-124-125-318-322-431-438l-205-210 57-55c292-278 615-463 1078-618 111-38 254-78 314-88 14-3 41-9 60-14 34-8 137-26 210-35 180-24 617-24 805 0 712 92 1222 453 1390 981 66 209 78 509 30 785-11 64-51 172-97 264-137 275-327 450-685 629-145 73-485 191-638 222-93 18-347 101-433 140-135 62-187 122-185 217 1 80 73 152 180 183 59 17 295 24 373 10 132-22 331-86 435-138 73-38 202-133 286-212l73-68 434 436c389 391 433 438 421 453-38 47-57 69-85 97-252 253-524 409-929 534-254 79-441 113-710 127-60 4-131 8-157 10-25 2-48 2-50 0z" />
</g>
</svg>
</span>
<span
v-else
class="h-full w-full bg-card-background-active text-text-secondary flex items-center justify-center">
<DocumentTextIcon v-if="source === 'generic'" class="h-1/2 w-1/2" />
<PuzzlePieceIcon v-else class="h-1/2 w-1/2" />
</span>
</span>
</template>

View File

@@ -0,0 +1,13 @@
<script setup lang="ts">
// Text with parts wrapped in ** shown bold
defineProps<{
text: string;
}>();
</script>
<template>
<template v-for="(part, index) in text.split('**')" :key="index"
><strong v-if="index % 2 === 1" class="font-semibold">{{ part }}</strong
><template v-else>{{ part }}</template></template
>
</template>

View File

@@ -0,0 +1,684 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import {
ArrowUpTrayIcon,
CheckCircleIcon,
ExclamationTriangleIcon,
} from '@heroicons/vue/24/outline';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { formatDateTimeLocalized } from '@/packages/ui/src/utils/time';
import { useOrganizationStore } from '@/utils/useOrganization';
import type { Import, ImportReport } from '@/packages/api/src';
import ImportChecklist from './ImportChecklist.vue';
import ImportWizardHeader from './ImportWizardHeader.vue';
import ImportSourceLogo from './ImportSourceLogo.vue';
import {
buildImportSources,
findSourceStepForImporter,
type ImportSource,
type ImportSourceId,
type ImportSourceStep,
} from './importSources';
import { isActiveImport, type ImportsState } from './useImports';
const props = defineProps<{
state: ImportsState;
}>();
const { organization } = storeToRefs(useOrganizationStore());
// Screens of a source: PREPARE, one screen per step (0..n-1) and the summary (n)
const PREPARE = -1;
// The open source, null while the source picker is shown
const sourceId = defineModel<ImportSourceId | null>('source', { default: null });
const screen = ref(PREPARE);
const dragging = ref(false);
const sources = computed(() => buildImportSources(props.state.importers.value));
const source = computed<ImportSource | null>(
() => sources.value.find((item) => item.id === sourceId.value) ?? null
);
const steps = computed(() => source.value?.steps ?? []);
const isSummary = computed(() => source.value !== null && screen.value >= steps.value.length);
const currentStep = computed<ImportSourceStep | null>(() =>
screen.value >= 0 && screen.value < steps.value.length ? steps.value[screen.value]! : null
);
function importsOfStep(step: ImportSourceStep): Import[] {
return props.state.imports.value.filter((item) => item.type === step.importer);
}
function isStepDone(step: ImportSourceStep): boolean {
return importsOfStep(step).some((item) => item.status === 'completed');
}
/**
* The screen a source opens with: the step of a running import, otherwise the first step after the last
* imported step (the summary if all steps are imported), otherwise the preparation screen.
*/
function initialScreen(item: ImportSource): number {
const active = props.state.activeImport.value;
if (active !== null) {
const activeIndex = item.steps.findIndex((step) => step.importer === active.type);
if (activeIndex !== -1) {
return activeIndex;
}
}
let lastDone = -1;
item.steps.forEach((step, index) => {
if (isStepDone(step)) {
lastDone = index;
}
});
if (lastDone !== -1) {
return lastDone + 1;
}
return item.prerequisites.length > 0 ? PREPARE : 0;
}
function openSource(item: ImportSource, atScreen?: number) {
sourceId.value = item.id;
screen.value = atScreen ?? initialScreen(item);
}
function changeSource() {
sourceId.value = null;
}
// Step detection: open the step of a running import when the page is opened
watch(
() => props.state.loaded.value,
(loaded) => {
const active = props.state.activeImport.value;
if (!loaded || active === null || sourceId.value !== null) {
return;
}
const location = findSourceStepForImporter(sources.value, active.type);
if (location !== null) {
openSource(location.source, location.stepIndex);
}
},
{ immediate: true }
);
/**
* Suggests to continue a source whose last import is not the last step, for example the Toggl time entries after
* the Toggl workspace data was imported.
*/
const continueSuggestion = computed(() => {
const latest = props.state.imports.value[0];
if (latest === undefined || latest.status !== 'completed') {
return null;
}
const location = findSourceStepForImporter(sources.value, latest.type);
if (location === null) {
return null;
}
const nextIndex = location.source.steps.findIndex(
(step, index) => index > location.stepIndex && !isStepDone(step)
);
if (nextIndex === -1) {
return null;
}
return {
source: location.source,
stepIndex: nextIndex,
step: location.source.steps[nextIndex]!,
};
});
const activeImport = computed(() => props.state.activeImport.value);
const activeLocation = computed(() =>
activeImport.value ? findSourceStepForImporter(sources.value, activeImport.value.type) : null
);
const activeIsOnScreen = computed(
() =>
activeLocation.value !== null &&
activeLocation.value.source.id === sourceId.value &&
activeLocation.value.stepIndex === screen.value
);
const uploadBlocked = computed(() => activeImport.value !== null || props.state.uploading.value);
const progressSegments = computed(() =>
steps.value.map((step, index) => ({
key: step.importer,
title: step.title,
done: isStepDone(step),
current: index === screen.value,
}))
);
function stepLabel(step: ImportSourceStep): string {
return step.format === 'File' ? step.title : `${step.title} (${step.format})`;
}
function formatDate(value: string | null): string {
if (value === null) {
return '';
}
return formatDateTimeLocalized(
value,
organization.value?.date_format,
organization.value?.time_format
);
}
function formatReport(report: ImportReport | null): string {
if (report === null) {
return 'Imported';
}
const parts: [number, string, string][] = [
[report.time_entries.created, 'time entry', 'time entries'],
[report.projects.created, 'project', 'projects'],
[report.clients.created, 'client', 'clients'],
[report.tasks.created, 'task', 'tasks'],
[report.tags.created, 'tag', 'tags'],
[report.users.created, 'member', 'members'],
];
const created = parts
.filter(([count]) => count > 0)
.map(
([count, singular, plural]) =>
`${count.toLocaleString()} ${count === 1 ? singular : plural}`
);
const skipped = report.time_entries.skipped;
const summary = created.length > 0 ? `Created ${created.join(', ')}` : 'Nothing new to create';
if (skipped > 0) {
return `${summary}. Skipped ${skipped.toLocaleString()} existing ${skipped === 1 ? 'time entry' : 'time entries'}`;
}
return summary;
}
function importDescription(item: Import): string {
switch (item.status) {
case 'pending':
return 'Waiting to start…';
case 'running':
return 'Importing… You can leave this page, the import continues in the background.';
case 'completed':
return formatReport(item.report);
case 'failed':
return `Failed, nothing was imported. ${item.error_message ?? ''}`.trim();
}
return item.status;
}
// Imports that existed when the page was opened. A step only lists imports of this visit and the ones that ran
// during it, so an import that was already running keeps showing its result. Earlier ones are listed in the
// recent imports.
const importIdsBeforeVisit = ref<Set<string> | null>(null);
const importIdsActiveDuringVisit = ref(new Set<string>());
watch(
() => props.state.loaded.value,
(loaded) => {
if (loaded && importIdsBeforeVisit.value === null) {
importIdsBeforeVisit.value = new Set(props.state.imports.value.map((item) => item.id));
}
},
{ immediate: true }
);
watch(
() => props.state.activeImport.value?.id,
(id) => {
if (id !== undefined) {
importIdsActiveDuringVisit.value.add(id);
}
},
{ immediate: true }
);
const currentStepImports = computed(() =>
currentStep.value
? importsOfStep(currentStep.value)
.filter(
(item) =>
isActive(item) ||
importIdsActiveDuringVisit.value.has(item.id) ||
importIdsBeforeVisit.value?.has(item.id) === false
)
.slice(0, 5)
: []
);
const currentStepDone = computed(() => (currentStep.value ? isStepDone(currentStep.value) : false));
const acceptedFiles = computed(() => {
switch (currentStep.value?.format) {
case 'ZIP':
return '.zip,application/zip';
case 'CSV':
return '.csv,text/csv';
}
return undefined;
});
const uploadTitle = computed(() => {
if (props.state.uploading.value) {
return 'Uploading…';
}
if (activeImport.value !== null) {
return 'Another import is running';
}
const step = currentStep.value;
if (step === null) {
return '';
}
if (currentStepDone.value) {
return step.repeat ? 'Add the next file' : 'Import another file';
}
return step.format === 'File' ? 'Choose the file' : `Choose the ${step.format} file`;
});
const uploadHint = computed(() => {
if (activeImport.value !== null && !props.state.uploading.value) {
return activeIsOnScreen.value
? 'The next file can be added when this import has finished.'
: 'Files can be added when it has finished. You can still go through the other steps.';
}
return 'Drop it here or click to choose. It is imported right away.';
});
async function importFile(file: File | undefined) {
const step = currentStep.value;
if (file === undefined || step === null || uploadBlocked.value) {
return;
}
await props.state.startImport(step.importer, file);
}
function onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
void importFile(input.files?.[0]);
input.value = '';
}
function onDragLeave(event: DragEvent) {
const currentTarget = event.currentTarget as HTMLElement | null;
if (currentTarget && currentTarget.contains(event.relatedTarget as Node | null)) {
return;
}
dragging.value = false;
}
function onDrop(event: DragEvent) {
dragging.value = false;
void importFile(event.dataTransfer?.files?.[0]);
}
function goBack() {
const firstScreen = source.value?.prerequisites.length ? PREPARE : 0;
if (screen.value <= firstScreen) {
changeSource();
return;
}
screen.value = Math.min(screen.value, steps.value.length) - 1;
}
// Skipping a step without importing a file is confirmed first, since the data of that step will be missing
const showSkipConfirmation = ref(false);
const skipNeedsConfirmation = computed(() => {
const step = currentStep.value;
if (step === null || currentStepDone.value) {
return false;
}
return !importsOfStep(step).some((item) => isActive(item));
});
function goNext() {
if (isSummary.value) {
changeSource();
return;
}
if (skipNeedsConfirmation.value) {
showSkipConfirmation.value = true;
return;
}
screen.value += 1;
}
function confirmSkip() {
showSkipConfirmation.value = false;
screen.value += 1;
}
const isLastStep = computed(() => screen.value === steps.value.length - 1);
const nextLabel = computed(() => {
if (isSummary.value) {
return 'Import from another tool';
}
if (screen.value === PREPARE) {
return 'Continue';
}
if (currentStepDone.value) {
return isLastStep.value ? 'Finish' : 'Next';
}
return isLastStep.value ? 'Skip and finish' : 'Skip';
});
const summaryRows = computed(() =>
steps.value.map((step) => ({
step,
imports: importsOfStep(step).filter((item) => item.status === 'completed'),
}))
);
const summaryHasImports = computed(() => summaryRows.value.some((row) => row.imports.length > 0));
const summaryCreatedMembers = computed(() =>
summaryRows.value.some((row) =>
row.imports.some((item) => (item.report?.users.created ?? 0) > 0)
)
);
function showActiveImport() {
if (activeLocation.value !== null) {
openSource(activeLocation.value.source, activeLocation.value.stepIndex);
}
}
function isActive(item: Import): boolean {
return isActiveImport(item);
}
</script>
<template>
<div class="flex flex-col" data-testid="import_wizard">
<!-- Header of the selected source -->
<ImportWizardHeader
v-if="source"
:source="source"
:segments="progressSegments"
:screen="screen"
@change-source="changeSource" />
<!-- Running import that belongs to another step or source -->
<div
v-if="activeImport && !activeIsOnScreen"
data-testid="import_in_progress"
class="px-4 sm:px-5 py-2.5 text-sm flex items-center gap-3 border-b border-card-background-separator">
<LoadingSpinner class="h-4 w-4 m-0" />
<p class="flex-1 text-text-secondary">
<template v-if="activeLocation">
{{ activeLocation.source.name }}
{{ activeLocation.source.steps[activeLocation.stepIndex]?.title.toLowerCase() }}
{{
activeImport.status === 'running'
? 'are being imported'
: 'are waiting to be imported'
}}.
</template>
<template v-else>An import is running.</template>
</p>
<button
v-if="activeLocation"
type="button"
class="text-sm text-text-primary hover:underline"
@click="showActiveImport">
Show
</button>
</div>
<div class="px-4 sm:px-5 py-5 space-y-4 text-sm">
<div
v-if="state.loadFailed.value"
data-testid="import_load_failed"
class="flex flex-col items-center gap-3 py-10 text-center">
<p class="text-text-secondary">The imports could not be loaded.</p>
<SecondaryButton @click="state.load()">Try again</SecondaryButton>
</div>
<div v-else-if="!state.loaded.value" class="flex justify-center py-10">
<LoadingSpinner />
</div>
<!-- Source picker -->
<template v-else-if="!source">
<div class="space-y-1">
<h3 class="text-base font-semibold text-text-primary">
Where is your data now?
</h3>
<p class="text-text-secondary">
Pick the tool. We show you what to export there and in which order to import
the files.
</p>
</div>
<button
v-if="continueSuggestion"
type="button"
data-testid="import_continue_suggestion"
class="w-full flex items-center gap-3 rounded-lg border border-card-border bg-card-background-active px-3 py-2.5 text-left hover:border-card-border-active"
@click="openSource(continueSuggestion.source, continueSuggestion.stepIndex)">
<ImportSourceLogo :source="continueSuggestion.source.id" size="small" />
<span class="flex-1 min-w-0">
<span class="block font-medium text-text-primary">
Continue with {{ continueSuggestion.source.name }}
</span>
<span class="block text-xs text-text-secondary">
Next: {{ stepLabel(continueSuggestion.step) }}
</span>
</span>
<span class="text-text-secondary" aria-hidden="true">→</span>
</button>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
<button
v-for="item in sources"
:key="item.id"
type="button"
:data-testid="`import_source_${item.id}`"
class="flex items-center gap-3 rounded-lg border border-card-border bg-card-background px-3 py-2.5 text-left hover:border-card-border-active hover:bg-card-background-active transition"
@click="openSource(item)">
<ImportSourceLogo :source="item.id" />
<span class="min-w-0">
<span class="block font-semibold text-text-primary">{{
item.name
}}</span>
<span class="block text-xs text-text-secondary">{{ item.blurb }}</span>
</span>
</button>
</div>
<p class="text-xs text-text-tertiary">
Using another tool? Export a CSV and use Generic CSV.
</p>
</template>
<!-- Preparation -->
<template v-else-if="screen === PREPARE">
<h3 class="text-base font-semibold text-text-primary">
Before you export from {{ source.name }}
</h3>
<ImportChecklist :items="source.prerequisites" />
</template>
<!-- Step -->
<template v-else-if="currentStep">
<div class="space-y-1">
<div class="text-xs font-medium text-accent-300">
File {{ screen + 1 }} of {{ steps.length }}
<template v-if="currentStep.format !== 'File'">
· {{ currentStep.format }}</template
>
</div>
<h3 class="text-base font-semibold text-text-primary">
<template v-if="currentStep.format === 'File'">{{
currentStep.title
}}</template>
<template v-else>Export the {{ currentStep.title.toLowerCase() }}</template>
</h3>
<p v-if="currentStep.note" class="max-w-md text-text-secondary">
{{ currentStep.note }}
</p>
</div>
<ImportChecklist
v-if="currentStep.instructions.length > 0"
:items="currentStep.instructions" />
<label
:class="[
'flex max-w-md flex-col items-center justify-center gap-1.5 rounded-lg border border-dashed px-4 text-center transition',
currentStepImports.length > 0 ? 'py-5' : 'py-8',
// Below the instructions it is indented like their previews
currentStep.instructions.length > 0 && 'ml-[1.875rem]',
uploadBlocked
? 'border-card-border bg-card-background cursor-not-allowed opacity-70'
: dragging
? 'border-accent-400 bg-card-background-active cursor-pointer'
: 'border-border-secondary bg-card-background-active hover:border-text-quaternary cursor-pointer',
]"
@dragover.prevent="dragging = !uploadBlocked"
@dragleave="onDragLeave"
@drop.prevent="onDrop">
<span
class="mb-1 flex h-10 w-10 items-center justify-center rounded-full bg-card-background text-text-secondary">
<LoadingSpinner v-if="state.uploading.value" class="h-5 w-5 m-0" />
<ArrowUpTrayIcon v-else class="h-5 w-5" />
</span>
<span class="text-base font-semibold text-text-primary">{{ uploadTitle }}</span>
<span class="text-xs text-text-secondary">{{ uploadHint }}</span>
<input
type="file"
class="sr-only"
data-testid="import_file_input"
:accept="acceptedFiles"
:disabled="uploadBlocked"
@change="onFileSelected" />
</label>
<ul
v-if="currentStepImports.length > 0"
:class="[
'max-w-md space-y-1.5',
currentStep.instructions.length > 0 && 'ml-[1.875rem]',
]"
data-testid="import_step_imports">
<li
v-for="item in currentStepImports"
:key="item.id"
:class="[
'flex items-start gap-2.5 rounded-lg border px-3 py-2',
item.status === 'failed'
? 'border-yellow-600/40 bg-yellow-500/5'
: 'border-card-border bg-card-background dark:bg-card-background-active',
]">
<LoadingSpinner v-if="isActive(item)" class="h-4 w-4 m-0 mt-0.5" />
<CheckCircleIcon
v-else-if="item.status === 'completed'"
class="h-4 w-4 flex-none mt-0.5 text-green-500" />
<ExclamationTriangleIcon
v-else
class="h-4 w-4 flex-none mt-0.5 text-yellow-500" />
<span class="flex-1 min-w-0">
<span class="block text-xs text-text-tertiary">{{
formatDate(item.created_at)
}}</span>
<span class="block text-text-primary">{{
importDescription(item)
}}</span>
</span>
</li>
</ul>
</template>
<!-- Summary -->
<template v-else-if="isSummary">
<div class="space-y-1">
<h3 class="text-base font-semibold text-text-primary">
<template v-if="summaryHasImports"
>Import from {{ source.name }} done</template
>
<template v-else>Nothing imported from {{ source.name }} yet</template>
</h3>
<p class="text-text-secondary">
<template v-if="summaryHasImports"
>This is what was imported for each step.</template
>
<template v-else>Go back to a step and add its file to import it.</template>
</p>
</div>
<ul class="space-y-1.5">
<li
v-for="(row, index) in summaryRows"
:key="row.step.importer"
class="flex items-start gap-2.5 rounded-lg border border-card-border bg-card-background dark:bg-card-background-active px-3 py-2">
<CheckCircleIcon
v-if="row.imports.length > 0"
class="h-4 w-4 flex-none mt-0.5 text-green-500" />
<span
v-else
class="h-4 w-4 flex-none mt-0.5 rounded-full border border-border-secondary"></span>
<span class="flex-1 min-w-0">
<span class="block font-medium text-text-primary">{{
stepLabel(row.step)
}}</span>
<span
v-for="item in row.imports"
:key="item.id"
class="block text-text-secondary">
{{ formatReport(item.report) }}
<span class="text-xs text-text-tertiary"
>· {{ formatDate(item.created_at) }}</span
>
</span>
<span v-if="row.imports.length === 0" class="block text-text-secondary">
Not imported.
<button
type="button"
class="underline hover:text-text-primary"
@click="screen = index">
Go to step
</button>
</span>
</span>
</li>
</ul>
<p v-if="summaryCreatedMembers" class="text-text-secondary">
People from the files were added as placeholder members. Invite them from
Members so they can see their time entries.
</p>
</template>
</div>
<div
v-if="source"
class="flex items-center gap-2 px-4 py-3 bg-card-background border-t border-card-background-separator sm:px-5">
<SecondaryButton data-testid="import_wizard_back" @click="goBack">Back</SecondaryButton>
<span class="flex-1"></span>
<PrimaryButton type="button" data-testid="import_wizard_next" @click="goNext">
{{ nextLabel }}
</PrimaryButton>
</div>
<DialogModal
:show="showSkipConfirmation"
max-width="lg"
@close="showSkipConfirmation = false">
<template #title>Skip without importing?</template>
<template #content>
<p v-if="currentStep && source">
You did not import the {{ currentStep.title.toLowerCase() }} from
{{ source.name }} yet.
<template v-if="currentStep.skipWarning">
{{ currentStep.skipWarning }}
</template>
<template v-else>
If you skip this step they will be missing in solidtime.
</template>
<template v-if="isLastStep">You can come back to it later.</template>
<template v-else>
Import it before the next steps, a later import does not update what already
exists in solidtime.
</template>
</p>
</template>
<template #footer>
<SecondaryButton @click="showSkipConfirmation = false">Go back</SecondaryButton>
<PrimaryButton
class="ms-3"
data-testid="import_wizard_skip_confirm"
@click="confirmSkip">
{{ nextLabel }}
</PrimaryButton>
</template>
</DialogModal>
</div>
</template>

View File

@@ -0,0 +1,82 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { ImportSource } from './importSources';
import ImportSourceLogo from './ImportSourceLogo.vue';
export interface ImportProgressSegment {
key: string;
title: string;
done: boolean;
current: boolean;
}
const props = defineProps<{
source: ImportSource;
// Import steps of the source, the preparation is added in front if the source has one
segments: ImportProgressSegment[];
// -1 is the preparation, the number of steps is the summary
screen: number;
}>();
defineEmits<{ changeSource: [] }>();
// Sources without prerequisites open at the first step and have no preparation screen
const hasPreparation = computed(() => props.source.prerequisites.length > 0);
const allSegments = computed<ImportProgressSegment[]>(() => [
...(hasPreparation.value
? [
{
key: 'preparation',
title: 'Preparation',
done: props.screen >= 0,
current: props.screen < 0,
},
]
: []),
...props.segments,
]);
const status = computed(() => {
if (props.screen >= props.segments.length) {
return 'Summary';
}
const stepNumber = props.screen + (hasPreparation.value ? 2 : 1);
return `Step ${stepNumber} of ${allSegments.value.length}`;
});
function dotClass(segment: ImportProgressSegment): string {
if (segment.current) {
return 'w-5 bg-accent-400';
}
return segment.done ? 'w-1.5 bg-accent-400/40' : 'w-1.5 bg-card-background-active';
}
</script>
<template>
<div
class="@container flex items-center gap-2.5 px-4 sm:px-5 py-3.5 border-b border-card-background-separator">
<ImportSourceLogo :source="source.id" size="small" />
<span class="font-semibold text-text-primary truncate">{{ source.name }}</span>
<div class="ml-1 flex flex-none items-center gap-2">
<div class="flex items-center gap-1.5" aria-hidden="true">
<span
v-for="segment in allSegments"
:key="segment.key"
:title="segment.title"
:class="['h-1.5 rounded-full transition-all', dotClass(segment)]"></span>
</div>
<!-- In narrow cards only the dots are shown -->
<span class="hidden @sm:inline text-xs text-text-tertiary whitespace-nowrap">
{{ status }}
</span>
</div>
<span class="flex-1"></span>
<button
type="button"
class="text-sm text-text-secondary hover:text-text-primary whitespace-nowrap"
@click="$emit('changeSource')">
Change source
</button>
</div>
</template>

View File

@@ -0,0 +1,70 @@
<script setup lang="ts">
// Items of the "Data Export" section in the Toggl workspace settings
const items = [
'Projects',
'Project members',
'Project tasks',
'Clients',
'Tags',
'Team',
'Teams',
'Workspace Settings',
'Alerts',
'Custom Reports',
'Scheduled Reports',
'Tracking Reminders',
'Invoices',
];
</script>
<template>
<div
role="img"
aria-label="Data Export in the Toggl workspace settings with all items selected"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Data Export</div>
<div class="mt-2 flex items-center gap-1.5 text-xs text-text-secondary">
<span
class="flex h-3.5 w-3.5 flex-none items-center justify-center rounded-[3px] bg-[#A5489B] dark:bg-[#BE7CB7]">
<svg
viewBox="0 0 16 16"
fill="none"
class="h-3.5 w-3.5 text-white dark:text-[#1B1B1B]">
<path
d="M4.2 8.4 6.8 11l5-6"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round" />
</svg>
</span>
{{ items.length }} items selected
</div>
<div class="mt-1.5 grid grid-cols-2 gap-x-4 gap-y-1">
<div
v-for="item in items"
:key="item"
class="flex items-center gap-1.5 text-xs text-text-primary">
<span
class="flex h-3.5 w-3.5 flex-none items-center justify-center rounded-[3px] bg-[#A5489B] dark:bg-[#BE7CB7]">
<svg
viewBox="0 0 16 16"
fill="none"
class="h-3.5 w-3.5 text-white dark:text-[#1B1B1B]">
<path
d="M4.2 8.4 6.8 11l5-6"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round" />
</svg>
</span>
<span class="truncate">{{ item }}</span>
</div>
</div>
<div
class="mt-3 flex h-7 w-48 max-w-full items-center justify-center rounded-md bg-[#A5489B] text-xs font-medium text-white dark:bg-[#BE7CB7] dark:text-[#1B1B1B]">
Export to email
</div>
</div>
</template>

View File

@@ -0,0 +1,22 @@
<script setup lang="ts">
const year = new Date().getFullYear();
</script>
<template>
<div
role="img"
:aria-label="`Time entries in the Toggl data export with the year ${year} selected`"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Time entries</div>
<div class="mt-2.5 flex items-center gap-2">
<div
class="flex h-7 w-32 min-w-0 shrink items-center rounded-md border border-input-border bg-input-background px-2.5 text-xs text-text-primary">
{{ year }}
</div>
<div
class="flex h-7 flex-none items-center whitespace-nowrap rounded-md bg-[#A5489B] px-3 text-xs font-medium text-white dark:bg-[#BE7CB7] dark:text-[#1B1B1B]">
Export time entries
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,29 @@
<script setup lang="ts">
import { computed } from 'vue';
import { ChevronDownIcon } from '@heroicons/vue/20/solid';
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
import { timezoneOffset } from './timezoneOffset';
const timezone = getUserTimezone();
// Toggl lists timezones as "(UTC+01:00) Europe/Vienna"
const label = computed(() => `(UTC${timezoneOffset(timezone)}) ${timezone}`);
</script>
<template>
<div
role="img"
:aria-label="`Account timezone in the Toggl account settings set to ${label}`"
class="w-full max-w-md rounded-lg border border-card-border bg-card-background px-4 py-3 select-none">
<div class="text-xs font-semibold text-text-primary">Time Preferences</div>
<div class="my-2.5 border-t border-card-border"></div>
<div class="text-[10px] font-medium uppercase tracking-wide text-text-tertiary">
Account timezone
</div>
<div
class="mt-1 flex w-64 max-w-full items-center justify-between gap-2 rounded-md border border-input-border bg-input-background px-3 py-1.5 text-xs text-text-primary">
<span class="truncate">{{ label }}</span>
<ChevronDownIcon class="h-3.5 w-3.5 flex-none text-text-secondary" />
</div>
</div>
</template>

View File

@@ -0,0 +1,350 @@
import type { ImportType } from '@/packages/api/src';
import type { Component } from 'vue';
import ClockifyFormatPreview from './ClockifyFormatPreview.vue';
import ClockifyProjectExportPreview from './ClockifyProjectExportPreview.vue';
import ClockifyProjectsTablePreview from './ClockifyProjectsTablePreview.vue';
import ClockifyTimezonePreview from './ClockifyTimezonePreview.vue';
import HarvestClientsExportPreview from './HarvestClientsExportPreview.vue';
import HarvestProjectsExportPreview from './HarvestProjectsExportPreview.vue';
import HarvestProjectsPagePreview from './HarvestProjectsPagePreview.vue';
import HarvestTimeExportPreview from './HarvestTimeExportPreview.vue';
import TogglDataExportPreview from './TogglDataExportPreview.vue';
import TogglTimeEntriesExportPreview from './TogglTimeEntriesExportPreview.vue';
import TogglTimezonePreview from './TogglTimezonePreview.vue';
export type ImportSourceId = 'toggl' | 'clockify' | 'harvest' | 'solidtime' | 'generic' | 'other';
export interface ImportSourceStep {
// Importer key of the backend, see ImporterProvider
importer: string;
title: string;
format: 'ZIP' | 'CSV' | 'File';
// What is missing in solidtime if the step is skipped, replaces the general text of the skip confirmation
skipWarning?: string;
// The source exports one file per year, several files can be imported in this step
repeat?: boolean;
note: string;
instructions: (string | ImportListItem)[];
}
export interface ImportListItem {
// Text wrapped in ** is shown bold
text: string;
link?: { href: string; label: string };
// Recreation of the setting in the source tool, shown below the text
preview?: Component;
}
export interface ImportSource {
id: ImportSourceId;
name: string;
blurb: string;
prerequisites: (string | ImportListItem)[];
steps: ImportSourceStep[];
}
const TOGGL_DATA_EXPORT_LINK = {
href: 'https://track.toggl.com/settings/export',
label: 'Open Toggl data export',
};
const CLOCKIFY_PREFERENCES_LINK = {
href: 'https://app.clockify.me/user/preferences',
label: 'Open Clockify preferences',
};
/**
* Known import sources with their exports in the order they have to be imported.
* Files that contain the organization structure (clients, projects, ...) come before the time entries,
* since they contain details (billable rates, estimates, ...) that the time entry exports do not contain.
*/
const KNOWN_SOURCES: ImportSource[] = [
{
id: 'toggl',
name: 'Toggl Track',
blurb: 'Workspace data, then time entries per year',
prerequisites: [
'Sign in to Toggl as an **Admin of the workspace**. Other members can only export their own time entries.',
{
text: 'Set the **same timezone in Toggl as in solidtime**',
link: {
href: 'https://track.toggl.com/account',
label: 'Open Toggl account settings',
},
preview: TogglTimezonePreview,
},
],
steps: [
{
importer: 'toggl_data_importer',
title: 'Workspace data',
format: 'ZIP',
note: 'Clients, projects, tasks, tags and members. Time entries are exported in the next step.',
instructions: [
{
text: 'In Toggl open Admin, then Settings, then Data export',
link: TOGGL_DATA_EXPORT_LINK,
},
{
text: 'Under "Data export" select all items and click "Export to email"',
preview: TogglDataExportPreview,
},
'Download the ZIP from the email (log in to Toggl first) and add it here',
],
},
{
importer: 'toggl_time_entries',
title: 'Time entries',
format: 'CSV',
repeat: true,
note: 'Toggl exports one file per year. Import every year you want to bring over.',
instructions: [
{
text: 'On the same Data export page find "Time entries"',
link: TOGGL_DATA_EXPORT_LINK,
},
{
text: 'Select a year and click "Export time entries"',
preview: TogglTimeEntriesExportPreview,
},
'Add the file here and repeat for each year',
],
},
],
},
{
id: 'clockify',
name: 'Clockify',
blurb: 'Projects, then time entries per year',
prerequisites: [
{
text: 'Under **General in the Clockify preferences** set the language to **English**, the date format to **MM/DD/YYYY** and the time format to **12-hour**',
link: CLOCKIFY_PREFERENCES_LINK,
preview: ClockifyFormatPreview,
},
{
text: 'Set the **same timezone in Clockify as in solidtime**',
link: CLOCKIFY_PREFERENCES_LINK,
preview: ClockifyTimezonePreview,
},
'Check that your Clockify plan includes **CSV exports** (Basic or higher)',
],
steps: [
{
importer: 'clockify_projects',
title: 'Projects',
format: 'CSV',
note: '',
skipWarning:
'Billable rates, billable status and estimates of the projects are not in the time report and will be missing in solidtime.',
instructions: [
{
text: 'Open Projects in the left navigation, click **Export** at the top right of the projects table, then **Customize...**',
link: {
href: 'https://app.clockify.me/projects',
label: 'Open Clockify projects',
},
preview: ClockifyProjectsTablePreview,
},
{
text: 'Make sure **all columns are selected** and click Save',
preview: ClockifyProjectExportPreview,
},
'Click Export again, then **Save as CSV**, and add the file here',
],
},
{
importer: 'clockify_time_entries',
title: 'Time entries',
format: 'CSV',
repeat: true,
note: 'The detailed report covers at most one year per file. Import one file per year.',
instructions: [
'Open Reports, then Time, then Detailed',
'Pick a date range of up to one year (top right)',
'Click Export, then Save as CSV, and add the file here',
],
},
],
},
{
id: 'harvest',
name: 'Harvest',
blurb: 'Clients, projects, then all time entries',
prerequisites: [
'Sign in to Harvest as an **Administrator**',
'Set the **same timezone in Harvest as in solidtime**',
],
steps: [
{
importer: 'harvest_clients',
title: 'Clients',
format: 'CSV',
note: '',
skipWarning:
'Clients that have no projects or time entries will be missing in solidtime.',
instructions: [
{
text: 'Open Clients in the left navigation, click **Import/Export** at the top right, then **Export clients**',
link: {
href: 'https://harvestapp.com/clients',
label: 'Open Harvest clients',
},
preview: HarvestClientsExportPreview,
},
'Add the downloaded CSV file here',
],
},
{
importer: 'harvest_projects',
title: 'Projects',
format: 'CSV',
note: '',
skipWarning:
'Billable status and estimates of the projects are not in the time entries export and will be missing in solidtime.',
instructions: [
{
text: 'Open Projects in the left navigation and click **Export** at the top right',
link: {
href: 'https://harvestapp.com/projects',
label: 'Open Harvest projects',
},
preview: HarvestProjectsPagePreview,
},
{
text: 'Select **Active**, choose **CSV** and click **Export projects**. Harvest sends the file by email.',
preview: HarvestProjectsExportPreview,
},
'Download the file from the email and add it here',
],
},
{
importer: 'harvest_time_entries',
title: 'Time entries',
format: 'CSV',
note: 'One file with all time entries. Large accounts get it by email.',
instructions: [
{
text: 'Open Settings, then **Import/Export**, and click **Export all time** under "Export data"',
link: {
href: 'https://harvestapp.com/company/settings/import_export',
label: 'Open Harvest import/export settings',
},
preview: HarvestTimeExportPreview,
},
'Add the downloaded CSV file here',
],
},
],
},
{
id: 'solidtime',
name: 'solidtime',
blurb: 'Another instance or organization',
prerequisites: [
'Sign in to the other solidtime as **Admin or Owner** of the organization you export',
],
steps: [
{
importer: 'solidtime',
title: 'Organization data',
format: 'ZIP',
note: 'Everything in one file: members, clients, projects, tasks, tags and time entries.',
instructions: [
'In the other solidtime instance select the organization (top left)',
'Open Import / Export in the navigation',
'Click "Export Organization Data" and add the ZIP here',
],
},
],
},
{
id: 'generic',
name: 'Generic CSV',
blurb: 'Your own spreadsheet',
prerequisites: [
'Save the file **comma separated** and **UTF-8 encoded**',
'Write all times in **UTC as ISO 8601**, for example 2024-03-04T09:23:00Z',
],
steps: [
{
importer: 'generic_projects',
title: 'Projects',
format: 'CSV',
note: 'Columns: name, color, billable_rate (in cents), is_public, client, billable_default, estimated_time (in seconds), archived_at.',
skipWarning:
'Colors, billable rates, visibility, estimates and the archived state of the projects will be missing in solidtime.',
instructions: [
{
text: 'Create a CSV with the columns above, one project per row. The docs describe every column and its format.',
link: {
href: 'https://docs.solidtime.io/user-guide/import#generic-projects-importer',
label: 'Open the docs',
},
},
],
},
{
importer: 'generic_time_entries',
title: 'Time entries',
format: 'CSV',
note: 'Columns: description, billable, client, project, tags, start, end, task, user_name, user_email.',
instructions: [
{
text: 'Create a CSV with the columns above, one time entry per row. The docs describe every column and its format.',
link: {
href: 'https://docs.solidtime.io/user-guide/import#generic-time-entries-importer',
label: 'Open the docs',
},
},
],
},
],
},
];
/**
* Builds the sources for the importers available on this instance. Steps of importers that are not available are
* removed, importers that are not part of a known source (for example from extensions) are grouped in "Other".
*/
export function buildImportSources(importers: ImportType[]): ImportSource[] {
const available = new Set(importers.map((importer) => importer.key));
const sources = KNOWN_SOURCES.map((source) => ({
...source,
steps: source.steps.filter((step) => available.has(step.importer)),
})).filter((source) => source.steps.length > 0);
const knownImporters = new Set(
KNOWN_SOURCES.flatMap((source) => source.steps.map((step) => step.importer))
);
const otherImporters = importers.filter((importer) => !knownImporters.has(importer.key));
if (otherImporters.length > 0) {
sources.push({
id: 'other',
name: 'Other',
blurb: 'More importers',
prerequisites: [],
steps: otherImporters.map((importer) => ({
importer: importer.key,
title: importer.name,
format: 'File',
note: '',
instructions: [],
})),
});
}
return sources;
}
export function findSourceStepForImporter(
sources: ImportSource[],
importer: string
): { source: ImportSource; stepIndex: number } | null {
for (const source of sources) {
const stepIndex = source.steps.findIndex((step) => step.importer === importer);
if (stepIndex !== -1) {
return { source, stepIndex };
}
}
return null;
}

View File

@@ -0,0 +1,12 @@
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
/**
* Current UTC offset of a timezone, for example "+01:00" for Europe/Vienna in winter.
*/
export function timezoneOffset(timezone: string): string {
try {
return getDayJsInstance()().tz(timezone).format('Z');
} catch {
return '+00:00';
}
}

View File

@@ -0,0 +1,170 @@
import { computed, getCurrentInstance, onUnmounted, ref } from 'vue';
import { api } from '@/packages/api/src';
import type { Import, ImportType } from '@/packages/api/src';
import { useNotificationsStore } from '@/utils/notification';
import { initializeStores } from '@/utils/init';
const POLL_INTERVAL_MS = 2000;
export function isActiveImport(item: Import): boolean {
return item.status === 'pending' || item.status === 'running';
}
function toBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result !== 'string') {
reject(new Error('Could not read the file'));
return;
}
// Strip the "data:<type>;base64," prefix
resolve(reader.result.substring(reader.result.indexOf(',') + 1));
};
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
/**
* State of the imports of an organization: the available importers, the recent imports and the running import.
* Imports are processed in the background, the running import is polled until it is finished.
*/
export function useImports(organizationId: string) {
const { addNotification, handleApiRequestNotifications } = useNotificationsStore();
const importers = ref<ImportType[]>([]);
const imports = ref<Import[]>([]);
const loaded = ref(false);
const loadFailed = ref(false);
const uploading = ref(false);
const activeImport = computed(() => imports.value.find(isActiveImport) ?? null);
let stopped = false;
let polling = false;
if (getCurrentInstance()) {
onUnmounted(() => {
stopped = true;
});
}
function upsert(updatedImport: Import) {
const index = imports.value.findIndex((item) => item.id === updatedImport.id);
if (index === -1) {
imports.value = [updatedImport, ...imports.value];
} else {
imports.value[index] = updatedImport;
}
}
/**
* Loads the importers and the imports. A failed request is shown as a notification and sets loadFailed,
* so the page can offer to try again instead of loading forever.
*/
async function load() {
loadFailed.value = false;
let responses;
try {
responses = await handleApiRequestNotifications(
() =>
Promise.all([
api.getImporters({ params: { organization: organizationId } }),
api.getImports({ params: { organization: organizationId } }),
]),
undefined,
'Could not load the imports'
);
} catch {
// The error was shown as a notification
loadFailed.value = true;
return;
}
const [importersResponse, importsResponse] = responses;
importers.value = importersResponse.data;
imports.value = importsResponse.data;
loaded.value = true;
void pollActiveImport();
}
async function pollActiveImport() {
if (polling) {
return;
}
polling = true;
try {
while (!stopped && activeImport.value !== null) {
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
const current = activeImport.value;
if (stopped || current === null) {
break;
}
try {
const updated = (
await api.getImport({
params: { organization: organizationId, import: current.id },
})
).data;
upsert(updated);
if (updated.status === 'completed') {
// The import created clients, projects, tags, ... that the stores do not know yet
initializeStores();
}
} catch {
// A failed status check (for example a network issue) is retried with the next poll
}
}
} finally {
polling = false;
}
}
/**
* Uploads the file and starts the import, the import is processed in the background.
*/
async function startImport(importer: string, file: File): Promise<Import | null> {
uploading.value = true;
try {
let data: string;
try {
data = await toBase64(file);
} catch {
addNotification('error', 'Could not read the file');
return null;
}
let response;
try {
response = await handleApiRequestNotifications(() =>
api.importData(
{ type: importer, data: data },
{ params: { organization: organizationId } }
)
);
} catch {
// The error was shown as a notification
return null;
}
upsert(response.data);
if (response.data.status === 'completed') {
initializeStores();
}
void pollActiveImport();
return response.data;
} finally {
uploading.value = false;
}
}
return {
importers,
imports,
loaded,
loadFailed,
uploading,
activeImport,
load,
startImport,
};
}
export type ImportsState = ReturnType<typeof useImports>;

View File

@@ -5,6 +5,11 @@ import { ArrowsRightLeftIcon } from '@heroicons/vue/16/solid';
import PageTitle from '@/Components/Common/PageTitle.vue';
import ImportData from '@/Pages/Teams/Partials/ImportData.vue';
import ExportData from '@/Pages/Teams/Partials/ExportData.vue';
import { onMounted } from 'vue';
import { useOrganizationStore } from '@/utils/useOrganization';
// The organization name and date/time formats are shown in the import and export sections
onMounted(() => useOrganizationStore().fetchOrganization());
</script>
<template>

View File

@@ -1,47 +1,181 @@
<script setup lang="ts">
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 { api, type OrganizationExportResponse } from '@/packages/api/src';
import { api, type Export } from '@/packages/api/src';
import { getCurrentOrganizationId } from '@/utils/useUser';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import { ArrowUpOnSquareIcon, InformationCircleIcon } from '@heroicons/vue/24/outline';
import { ArrowUpOnSquareIcon } from '@heroicons/vue/24/outline';
import { CardTitle } from '@/packages/ui/src';
import Card from '@/Components/Common/Card.vue';
import { useOrganizationStore } from '@/utils/useOrganization';
import ImportLinkButton from '@/Components/Import/ImportLinkButton.vue';
import { formatDateTimeLocalized } from '@/packages/ui/src/utils/time';
const EXPORT_POLL_INTERVAL_MS = 2000;
const showResultModal = 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 { handleApiRequestNotifications } = useNotificationsStore();
const { organization } = storeToRefs(useOrganizationStore());
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() {
loading.value = true;
const organizationId = getCurrentOrganizationId();
if (organizationId) {
try {
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;
}
if (organizationId === null) {
return;
}
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>
@@ -54,7 +188,7 @@ async function exportData() {
<a
class="font-semibold text-accent-200 hover:text-accent-300"
target="_self"
:href="exportResponse?.download_url"
:href="downloadUrl ?? undefined"
>click here</a
>
</div>
@@ -63,27 +197,61 @@ async function exportData() {
<SecondaryButton @click="showResultModal = false"> Close </SecondaryButton>
</template>
</DialogModal>
<div>
<!-- Same spacing between title and card as the dashboard cards -->
<div class="flex flex-col gap-1.5">
<CardTitle title="Export Data" :icon="ArrowUpOnSquareIcon"></CardTitle>
<Card class="mb-3">
<div class="py-2 px-3 sm:px-4 text-sm flex items-center space-x-3">
<InformationCircleIcon class="h-5 min-w-0 w-5 text-bg-tertiary" />
<p class="flex-1">
Export your solidtime organization data. This will include all clients,
projects, tasks, and time entries. You will receive a zip file with json files
for each entity.
</p>
</div>
</Card>
<Card>
<div class="py-6 flex-col items-center flex space-y-5 text-center text-sm">
<div class="py-6 px-4 flex-col items-center flex space-y-5 text-center text-sm">
<div>
The following organization will be exported: <br />
<strong class="font-semibold">{{ organization?.name }}</strong>
</div>
<PrimaryButton :loading @click="exportData"
<PrimaryButton :loading="loading || exportInProgress" @click="exportData"
>Export Organization Data
</PrimaryButton>
<div class="flex flex-col items-center gap-1">
<p class="max-w-md text-text-secondary">
Export your solidtime organization data. This will include all clients,
projects, tasks, and time entries.
</p>
<ImportLinkButton
href="https://docs.solidtime.io/user-guide/export"
label="Read the export docs" />
</div>
<div v-if="exportInProgress" class="text-text-secondary">
The export is being prepared, the download starts automatically when it is
ready.
</div>
</div>
</Card>
<Card v-if="exports.length > 0" class="mt-1.5">
<div class="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>
</Card>
</div>

View File

@@ -1,241 +1,123 @@
<script setup lang="ts">
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { computed, onMounted, ref } from 'vue';
import { useNotificationsStore } from '@/utils/notification';
import { api } from '@/packages/api/src';
import { Field, FieldLabel } from '@/packages/ui/src/field';
import { DocumentIcon } from '@heroicons/vue/24/solid';
import {
ArrowDownOnSquareIcon,
ExclamationTriangleIcon,
InformationCircleIcon,
} from '@heroicons/vue/24/outline';
import { storeToRefs } from 'pinia';
import { ArrowDownOnSquareIcon, ExclamationTriangleIcon } from '@heroicons/vue/24/outline';
import { canUseBillableRates } from '@/utils/billing';
import { getCurrentOrganizationId } from '@/utils/useUser';
import type { 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';
import type { Import } from '@/packages/api/src';
import { CardTitle } from '@/packages/ui/src';
import Card from '@/Components/Common/Card.vue';
import { formatDateTimeLocalized } from '@/packages/ui/src/utils/time';
import { useOrganizationStore } from '@/utils/useOrganization';
import ImportWizard from '@/Components/Import/ImportWizard.vue';
import { useImports } from '@/Components/Import/useImports';
import type { ImportSourceId } from '@/Components/Import/importSources';
const importTypeOptions = ref<ImportType[]>([]);
const organizationId = getCurrentOrganizationId();
const importsState = useImports(organizationId ?? '');
const { imports, importers } = importsState;
const { addNotification } = useNotificationsStore();
const { organization } = storeToRefs(useOrganizationStore());
const loading = ref(false);
// Recent imports are only shown while no source is open in the wizard
const openSource = ref<ImportSourceId | null>(null);
const billableRatesLocked = computed(() => !canUseBillableRates());
onMounted(async () => {
const organizationId = getCurrentOrganizationId();
if (organizationId) {
importTypeOptions.value = (
await api.getImporters({
params: {
organization: organizationId,
},
})
).data;
}
});
const reportResult = ref<ImportReport | null>();
const files = ref<FileList | null>(null);
async function importData() {
if (importType.value === null) {
addNotification('error', 'Please select the import type');
return;
}
if (files.value?.length !== 1) {
addNotification('error', 'Please select the CSV or ZIP file that you want to import');
return;
}
const rawBase64String = await toBase64(files.value[0]!);
const base64String = rawBase64String.split(';')[1]!.replace('base64,', '') as string;
const organizationId = getCurrentOrganizationId();
if (organizationId !== null) {
const { handleApiRequestNotifications } = useNotificationsStore();
loading.value = true;
try {
reportResult.value = await handleApiRequestNotifications(() => {
if (importType.value) {
return api.importData(
{
type: importType.value.key,
data: base64String,
},
{
params: {
organization: organizationId,
},
}
);
}
return new Promise((resolve, reject) => {
reject('Import type is null');
});
});
initializeStores();
if (reportResult.value) {
showResultModal.value = true;
}
} finally {
loading.value = false;
}
await importsState.load();
}
}
const importFile = ref<HTMLInputElement | null>();
function toBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
if (reader.result instanceof ArrayBuffer) {
const decoder = new TextDecoder();
const str = decoder.decode(reader.result);
return reject(str);
} else if (reader.result) {
resolve(reader.result);
}
};
reader.onerror = reject;
});
}
function updateFiles() {
files.value = importFile.value?.files ?? null;
}
const currentImporterDescription = computed(() => {
if (importType.value === null) {
return '';
}
return importType.value.description;
});
const filenames = computed(() => {
return files.value?.item(0)?.name ?? 'Import File selected';
});
function importTypeName(type: string): string {
return importers.value.find((importer) => importer.key === type)?.name ?? type;
}
const importType = ref<ImportType | null>(null);
const showResultModal = ref(false);
function statusLabel(item: Import): string {
switch (item.status) {
case 'pending':
return 'Waiting';
case 'running':
return 'In progress';
case 'completed':
return 'Completed';
case 'failed':
return 'Failed';
}
return item.status;
}
</script>
<template>
<DialogModal closeable :show="showResultModal" @close="showResultModal = false">
<template #title>Import Result</template>
<template #content>
<div class="pb-6">
The import was successful! Here is an overview of the imported data:
</div>
<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 }}
</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 }}
</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 }}
</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 }}
</div>
</template>
<template #footer>
<SecondaryButton @click="showResultModal = false"> Close </SecondaryButton>
</template>
</DialogModal>
<div>
<!-- Same spacing between title and card as the dashboard cards -->
<div class="flex flex-col gap-1.5">
<CardTitle title="Import Data" :icon="ArrowDownOnSquareIcon"></CardTitle>
<Card class="mb-3">
<div class="py-2 px-3 sm:px-4 text-sm flex items-center space-x-3">
<InformationCircleIcon class="h-5 min-w-0 w-5 text-bg-tertiary" />
<p class="flex-1">
Import existing data from Toggl, Clockify, Harvest, generic CSV files or a
different solidtime instance. Please select the type of data you want to import
and follow the instructions.
</p>
</div>
<div
v-if="billableRatesLocked"
class="py-2 px-3 sm:px-4 text-sm flex items-center space-x-3 border-t border-card-background-separator">
<ExclamationTriangleIcon class="h-5 min-w-0 w-5 text-yellow-500" />
<p class="flex-1">
<div v-if="billableRatesLocked" class="mb-1.5 text-sm text-text-secondary">
<p class="flex items-start space-x-2">
<ExclamationTriangleIcon class="h-5 min-w-0 w-5 text-yellow-500 shrink-0" />
<span>
Billable rates and billable status will not be imported, since they are not
available in the free plan. All projects and time entries will be imported as
non-billable.
</p>
</div>
</Card>
</span>
</p>
</div>
<Card>
<div class="px-4 py-5 sm:px-5">
<Field>
<FieldLabel for="importType">Import Type</FieldLabel>
<select
id="importType"
v-model="importType"
name="importType"
class="block w-full border-input-border bg-input-background text-text-primary focus:border-input-border-active rounded-md shadow-sm">
<option :value="null" selected disabled>
Select an import type to get instructions...
</option>
<option
v-for="importTypeOption in importTypeOptions"
:key="importTypeOption.key"
:value="importTypeOption">
{{ importTypeOption.name }}
</option>
</select>
<div v-if="currentImporterDescription" class="py-3 text-text-primary">
<div class="font-semibold text-text-secondary py-1">Instructions:</div>
<div class="max-w-2xl" v-html="currentImporterDescription"></div>
</div>
</Field>
<ImportWizard v-model:source="openSource" :state="importsState" />
</Card>
<div
class="mt-2 flex justify-center rounded-lg border border-dashed border-border-primary px-6 py-10">
<div class="text-center">
<DocumentIcon
class="mx-auto h-8 w-8 text-text-secondary"
aria-hidden="true" />
<div class="mt-4 flex text-sm leading-6 text-text-secondary">
<label
for="file-upload"
class="relative cursor-pointer rounded-md font-semibold text-text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 focus-within:ring-offset-gray-900 hover:text-indigo-500">
<span v-if="files">{{ filenames }}</span>
<span v-else>Upload the Export file</span>
<input
id="file-upload"
ref="importFile"
name="file-upload"
type="file"
class="sr-only"
@change="updateFiles" />
</label>
<Card v-if="openSource === null && imports.length > 0" class="mt-1.5">
<div class="px-4 py-3 sm:px-5 text-sm" data-testid="recent_imports">
<div class="font-semibold text-text-primary pb-2">Recent imports</div>
<ul>
<li
v-for="item in imports"
:key="item.id"
class="py-2 border-t first:border-t-0 border-card-background-separator">
<div class="flex items-center justify-between space-x-3">
<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">{{ importTypeName(item.type) }}</span>
</div>
<span
:class="[
item.status === 'failed'
? 'text-red-500'
: 'text-text-tertiary',
'whitespace-nowrap',
]"
>{{ statusLabel(item) }}</span
>
</div>
<p class="text-xs leading-5 text-text-secondary">
CSV and ZIP are supported
</p>
</div>
</div>
</div>
<div
class="flex items-center justify-end px-4 py-3 bg-card-background border-t border-card-background-separator text-end sm:px-6 shadow sm:rounded-bl-md sm:rounded-br-md">
<PrimaryButton :loading @click="importData">Import Data </PrimaryButton>
<div
v-if="item.status === 'completed' && item.report"
class="text-text-secondary text-xs pt-1">
{{ item.report.time_entries.created }} time entries,
{{ item.report.projects.created }} projects,
{{ item.report.clients.created }} clients,
{{ item.report.tasks.created }} tasks created<template
v-if="item.report.time_entries.skipped > 0"
>, {{ item.report.time_entries.skipped }} existing time entries
skipped</template
>
</div>
<div
v-else-if="item.status === 'failed' && item.error_message"
class="text-text-secondary text-xs pt-1">
{{ item.error_message }}
</div>
</li>
</ul>
</div>
</Card>
</div>

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

View File

@@ -42,7 +42,54 @@ const DestroyWithPasswordRequest = z
password: z.string().nullish(),
})
.passthrough();
const ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
const ExportType = z.literal('organization');
const ExportStatus = z.enum(['pending', 'running', 'completed', 'failed']);
const ExportResource = z
.object({
id: z.string(),
type: ExportType,
status: ExportStatus,
download_available: z.boolean(),
error_message: z.union([z.string(), z.null()]),
user_id: z.union([z.string(), z.null()]),
started_at: z.union([z.string(), z.null()]),
finished_at: z.union([z.string(), z.null()]),
created_at: z.union([z.string(), z.null()]),
})
.passthrough();
const ExportCollection = z.array(ExportResource);
const ImportRequest = z.object({ type: z.string(), data: z.string().max(52428800) }).passthrough();
const ImportSource = z.enum(['file', 'api']);
const ImportStatus = z.enum(['pending', 'running', 'completed', 'failed']);
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(), skipped: 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();
@@ -842,7 +889,15 @@ export const schemas = {
ClientResource,
ClientStoreRequest,
ClientUpdateRequest,
ExportType,
ExportStatus,
ExportResource,
ExportCollection,
ImportRequest,
ImportSource,
ImportStatus,
ImportResource,
ImportCollection,
InvitationResource,
InvitationStoreRequest,
InvoiceResource,
@@ -1610,6 +1665,8 @@ const endpoints = makeApi([
method: 'post',
path: '/v1/organizations/:organization/export',
alias: 'exportOrganization',
description: `The export is processed in the background. Use the returned export ID to poll the status of the export and
the download endpoint to get the download URL once the export is completed.`,
requestFormat: 'json',
parameters: [
{
@@ -1618,7 +1675,162 @@ const endpoints = makeApi([
schema: z.string(),
},
],
response: z.object({ success: z.boolean(), download_url: z.string() }).passthrough(),
response: z.object({ data: ExportResource }).passthrough(),
errors: [
{
status: 400,
description: `API exception`,
schema: z
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
status: 401,
description: `Unauthenticated`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 403,
description: `Authorization error`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 404,
description: `Not found`,
schema: z.object({ message: z.string() }).passthrough(),
},
],
},
{
method: 'get',
path: '/v1/organizations/:organization/exports',
alias: 'getExports',
requestFormat: 'json',
parameters: [
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'page',
type: 'Query',
schema: z.number().int().gte(1).lte(2147483647).optional(),
},
],
response: z
.object({
data: ExportCollection,
links: z
.object({
first: z.union([z.string(), z.null()]),
last: z.union([z.string(), z.null()]),
prev: z.union([z.string(), z.null()]),
next: z.union([z.string(), z.null()]),
})
.passthrough(),
meta: z
.object({
current_page: z.number().int().gte(1),
from: z.union([z.number(), z.null()]),
last_page: z.number().int().gte(1),
links: z.array(
z
.object({
url: z.union([z.string(), z.null()]),
label: z.string(),
active: z.boolean(),
})
.passthrough()
),
path: z.union([z.string(), z.null()]),
per_page: z.number().int().gte(0),
to: z.union([z.number(), z.null()]),
total: z.number().int().gte(0),
})
.passthrough(),
})
.passthrough(),
errors: [
{
status: 401,
description: `Unauthenticated`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 403,
description: `Authorization error`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 404,
description: `Not found`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 422,
description: `Validation error`,
schema: z
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
},
{
method: 'get',
path: '/v1/organizations/:organization/exports/:export',
alias: 'getExport',
requestFormat: 'json',
parameters: [
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'export',
type: 'Path',
schema: z.string(),
},
],
response: z.object({ data: ExportResource }).passthrough(),
errors: [
{
status: 401,
description: `Unauthenticated`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 403,
description: `Authorization error`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 404,
description: `Not found`,
schema: z.object({ message: z.string() }).passthrough(),
},
],
},
{
method: 'get',
path: '/v1/organizations/:organization/exports/:export/download',
alias: 'downloadExport',
description: `The download URL is only valid for a short time, request a new one for every download.`,
requestFormat: 'json',
parameters: [
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'export',
type: 'Path',
schema: z.string(),
},
],
response: z.object({ download_url: z.string() }).passthrough(),
errors: [
{
status: 400,
@@ -1648,6 +1860,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 +1874,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 +1946,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

@@ -32,7 +32,7 @@ const sizeClasses = {
:disabled="loading"
:class="
twMerge(
'bg-button-secondary-background border border-button-secondary-border hover:bg-button-secondary-background-hover shadow-sm transition text-text-primary rounded-lg font-medium inline-flex items-center space-x-1.5 focus-visible:outline-none focus-visible:border-transparent focus-visible:ring-2 focus-visible:ring-ring focus:border-transparent disabled:opacity-25 ease-in-out',
'bg-button-secondary-background border border-button-secondary-border hover:bg-button-secondary-background-hover shadow-sm transition text-text-primary rounded-lg font-medium inline-flex items-center space-x-1.5 focus-visible:outline-none focus-visible:border-transparent focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-25 ease-in-out',
sizeClasses[props.size],
props.class
)

View File

@@ -11,9 +11,9 @@ export const buttonVariants = cva(
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 dark:bg-destructive/70',
outline:
'border shadow-xs hover:text-text-primary bg-card-background dark:bg-transparent border-input dark:border-input hover:bg-white/5',
'border shadow-xs hover:text-text-primary bg-card-background dark:bg-transparent border-input dark:border-input hover:bg-black/5 dark:hover:bg-white/5',
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-white/5',
ghost: 'hover:bg-black/5 dark:hover:bg-white/5',
link: 'text-primary underline-offset-4 hover:underline',
input: 'border-input-border border bg-input-background text-text-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:border-transparent shadow-sm',
},

View File

@@ -0,0 +1,3 @@
id,name,organization_id,archived_at,created_at,updated_at
b4187a44-41f4-46d7-8460-f15a25b3aad6,"Big Company",ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72,"Other Company (Archived)",ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name organization_id archived_at created_at updated_at
2 b4187a44-41f4-46d7-8460-f15a25b3aad6 Big Company ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72 Other Company (Archived) ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,2 @@
id,user_id,name,email,organization_id,billable_rate,role,created_at,updated_at
06e6e605-86bd-417b-b75d-02f671e5d520,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,"Peter Tester",peter.test@email.test,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,admin,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id user_id name email organization_id billable_rate role created_at updated_at
2 06e6e605-86bd-417b-b75d-02f671e5d520 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c Peter Tester peter.test@email.test ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 admin 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1 @@
{"id":"d6a324ee-58d5-4096-8069-c63bd55608f7","version":"1.0","organizations":["ee5a8cd6-312f-4ae6-b044-e2014f09ecc2"],"exported_at":"2024-08-26T18:21:59Z"}

View File

@@ -0,0 +1 @@
id,email,organization_id,role,created_at,updated_at
1 id email organization_id role created_at updated_at

View File

@@ -0,0 +1,2 @@
id,name,billable_rate,currency,created_at,updated_at
ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,"ACME Corp",,EUR,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name billable_rate currency created_at updated_at
2 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 ACME Corp EUR 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,2 @@
id,billable_rate,project_id,user_id,member_id,created_at,updated_at
180a1a98-2f1c-4596-86e4-63a6be0d7b1d,10002,06e79ec4-33f8-4730-804c-d03c014991d1,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,5b2bb4f9-0f8e-4c4a-9d55-6a0c3e0f4a11,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id billable_rate project_id user_id member_id created_at updated_at
2 180a1a98-2f1c-4596-86e4-63a6be0d7b1d 10002 06e79ec4-33f8-4730-804c-d03c014991d1 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c 5b2bb4f9-0f8e-4c4a-9d55-6a0c3e0f4a11 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,4 @@
id,name,color,billable_rate,is_public,client_id,organization_id,is_billable,archived_at,created_at,updated_at
06e79ec4-33f8-4730-804c-d03c014991d1,"Project for Big Company",#ec407a,10001,false,b4187a44-41f4-46d7-8460-f15a25b3aad6,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,true,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
622c74a9-7e64-44c2-9426-2a37ac738206,"Project without Client",#ef5350,,false,,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,false,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
aa831162-dbb2-4cfe-bfe0-5e3a252c66f0,"Project (Archived)",#6a407f,,true,e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,true,2024-08-25T10:00:00Z,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name color billable_rate is_public client_id organization_id is_billable archived_at created_at updated_at
2 06e79ec4-33f8-4730-804c-d03c014991d1 Project for Big Company #ec407a 10001 false b4187a44-41f4-46d7-8460-f15a25b3aad6 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 true 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 622c74a9-7e64-44c2-9426-2a37ac738206 Project without Client #ef5350 false ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 false 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
4 aa831162-dbb2-4cfe-bfe0-5e3a252c66f0 Project (Archived) #6a407f true e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 true 2024-08-25T10:00:00Z 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,3 @@
id,name,organization_id,created_at,updated_at
2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7,Development,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
bf6c0ac5-2587-474b-8983-40bb3ea8002f,Backend,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name organization_id created_at updated_at
2 2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7 Development ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 bf6c0ac5-2587-474b-8983-40bb3ea8002f Backend ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

Some files were not shown because too many files have changed in this diff Show More