mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-10-08 05:43:18 +01:00
Compare commits
3 Commits
project-ta
...
feature/fi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
104d9ee3c2 | ||
|
|
c1e2ccb495 | ||
|
|
c1dce20902 |
@@ -1,37 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
use Illuminate\Auth\EloquentUserProvider;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* User provider that only resolves non-placeholder users.
|
||||
*
|
||||
* Placeholder users are created by imports and when members are removed from an
|
||||
* organization. They can share an email address with a real user, so resolving a user by
|
||||
* email can return a placeholder instead of the real account. The login flow filters them
|
||||
* out explicitly, but the password broker and the guard credential checks (for example the
|
||||
* password confirmation) resolve users through the configured user provider.
|
||||
*
|
||||
* Registered as the "eloquent" provider driver in the AuthServiceProvider, so it replaces the
|
||||
* built-in one for every provider in config/auth.php.
|
||||
*/
|
||||
class ActiveUserProvider extends EloquentUserProvider
|
||||
{
|
||||
/**
|
||||
* @param Model|null $model
|
||||
* @return Builder<Model>
|
||||
*/
|
||||
#[\Override]
|
||||
protected function newModelQuery($model = null): Builder
|
||||
{
|
||||
$query = parent::newModelQuery($model);
|
||||
$query->getQuery()->where('is_placeholder', '=', false);
|
||||
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,6 @@ class ImportRequest extends BaseFormRequest
|
||||
'data' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:'.config('import.max_data_size'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -38,10 +38,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property string|null $pending_email
|
||||
* @property Carbon|null $email_verified_at
|
||||
* @property string|null $password
|
||||
* @property string|null $remember_token
|
||||
* @property string|null $two_factor_secret
|
||||
* @property string|null $two_factor_recovery_codes
|
||||
* @property Carbon|null $two_factor_confirmed_at
|
||||
* @property string $timezone
|
||||
* @property bool $is_placeholder
|
||||
* @property Weekday $week_start
|
||||
@@ -153,9 +150,7 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
|
||||
|
||||
public function canAccessPanel(Panel $panel): bool
|
||||
{
|
||||
return $this->is_placeholder === false
|
||||
&& in_array($this->email, config('auth.super_admins', []), true)
|
||||
&& $this->hasVerifiedEmail();
|
||||
return in_array($this->email, config('auth.super_admins', []), true) && $this->hasVerifiedEmail();
|
||||
}
|
||||
|
||||
public function isMemberOfOrganization(Organization $organization): bool
|
||||
|
||||
@@ -4,14 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Auth\ActiveUserProvider;
|
||||
use App\Models\Passport\AuthCode;
|
||||
use App\Models\Passport\Client;
|
||||
use App\Models\Passport\RefreshToken;
|
||||
use App\Models\Passport\Token;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Passport\Passport;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
@@ -29,13 +26,6 @@ class AuthServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// Replaces the built-in eloquent user provider, so that no authentication flow can
|
||||
// resolve a placeholder user. The driver name is kept, because Passport recognizes
|
||||
// only providers that are configured with the driver "eloquent".
|
||||
Auth::provider('eloquent', function (Application $app, array $config): ActiveUserProvider {
|
||||
return new ActiveUserProvider($app->make('hash'), $config['model']);
|
||||
});
|
||||
|
||||
// define scopes for passport tokens
|
||||
Passport::tokensCan([
|
||||
'create' => 'Create resources',
|
||||
|
||||
@@ -9,8 +9,11 @@ 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\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ImportService
|
||||
{
|
||||
@@ -22,6 +25,8 @@ class ImportService
|
||||
/** @var ImporterContract $importer */
|
||||
$importer = app(ImporterProvider::class)->getImporter($importerType);
|
||||
$importer->init($organization);
|
||||
Storage::disk(config('filesystems.default'))
|
||||
->put('import/'.Carbon::now()->toDateString().'-'.$organization->getKey().'-'.Str::uuid(), $data);
|
||||
|
||||
$lock = Cache::lock('import:'.$organization->getKey(), config('octane.max_execution_time', 60) + 1);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use Illuminate\Support\Str;
|
||||
use League\Csv\Reader;
|
||||
use Override;
|
||||
use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
use ZipArchive;
|
||||
|
||||
class SolidtimeImporter extends DefaultImporter
|
||||
{
|
||||
@@ -33,10 +34,16 @@ class SolidtimeImporter extends DefaultImporter
|
||||
$temporaryDirectoryZip = null;
|
||||
$temporaryDirectory = null;
|
||||
try {
|
||||
$zip = new ZipArchive;
|
||||
$temporaryDirectoryZip = TemporaryDirectory::make();
|
||||
file_put_contents($temporaryDirectoryZip->path('import.zip'), $data);
|
||||
$res = $zip->open($temporaryDirectoryZip->path('import.zip'), ZipArchive::RDONLY);
|
||||
if ($res !== true) {
|
||||
throw new ImportException('Invalid ZIP, error code: '.$res);
|
||||
}
|
||||
$temporaryDirectory = TemporaryDirectory::make();
|
||||
app(ZipImportHelper::class)->extract($temporaryDirectoryZip->path('import.zip'), $temporaryDirectory->path());
|
||||
$zip->extractTo($temporaryDirectory->path());
|
||||
$zip->close();
|
||||
|
||||
if (! file_exists($temporaryDirectory->path('meta.json'))) {
|
||||
throw new ImportException('File "meta.json" missing in ZIP');
|
||||
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Support\Str;
|
||||
use Override;
|
||||
use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
use ValueError;
|
||||
use ZipArchive;
|
||||
|
||||
class TogglDataImporter extends DefaultImporter
|
||||
{
|
||||
@@ -25,10 +26,16 @@ class TogglDataImporter extends DefaultImporter
|
||||
$temporaryDirectoryZip = null;
|
||||
$temporaryDirectory = null;
|
||||
try {
|
||||
$zip = new ZipArchive;
|
||||
$temporaryDirectoryZip = TemporaryDirectory::make();
|
||||
file_put_contents($temporaryDirectoryZip->path('import.zip'), $data);
|
||||
$res = $zip->open($temporaryDirectoryZip->path('import.zip'), ZipArchive::RDONLY);
|
||||
if ($res !== true) {
|
||||
throw new ImportException('Invalid ZIP, error code: '.$res);
|
||||
}
|
||||
$temporaryDirectory = TemporaryDirectory::make();
|
||||
app(ZipImportHelper::class)->extract($temporaryDirectoryZip->path('import.zip'), $temporaryDirectory->path());
|
||||
$zip->extractTo($temporaryDirectory->path());
|
||||
$zip->close();
|
||||
if (! file_exists($temporaryDirectory->path('clients.json'))) {
|
||||
throw new ImportException('File "clients.json" missing in ZIP');
|
||||
}
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Import\Importers;
|
||||
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* Extracts uploaded ZIP archives with limits on file count, total uncompressed
|
||||
* size and entry paths, so a small malicious archive can not fill the disk
|
||||
* (decompression bomb) or write outside the target directory (zip slip).
|
||||
*/
|
||||
class ZipImportHelper
|
||||
{
|
||||
private const int CHUNK_SIZE = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* @throws ImportException
|
||||
*/
|
||||
public function extract(string $zipPath, string $targetPath): void
|
||||
{
|
||||
$zip = new ZipArchive;
|
||||
$res = $zip->open($zipPath, ZipArchive::RDONLY);
|
||||
if ($res !== true) {
|
||||
throw new ImportException('Invalid ZIP, error code: '.$res);
|
||||
}
|
||||
|
||||
try {
|
||||
$maxFiles = (int) config('import.zip_max_files');
|
||||
$maxUncompressedSize = (int) config('import.zip_max_uncompressed_size');
|
||||
|
||||
if ($zip->numFiles > $maxFiles) {
|
||||
throw new ImportException('ZIP contains too many files, maximum is '.$maxFiles);
|
||||
}
|
||||
|
||||
// Check the sizes declared in the archive before writing anything to disk
|
||||
$declaredSize = 0;
|
||||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||||
$stat = $zip->statIndex($index);
|
||||
if ($stat === false) {
|
||||
throw new ImportException('Invalid ZIP entry');
|
||||
}
|
||||
$this->validateEntryName($stat['name']);
|
||||
$declaredSize += $stat['size'];
|
||||
if ($declaredSize > $maxUncompressedSize) {
|
||||
throw new ImportException('ZIP uncompressed size exceeds the maximum of '.$maxUncompressedSize.' bytes');
|
||||
}
|
||||
}
|
||||
|
||||
// The declared sizes can be forged, so the written bytes are counted as well
|
||||
$writtenSize = 0;
|
||||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||||
$stat = $zip->statIndex($index);
|
||||
if ($stat === false) {
|
||||
throw new ImportException('Invalid ZIP entry');
|
||||
}
|
||||
$name = $stat['name'];
|
||||
$entryPath = $targetPath.DIRECTORY_SEPARATOR.$name;
|
||||
|
||||
if (str_ends_with($name, '/')) {
|
||||
$this->ensureDirectoryExists($entryPath);
|
||||
|
||||
continue;
|
||||
}
|
||||
$this->ensureDirectoryExists(dirname($entryPath));
|
||||
|
||||
$stream = $zip->getStreamIndex($index);
|
||||
if ($stream === false) {
|
||||
throw new ImportException('ZIP entry "'.$name.'" can not be read');
|
||||
}
|
||||
$target = fopen($entryPath, 'wb');
|
||||
if ($target === false) {
|
||||
fclose($stream);
|
||||
throw new ImportException('ZIP entry "'.$name.'" can not be extracted');
|
||||
}
|
||||
try {
|
||||
while (! feof($stream)) {
|
||||
$chunk = fread($stream, self::CHUNK_SIZE);
|
||||
if ($chunk === false) {
|
||||
throw new ImportException('ZIP entry "'.$name.'" can not be read');
|
||||
}
|
||||
$writtenSize += strlen($chunk);
|
||||
if ($writtenSize > $maxUncompressedSize) {
|
||||
throw new ImportException('ZIP uncompressed size exceeds the maximum of '.$maxUncompressedSize.' bytes');
|
||||
}
|
||||
fwrite($target, $chunk);
|
||||
}
|
||||
} finally {
|
||||
fclose($target);
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ImportException
|
||||
*/
|
||||
private function validateEntryName(string $name): void
|
||||
{
|
||||
if ($name === '' || str_contains($name, "\0") || str_contains($name, '\\') || str_starts_with($name, '/')) {
|
||||
throw new ImportException('ZIP contains an invalid file path: "'.$name.'"');
|
||||
}
|
||||
if (preg_match('/^[a-zA-Z]:/', $name) === 1) {
|
||||
throw new ImportException('ZIP contains an invalid file path: "'.$name.'"');
|
||||
}
|
||||
foreach (explode('/', rtrim($name, '/')) as $segment) {
|
||||
if ($segment === '' || $segment === '..') {
|
||||
throw new ImportException('ZIP contains an invalid file path: "'.$name.'"');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ImportException
|
||||
*/
|
||||
private function ensureDirectoryExists(string $path): void
|
||||
{
|
||||
if (is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
if (! mkdir($path, 0700, true) && ! is_dir($path)) {
|
||||
throw new ImportException('Directory "'.$path.'" can not be created');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,16 +218,7 @@ class MemberService
|
||||
|
||||
$placeholderUser = $user->replicate();
|
||||
$placeholderUser->is_placeholder = true;
|
||||
// Reset authentication relevant properties on the placeholder user
|
||||
$placeholderUser->password = null;
|
||||
$placeholderUser->remember_token = null;
|
||||
$placeholderUser->two_factor_secret = null;
|
||||
$placeholderUser->two_factor_recovery_codes = null;
|
||||
$placeholderUser->two_factor_confirmed_at = null;
|
||||
$placeholderUser->email_verified_at = null;
|
||||
$placeholderUser->pending_email = null;
|
||||
$placeholderUser->current_team_id = null;
|
||||
$placeholderUser->profile_photo_path = null;
|
||||
$placeholderUser->current_team_id = $member->organization_id;
|
||||
$placeholderUser->save();
|
||||
|
||||
$member->user()->associate($placeholderUser);
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Import payload limit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Maximum length of the base64 encoded "data" field of an import request in
|
||||
| bytes. Requests with a larger payload are rejected with a validation error.
|
||||
|
|
||||
*/
|
||||
|
||||
'max_data_size' => (int) (env('IMPORT_MAX_DATA_SIZE') ?: 50 * 1024 * 1024),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| ZIP extraction limits
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Limits applied to ZIP based importers before and during extraction to
|
||||
| protect the instance against decompression bombs. The uncompressed size
|
||||
| is the sum of all files in the archive in bytes.
|
||||
|
|
||||
*/
|
||||
|
||||
'zip_max_files' => (int) (env('IMPORT_ZIP_MAX_FILES') ?: 100),
|
||||
|
||||
'zip_max_uncompressed_size' => (int) (env('IMPORT_ZIP_MAX_UNCOMPRESSED_SIZE') ?: 500 * 1024 * 1024),
|
||||
|
||||
];
|
||||
@@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Placeholder users used to be created as a full copy of the user they were made from,
|
||||
* which included the credentials and the account state of that user. A placeholder is a
|
||||
* stand-in for a person in one organization, not an account, and the row shares the email
|
||||
* address with the real account, so these values are removed from the placeholders that
|
||||
* already exist. The organization a placeholder belongs to is recorded on its member row.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('users')
|
||||
->where('is_placeholder', '=', true)
|
||||
->where(function (Builder $builder): void {
|
||||
$builder->whereNotNull('password')
|
||||
->orWhereNotNull('remember_token')
|
||||
->orWhereNotNull('two_factor_secret')
|
||||
->orWhereNotNull('two_factor_recovery_codes')
|
||||
->orWhereNotNull('two_factor_confirmed_at')
|
||||
->orWhereNotNull('email_verified_at')
|
||||
->orWhereNotNull('pending_email')
|
||||
->orWhereNotNull('current_team_id')
|
||||
->orWhereNotNull('profile_photo_path');
|
||||
})
|
||||
->update([
|
||||
'password' => null,
|
||||
'remember_token' => null,
|
||||
'two_factor_secret' => null,
|
||||
'two_factor_recovery_codes' => null,
|
||||
'two_factor_confirmed_at' => null,
|
||||
'email_verified_at' => null,
|
||||
'pending_email' => null,
|
||||
'current_team_id' => null,
|
||||
'profile_photo_path' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
};
|
||||
@@ -53,47 +53,6 @@ function todayAt(hour: number, minute: number = 0): string {
|
||||
return d.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
}
|
||||
|
||||
// Cross-day tests anchor to Wednesday and Thursday of the current week instead of today and
|
||||
// tomorrow. E2E users start the week on Monday, so both days are always in the visible week,
|
||||
// whichever day the suite runs on.
|
||||
function wednesdayAt(hour: number, minute: number = 0): Date {
|
||||
const now = new Date();
|
||||
const daysSinceMonday = (now.getDay() + 6) % 7;
|
||||
return new Date(
|
||||
now.getFullYear(),
|
||||
now.getMonth(),
|
||||
now.getDate() - daysSinceMonday + 2,
|
||||
hour,
|
||||
minute,
|
||||
0,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
function thursdayAt(hour: number, minute: number = 0): Date {
|
||||
const d = wednesdayAt(hour, minute);
|
||||
d.setDate(d.getDate() + 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
function toApiTimestamp(date: Date): string {
|
||||
return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
}
|
||||
|
||||
// Local calendar date (YYYY-MM-DD), matching FullCalendar's data-date attributes
|
||||
function toDateStr(date: Date): string {
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${month}-${day}`;
|
||||
}
|
||||
|
||||
async function columnHeaderCenterX(page: Page, date: Date): Promise<number> {
|
||||
const header = page.locator(`.fc-col-header-cell[data-date="${toDateStr(date)}"]`);
|
||||
await expect(header).toBeVisible();
|
||||
const box = await header.boundingBox();
|
||||
return box!.x + box!.width / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* These tests verify that changing the project on a time entry via the calendar
|
||||
* updates the billable status to match the new project's is_billable setting.
|
||||
@@ -1003,9 +962,14 @@ test.describe('Drag-to-Move Events', () => {
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Create entry: Thursday 00:30 → Thursday 01:30 (1 hour, near midnight)
|
||||
const start = toApiTimestamp(thursdayAt(0, 30));
|
||||
const end = toApiTimestamp(thursdayAt(1, 30));
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getDay();
|
||||
// Need today to have a previous day visible in the week view (skip Sunday with Monday week start)
|
||||
test.skip(dayOfWeek === 1, 'Skipping on Monday — previous day not visible in week view');
|
||||
|
||||
// Create entry: today 00:30 → today 01:30 (1 hour, near midnight)
|
||||
const start = todayAt(0, 30);
|
||||
const end = todayAt(1, 30);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Drag up past midnight test',
|
||||
start,
|
||||
@@ -1014,10 +978,11 @@ test.describe('Drag-to-Move Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '00:00:00');
|
||||
|
||||
const thursdayCol = page.locator(
|
||||
`.fc-timegrid-col[data-date="${toDateStr(thursdayAt(0))}"]`
|
||||
);
|
||||
const event = thursdayCol
|
||||
const todayStr = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
const todayCol = page.locator(`.fc-timegrid-col[data-date="${todayStr}"]`);
|
||||
const event = todayCol
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Drag up past midnight test' });
|
||||
await expect(event).toBeVisible({ timeout: 10000 });
|
||||
@@ -1053,7 +1018,10 @@ test.describe('Drag-to-Move Events', () => {
|
||||
expect(newDurationMs).toBe(3600000);
|
||||
|
||||
// The event should have moved to the previous day
|
||||
expect(toDateStr(newStart)).toBe(toDateStr(wednesdayAt(0)));
|
||||
const yesterdayStr = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
expect(newStart.toISOString().split('T')[0]).toBe(yesterdayStr);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1293,8 +1261,8 @@ test.describe('Resize Events', () => {
|
||||
});
|
||||
|
||||
test('resize bottom edge across day boundary changes end date', async ({ page, ctx }) => {
|
||||
const start = toApiTimestamp(wednesdayAt(10));
|
||||
const end = toApiTimestamp(wednesdayAt(11));
|
||||
const start = todayAt(10);
|
||||
const end = todayAt(11);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Cross resize end test',
|
||||
start,
|
||||
@@ -1303,8 +1271,26 @@ test.describe('Resize Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '09:00:00');
|
||||
|
||||
// Resize into Thursday's column (for end resize, end must be > start)
|
||||
const targetX = await columnHeaderCenterX(page, thursdayAt(0));
|
||||
// Find a column AFTER today (for end resize, end must be > start)
|
||||
const headers = page.locator('.fc-col-header-cell');
|
||||
const headerCount = await headers.count();
|
||||
let targetX: number | undefined;
|
||||
let todayIndex = -1;
|
||||
for (let i = 0; i < headerCount; i++) {
|
||||
const header = headers.nth(i);
|
||||
const isToday = await header.evaluate((el) => el.classList.contains('fc-day-today'));
|
||||
if (isToday) {
|
||||
todayIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Pick first column after today, or skip if today is last
|
||||
for (let i = todayIndex + 1; i < headerCount; i++) {
|
||||
const box = await headers.nth(i).boundingBox();
|
||||
targetX = box!.x + box!.width / 2;
|
||||
break;
|
||||
}
|
||||
test.skip(targetX === undefined, 'No column after today to resize to');
|
||||
|
||||
const event = page
|
||||
.locator('.fc-event')
|
||||
@@ -1332,7 +1318,7 @@ test.describe('Resize Events', () => {
|
||||
// First drag down vertically to engage resize (like test 3.1)
|
||||
await page.mouse.move(centerX, bottomY + slotHeight * 4, { steps: 15 });
|
||||
// Then move horizontally to a later day column
|
||||
await page.mouse.move(targetX, bottomY + slotHeight * 4, { steps: 10 });
|
||||
await page.mouse.move(targetX!, bottomY + slotHeight * 4, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
})(),
|
||||
]);
|
||||
@@ -1354,8 +1340,8 @@ test.describe('Resize Events', () => {
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const start = toApiTimestamp(wednesdayAt(10));
|
||||
const end = toApiTimestamp(wednesdayAt(14));
|
||||
const start = todayAt(10);
|
||||
const end = todayAt(14);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Cross resize end test',
|
||||
start,
|
||||
@@ -1364,8 +1350,30 @@ test.describe('Resize Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '09:00:00');
|
||||
|
||||
// Resize into Thursday's column (later day needed for end-edge resize)
|
||||
const targetX = await columnHeaderCenterX(page, thursdayAt(0));
|
||||
// Find a non-today column header that is AFTER today (later day needed for end-edge resize)
|
||||
const headers = page.locator('.fc-col-header-cell');
|
||||
const headerCount = await headers.count();
|
||||
let targetX: number | undefined;
|
||||
let foundToday = false;
|
||||
for (let i = 0; i < headerCount; i++) {
|
||||
const header = headers.nth(i);
|
||||
const isToday = await header.evaluate((el) => el.classList.contains('fc-day-today'));
|
||||
if (isToday) {
|
||||
foundToday = true;
|
||||
continue;
|
||||
}
|
||||
if (foundToday) {
|
||||
const box = await header.boundingBox();
|
||||
targetX = box!.x + box!.width / 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// If today is the last column, use the one before today instead won't work for end resize,
|
||||
// so skip this test in that edge case
|
||||
if (targetX === undefined) {
|
||||
test.skip();
|
||||
return;
|
||||
}
|
||||
|
||||
const event = page
|
||||
.locator('.fc-event')
|
||||
@@ -1390,7 +1398,7 @@ test.describe('Resize Events', () => {
|
||||
await page.waitForTimeout(100);
|
||||
await page.mouse.down();
|
||||
// Move to a different day column at same Y position
|
||||
await page.mouse.move(targetX, bottomY - 3, { steps: 15 });
|
||||
await page.mouse.move(targetX!, bottomY - 3, { steps: 15 });
|
||||
await page.mouse.up();
|
||||
})(),
|
||||
]);
|
||||
@@ -1456,9 +1464,22 @@ test.describe('Resize Events', () => {
|
||||
});
|
||||
|
||||
test('multi-day event end resize on last day works correctly', async ({ page, ctx }) => {
|
||||
// Create entry spanning Wednesday evening → Thursday morning
|
||||
const start = toApiTimestamp(wednesdayAt(20));
|
||||
const end = toApiTimestamp(thursdayAt(10));
|
||||
// Create entry spanning today evening → tomorrow morning
|
||||
const start = todayAt(20);
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const tomorrowStr = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
|
||||
const end = new Date(
|
||||
tomorrow.getFullYear(),
|
||||
tomorrow.getMonth(),
|
||||
tomorrow.getDate(),
|
||||
10,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
)
|
||||
.toISOString()
|
||||
.replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi-day end resize',
|
||||
@@ -1467,14 +1488,14 @@ test.describe('Resize Events', () => {
|
||||
});
|
||||
await goToCalendar(page);
|
||||
|
||||
const thursdayCol = page.locator(
|
||||
`.fc-timegrid-col[data-date="${toDateStr(thursdayAt(0))}"]`
|
||||
);
|
||||
// Check if tomorrow column is visible
|
||||
const tomorrowCol = page.locator(`.fc-timegrid-col[data-date="${tomorrowStr}"]`);
|
||||
test.skip((await tomorrowCol.count()) === 0, 'Tomorrow not visible in current view');
|
||||
|
||||
await scrollCalendarToTime(page, '09:00:00');
|
||||
|
||||
// Find the event segment on Thursday's column
|
||||
const event = thursdayCol
|
||||
// Find the event segment on tomorrow's column
|
||||
const event = tomorrowCol
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Multi-day end resize' })
|
||||
.first();
|
||||
@@ -1520,9 +1541,22 @@ test.describe('Resize Events', () => {
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Create entry spanning Wednesday → Thursday
|
||||
const start = toApiTimestamp(wednesdayAt(10));
|
||||
const end = toApiTimestamp(thursdayAt(14));
|
||||
// Create entry spanning today → tomorrow
|
||||
const start = todayAt(10);
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const tomorrowStr = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
|
||||
const end = new Date(
|
||||
tomorrow.getFullYear(),
|
||||
tomorrow.getMonth(),
|
||||
tomorrow.getDate(),
|
||||
14,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
)
|
||||
.toISOString()
|
||||
.replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Backward end resize multi',
|
||||
@@ -1531,16 +1565,29 @@ test.describe('Resize Events', () => {
|
||||
});
|
||||
await goToCalendar(page);
|
||||
|
||||
const thursdayCol = page.locator(
|
||||
`.fc-timegrid-col[data-date="${toDateStr(thursdayAt(0))}"]`
|
||||
);
|
||||
// Check if tomorrow column is visible
|
||||
const tomorrowCol = page.locator(`.fc-timegrid-col[data-date="${tomorrowStr}"]`);
|
||||
test.skip((await tomorrowCol.count()) === 0, 'Tomorrow not visible in current view');
|
||||
|
||||
await scrollCalendarToTime(page, '12:00:00');
|
||||
|
||||
const wednesdayX = await columnHeaderCenterX(page, wednesdayAt(0));
|
||||
// Find today's column header to get its X center
|
||||
const headers = page.locator('.fc-col-header-cell');
|
||||
const headerCount = await headers.count();
|
||||
let todayX: number | undefined;
|
||||
for (let i = 0; i < headerCount; i++) {
|
||||
const header = headers.nth(i);
|
||||
const isToday = await header.evaluate((el) => el.classList.contains('fc-day-today'));
|
||||
if (isToday) {
|
||||
const box = await header.boundingBox();
|
||||
todayX = box!.x + box!.width / 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
test.skip(todayX === undefined, 'Could not find today column header');
|
||||
|
||||
// Find event segment on Thursday's column and resize end backward to Wednesday
|
||||
const event = thursdayCol
|
||||
// Find event segment on tomorrow's column and resize end backward to today
|
||||
const event = tomorrowCol
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Backward end resize multi' })
|
||||
.first();
|
||||
@@ -1562,9 +1609,9 @@ test.describe('Resize Events', () => {
|
||||
await page.mouse.move(centerX, bottomY - 3);
|
||||
await page.waitForTimeout(100);
|
||||
await page.mouse.down();
|
||||
// Drag down a bit first, then move to Wednesday's column at a Y after the start
|
||||
// Drag down a bit first, then move to today's column at a Y after the start
|
||||
await page.mouse.move(centerX, bottomY + slotHeight, { steps: 5 });
|
||||
await page.mouse.move(wednesdayX, bottomY + slotHeight, { steps: 10 });
|
||||
await page.mouse.move(todayX!, bottomY + slotHeight, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
})(),
|
||||
]);
|
||||
@@ -1580,8 +1627,8 @@ test.describe('Resize Events', () => {
|
||||
});
|
||||
|
||||
test('resize end to earlier column prevents end before start', async ({ page, ctx }) => {
|
||||
const start = toApiTimestamp(thursdayAt(10));
|
||||
const end = toApiTimestamp(thursdayAt(14));
|
||||
const start = todayAt(10);
|
||||
const end = todayAt(14);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'End before start test',
|
||||
start,
|
||||
@@ -1590,8 +1637,25 @@ test.describe('Resize Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '09:00:00');
|
||||
|
||||
// Target Wednesday's column, the day before the entry
|
||||
const targetX = await columnHeaderCenterX(page, wednesdayAt(0));
|
||||
// Find a column BEFORE today
|
||||
const headers = page.locator('.fc-col-header-cell');
|
||||
const headerCount = await headers.count();
|
||||
let targetX: number | undefined;
|
||||
let todayIndex = -1;
|
||||
for (let i = 0; i < headerCount; i++) {
|
||||
const header = headers.nth(i);
|
||||
const isToday = await header.evaluate((el) => el.classList.contains('fc-day-today'));
|
||||
if (isToday) {
|
||||
todayIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (let i = todayIndex - 1; i >= 0; i--) {
|
||||
const box = await headers.nth(i).boundingBox();
|
||||
targetX = box!.x + box!.width / 2;
|
||||
break;
|
||||
}
|
||||
test.skip(targetX === undefined, 'No column before today to test');
|
||||
|
||||
const event = page
|
||||
.locator('.fc-event')
|
||||
@@ -1619,7 +1683,7 @@ test.describe('Resize Events', () => {
|
||||
await page.waitForTimeout(100);
|
||||
await page.mouse.down();
|
||||
// Move to earlier column at a Y position near the top of the grid (before start time)
|
||||
await page.mouse.move(targetX, eventBox!.y - slotHeight * 4, { steps: 15 });
|
||||
await page.mouse.move(targetX!, eventBox!.y - slotHeight * 4, { steps: 15 });
|
||||
await page.mouse.up();
|
||||
|
||||
// Wait for any potential API call
|
||||
@@ -1668,21 +1732,30 @@ test.describe('Click-Drag Selection to Create', () => {
|
||||
test('drag-to-create spanning two days opens create modal with correct cross-day times', async ({
|
||||
page,
|
||||
}) => {
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getDay();
|
||||
// Need today and tomorrow both visible (skip Saturday with Monday week start)
|
||||
test.skip(dayOfWeek === 6, 'Skipping on Saturday — tomorrow not visible in week view');
|
||||
|
||||
await goToCalendar(page);
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
// Use mid-day times so both start and end slots are visible in the viewport
|
||||
await scrollCalendarToTime(page, '10:00:00');
|
||||
|
||||
// Find Wednesday's and Thursday's columns
|
||||
const wednesdayStr = toDateStr(wednesdayAt(0));
|
||||
const thursdayStr = toDateStr(thursdayAt(0));
|
||||
// Find today's and tomorrow's columns
|
||||
const todayStr = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
const tomorrowStr = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
|
||||
const wednesdayCol = page.locator(`.fc-timegrid-col[data-date="${wednesdayStr}"]`);
|
||||
const thursdayCol = page.locator(`.fc-timegrid-col[data-date="${thursdayStr}"]`);
|
||||
await expect(wednesdayCol).toBeVisible();
|
||||
await expect(thursdayCol).toBeVisible();
|
||||
const todayCol = page.locator(`.fc-timegrid-col[data-date="${todayStr}"]`);
|
||||
const tomorrowCol = page.locator(`.fc-timegrid-col[data-date="${tomorrowStr}"]`);
|
||||
await expect(todayCol).toBeVisible();
|
||||
await expect(tomorrowCol).toBeVisible();
|
||||
|
||||
// Find the 11:00 slot (start) and 13:00 slot (end on Thursday)
|
||||
// Find the 11:00 slot (start) and 13:00 slot (end on tomorrow)
|
||||
const startSlot = page.locator('.fc-timegrid-slot-lane[data-time="11:00:00"]').first();
|
||||
const endSlot = page.locator('.fc-timegrid-slot-lane[data-time="13:00:00"]').first();
|
||||
await expect(startSlot).toBeVisible();
|
||||
@@ -1690,18 +1763,18 @@ test.describe('Click-Drag Selection to Create', () => {
|
||||
|
||||
const startSlotBox = await startSlot.boundingBox();
|
||||
const endSlotBox = await endSlot.boundingBox();
|
||||
const wednesdayColBox = await wednesdayCol.boundingBox();
|
||||
const thursdayColBox = await thursdayCol.boundingBox();
|
||||
const todayColBox = await todayCol.boundingBox();
|
||||
const tomorrowColBox = await tomorrowCol.boundingBox();
|
||||
|
||||
// Start drag at 11:00 on Wednesday's column
|
||||
const startX = wednesdayColBox!.x + wednesdayColBox!.width / 2;
|
||||
// Start drag at 11:00 on today's column
|
||||
const startX = todayColBox!.x + todayColBox!.width / 2;
|
||||
const startY = startSlotBox!.y + 2;
|
||||
|
||||
// End drag at 13:00 on Thursday's column
|
||||
const endX = thursdayColBox!.x + thursdayColBox!.width / 2;
|
||||
// End drag at 13:00 on tomorrow's column
|
||||
const endX = tomorrowColBox!.x + tomorrowColBox!.width / 2;
|
||||
const endY = endSlotBox!.y + 2;
|
||||
|
||||
// Drag from Wednesday to Thursday, moving down first, then across
|
||||
// Drag from today to tomorrow — move down first, then across
|
||||
const slotHeight = await getSlotHeight(page);
|
||||
await page.mouse.move(startX, startY);
|
||||
await page.mouse.down();
|
||||
@@ -1719,9 +1792,9 @@ test.describe('Click-Drag Selection to Create', () => {
|
||||
await expect(dialog.getByText('Start')).toBeVisible();
|
||||
await expect(dialog.getByText('End')).toBeVisible();
|
||||
|
||||
// Start date should be Wednesday, end date should be Thursday
|
||||
await expect(dialog.getByText(wednesdayStr)).toBeVisible();
|
||||
await expect(dialog.getByText(thursdayStr)).toBeVisible();
|
||||
// Start date should be today, end date should be tomorrow
|
||||
await expect(dialog.getByText(todayStr)).toBeVisible();
|
||||
await expect(dialog.getByText(tomorrowStr)).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1803,9 +1876,17 @@ test.describe('Timezone & Localization', () => {
|
||||
|
||||
test.describe('Multi-Day Events', () => {
|
||||
test('event spanning 2 days renders and is visible', async ({ page, ctx }) => {
|
||||
// Create entry that spans from Wednesday 22:00 to Thursday 02:00
|
||||
const start = toApiTimestamp(wednesdayAt(22));
|
||||
const end = toApiTimestamp(thursdayAt(2));
|
||||
// Create entry that spans from today 22:00 to tomorrow 02:00
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getDay();
|
||||
// If today is Saturday (6), the entry would span to next week and may not be visible
|
||||
test.skip(dayOfWeek === 6, 'Skipping on Saturday — multi-day would span to next week');
|
||||
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 0, 0);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 2, 0, 0);
|
||||
|
||||
const start = startDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
const end = endDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi day entry',
|
||||
@@ -1820,8 +1901,14 @@ test.describe('Multi-Day Events', () => {
|
||||
});
|
||||
|
||||
test('multi-day event can be edited via click', async ({ page, ctx }) => {
|
||||
const start = toApiTimestamp(wednesdayAt(22));
|
||||
const end = toApiTimestamp(thursdayAt(2));
|
||||
const now = new Date();
|
||||
test.skip(now.getDay() === 6, 'Skip on Saturday');
|
||||
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 0, 0);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 2, 0, 0);
|
||||
|
||||
const start = startDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
const end = endDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi day edit test',
|
||||
@@ -1840,8 +1927,14 @@ test.describe('Multi-Day Events', () => {
|
||||
});
|
||||
|
||||
test('multi-day event context menu works', async ({ page, ctx }) => {
|
||||
const start = toApiTimestamp(wednesdayAt(22));
|
||||
const end = toApiTimestamp(thursdayAt(2));
|
||||
const now = new Date();
|
||||
test.skip(now.getDay() === 6, 'Skip on Saturday');
|
||||
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 0, 0);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 2, 0, 0);
|
||||
|
||||
const start = startDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
const end = endDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi day ctx test',
|
||||
@@ -1861,11 +1954,16 @@ test.describe('Multi-Day Events', () => {
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Create entry: Wednesday 22:00 → Thursday 02:00 (4 hours, spanning 2 days)
|
||||
const startDate = wednesdayAt(22);
|
||||
const endDate = thursdayAt(2);
|
||||
const start = toApiTimestamp(startDate);
|
||||
const end = toApiTimestamp(endDate);
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getDay();
|
||||
// Need today and tomorrow both visible (skip Saturday)
|
||||
test.skip(dayOfWeek === 6, 'Skipping on Saturday — multi-day would span to next week');
|
||||
|
||||
// Create entry: today 22:00 → tomorrow 02:00 (4 hours, spanning 2 days)
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 0, 0);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 2, 0, 0);
|
||||
const start = startDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
const end = endDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi day drag test',
|
||||
@@ -1875,9 +1973,12 @@ test.describe('Multi-Day Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '00:00:00');
|
||||
|
||||
// Find the clipped segment on Thursday's column (00:00-02:00)
|
||||
const thursdayCol = page.locator(`.fc-timegrid-col[data-date="${toDateStr(endDate)}"]`);
|
||||
const event = thursdayCol.locator('.fc-event').filter({ hasText: 'Multi day drag test' });
|
||||
// Find the clipped segment on tomorrow's column (00:00-02:00)
|
||||
const tomorrowStr = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
const tomorrowCol = page.locator(`.fc-timegrid-col[data-date="${tomorrowStr}"]`);
|
||||
const event = tomorrowCol.locator('.fc-event').filter({ hasText: 'Multi day drag test' });
|
||||
await expect(event).toBeVisible({ timeout: 10000 });
|
||||
|
||||
const eventBox = await event.boundingBox();
|
||||
@@ -1912,19 +2013,27 @@ test.describe('Multi-Day Events', () => {
|
||||
// Duration must be preserved (4 hours)
|
||||
expect(Math.abs(newDurationMs - origDurationMs)).toBeLessThan(60000);
|
||||
|
||||
// The start should still be on Wednesday (not jumped to Thursday)
|
||||
expect(toDateStr(newStart)).toBe(toDateStr(startDate));
|
||||
// The start should still be on today (not jumped to tomorrow)
|
||||
const todayStr = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
expect(newStart.toISOString().split('T')[0]).toBe(todayStr);
|
||||
});
|
||||
|
||||
test('dragging clipped segment of multi-day event upward shifts event earlier', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Create entry: Wednesday 22:00 → Thursday 02:00 (4 hours, spanning 2 days)
|
||||
const startDate = wednesdayAt(22);
|
||||
const endDate = thursdayAt(2);
|
||||
const start = toApiTimestamp(startDate);
|
||||
const end = toApiTimestamp(endDate);
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getDay();
|
||||
// Need today and tomorrow both visible (skip Saturday)
|
||||
test.skip(dayOfWeek === 6, 'Skipping on Saturday — multi-day would span to next week');
|
||||
|
||||
// Create entry: today 22:00 → tomorrow 02:00 (4 hours, spanning 2 days)
|
||||
const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 22, 0, 0);
|
||||
const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 2, 0, 0);
|
||||
const start = startDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
const end = endDate.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
description: 'Multi day drag up test',
|
||||
@@ -1934,9 +2043,12 @@ test.describe('Multi-Day Events', () => {
|
||||
await goToCalendar(page);
|
||||
await scrollCalendarToTime(page, '00:00:00');
|
||||
|
||||
// Find the clipped segment on Thursday's column (00:00-02:00)
|
||||
const thursdayCol = page.locator(`.fc-timegrid-col[data-date="${toDateStr(endDate)}"]`);
|
||||
const event = thursdayCol
|
||||
// Find the clipped segment on tomorrow's column (00:00-02:00)
|
||||
const tomorrowStr = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
|
||||
.toISOString()
|
||||
.split('T')[0];
|
||||
const tomorrowCol = page.locator(`.fc-timegrid-col[data-date="${tomorrowStr}"]`);
|
||||
const event = tomorrowCol
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Multi day drag up test' });
|
||||
await expect(event).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -1579,6 +1579,57 @@ test('test that project selection works in create modal', async ({ page, ctx })
|
||||
expect(createBody.data.project_id).not.toBeNull();
|
||||
});
|
||||
|
||||
test('test that ctrl+enter submits the create modal after selecting a project via keyboard', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Regression test for https://github.com/solidtime-io/solidtime/issues/1238
|
||||
const projectName = 'Keyboard Submit Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createProjectViaApi(ctx, { name: projectName });
|
||||
|
||||
await goToTimeOverview(page);
|
||||
|
||||
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Manual time entry' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
// The menu that opened the modal animates out and only then hands focus back to its
|
||||
// own trigger.
|
||||
await expect(page.locator('[role="menu"]')).toHaveCount(0);
|
||||
|
||||
// Fill the description, then move to the project dropdown and select a project purely via keyboard
|
||||
const description = page.getByRole('dialog').getByRole('textbox', { name: 'Description' });
|
||||
await description.fill('Keyboard submit test');
|
||||
await description.press('Tab');
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('button', { name: 'No Project' })
|
||||
).toBeFocused();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByTestId('client_dropdown_search').fill(projectName);
|
||||
await expect(page.getByRole('option', { name: projectName })).toBeVisible();
|
||||
await page.keyboard.press('Enter');
|
||||
const projectTrigger = page.getByRole('dialog').getByRole('button', { name: projectName });
|
||||
await expect(projectTrigger).toBeVisible();
|
||||
// The trigger label updates on the next tick, but the dropdown keeps focus until its
|
||||
// exit animation has finished and reka-ui hands focus back to the trigger.
|
||||
await expect(projectTrigger).toBeFocused();
|
||||
|
||||
// Ctrl+Enter must submit even though focus is no longer on the description input
|
||||
const [createResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) => response.url().includes('/time-entries') && response.status() === 201
|
||||
),
|
||||
page.keyboard.press('Control+Enter'),
|
||||
]);
|
||||
const createBody = await createResponse.json();
|
||||
expect(createBody.data.description).toBe('Keyboard submit test');
|
||||
expect(createBody.data.project_id).not.toBeNull();
|
||||
await expect(page.getByRole('dialog')).toBeHidden();
|
||||
const newTimeEntry = page.locator('[data-testid="time_entry_row"]').first();
|
||||
await expect(newTimeEntry.getByTestId('time_entry_description').first()).toHaveValue(
|
||||
'Keyboard submit test'
|
||||
);
|
||||
});
|
||||
|
||||
test('test that tag selection works in create modal', async ({ page }) => {
|
||||
await goToTimeOverview(page);
|
||||
|
||||
|
||||
@@ -9,6 +9,6 @@
|
||||
},
|
||||
"Invoicing": {
|
||||
"repository": "solidtime-io/extension-invoicing",
|
||||
"ref": "v0.0.6"
|
||||
"ref": "v0.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
2
package-lock.json
generated
2
package-lock.json
generated
@@ -8564,7 +8564,7 @@
|
||||
},
|
||||
"resources/js/packages/ui": {
|
||||
"name": "@solidtime/ui",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.22",
|
||||
"license": "AGPL-3.0",
|
||||
"devDependencies": {
|
||||
"@types/chroma-js": "^3.1.2",
|
||||
|
||||
@@ -28,7 +28,7 @@ useFocus(clientNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Client </span>
|
||||
|
||||
@@ -30,7 +30,7 @@ useFocus(clientNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Update Client </span>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { type Client } from '@/packages/api/src';
|
||||
import ClientTableRow from '@/Components/Common/Client/ClientTableRow.vue';
|
||||
import ClientCreateModal from '@/Components/Common/Client/ClientCreateModal.vue';
|
||||
import ClientTableHeading from '@/Components/Common/Client/ClientTableHeading.vue';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import { canCreateClients } from '@/utils/permissions';
|
||||
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
||||
import {
|
||||
|
||||
@@ -136,7 +136,7 @@ const roleDescription = computed(() => {
|
||||
v-model:show="showOwnershipTransferConfirmModal"
|
||||
:member-name="member.name"
|
||||
@submit="submit"></MemberOwnershipTransferConfirmModal>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="saveWithChecks()">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Update Member </span>
|
||||
|
||||
@@ -78,7 +78,7 @@ useFocus(clientNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Invite Member </span>
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
ChevronRightIcon,
|
||||
EllipsisHorizontalIcon,
|
||||
} from '@heroicons/vue/20/solid';
|
||||
import { buttonVariants } from './Buttons/index';
|
||||
import { cn } from './utils/cn';
|
||||
import { buttonVariants } from '@/packages/ui/src';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { computed, watch } from 'vue';
|
||||
|
||||
const page = defineModel<number>('page', { default: 1 });
|
||||
@@ -79,7 +79,7 @@ async function submitBillableRate() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Edit Project {{ props.originalProject.name }} </span>
|
||||
|
||||
@@ -6,25 +6,17 @@ import { computed, ref, watch } from 'vue';
|
||||
import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue';
|
||||
import ProjectTableHeading from '@/Components/Common/Project/ProjectTableHeading.vue';
|
||||
import ProjectTableRow from '@/Components/Common/Project/ProjectTableRow.vue';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
|
||||
|
||||
export type SortColumn =
|
||||
| 'name'
|
||||
| 'tasks'
|
||||
| 'client_name'
|
||||
| 'spent_time'
|
||||
| 'progress'
|
||||
| 'billable_rate'
|
||||
| 'status'
|
||||
| 'visibility';
|
||||
'name' | 'client_name' | 'spent_time' | 'progress' | 'billable_rate' | 'status' | 'visibility';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
import { canCreateProjects } from '@/utils/permissions';
|
||||
import type { CreateProjectBody, Project, Client, CreateClientBody } from '@/packages/api/src';
|
||||
import { useProjectsStore } from '@/utils/useProjects';
|
||||
import { useClientsStore } from '@/utils/useClients';
|
||||
import { useClientsQuery } from '@/utils/useClientsQuery';
|
||||
import { useTasksQuery } from '@/utils/useTasksQuery';
|
||||
import { getOrganizationCurrencyString } from '@/utils/money';
|
||||
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
|
||||
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
||||
@@ -64,16 +56,6 @@ const clientNameMap = computed(() => {
|
||||
return map;
|
||||
});
|
||||
|
||||
const { tasks } = useTasksQuery();
|
||||
|
||||
const taskCountMap = computed(() => {
|
||||
const map = new Map<string, number>();
|
||||
tasks.value.forEach((task) => {
|
||||
map.set(task.project_id, (map.get(task.project_id) ?? 0) + 1);
|
||||
});
|
||||
return map;
|
||||
});
|
||||
|
||||
// Define column accessors for sorting.
|
||||
// Numeric columns use sortDescFirst so that the first click (chevron down) sorts highest-first,
|
||||
// while text columns default to ascending (A-Z) on first click (chevron down).
|
||||
@@ -82,11 +64,6 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
|
||||
id: 'name',
|
||||
accessorFn: (row: Project) => row.name.toLowerCase(),
|
||||
},
|
||||
{
|
||||
id: 'tasks',
|
||||
sortDescFirst: true,
|
||||
accessorFn: (row: Project) => taskCountMap.value.get(row.id) ?? 0,
|
||||
},
|
||||
{
|
||||
id: 'client_name',
|
||||
accessorFn: (row: Project) => {
|
||||
@@ -184,7 +161,7 @@ async function createClient(client: CreateClientBody): Promise<Client | undefine
|
||||
}
|
||||
|
||||
const gridTemplate = computed(() => {
|
||||
return `grid-template-columns: minmax(300px, 1fr) minmax(100px, auto) minmax(150px, auto) minmax(140px, auto) minmax(130px, auto) ${props.showBillableRate ? 'minmax(130px, auto)' : ''} minmax(120px, auto) minmax(120px, auto) 80px;`;
|
||||
return `grid-template-columns: minmax(300px, 1fr) minmax(150px, auto) minmax(140px, auto) minmax(130px, auto) ${props.showBillableRate ? 'minmax(130px, auto)' : ''} minmax(120px, auto) minmax(120px, auto) 80px;`;
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -36,9 +36,6 @@ function handleSort(column: SortColumn) {
|
||||
@sort="handleSort">
|
||||
Name
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="tasks" v-bind="sortState" @sort="handleSort">
|
||||
Tasks
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="client_name" v-bind="sortState" @sort="handleSort">
|
||||
Client
|
||||
</SortableTableHeaderCell>
|
||||
|
||||
@@ -88,19 +88,17 @@ const showEditProjectModal = ref(false);
|
||||
<ContextMenuTrigger as-child>
|
||||
<TableRow :href="route('projects.show', { project: project.id })">
|
||||
<div
|
||||
class="whitespace-nowrap min-w-0 flex items-center space-x-3 py-4 pr-3 text-sm font-medium text-text-primary pl-2 sm:pl-4 lg:pl-6">
|
||||
class="whitespace-nowrap min-w-0 flex items-center space-x-5 py-4 pr-3 text-sm font-medium text-text-primary pl-2 sm:pl-4 lg:pl-6">
|
||||
<div
|
||||
:style="{ backgroundColor: project.color }"
|
||||
class="w-2.5 h-2.5 ml-1 rounded-full"></div>
|
||||
:style="{
|
||||
backgroundColor: project.color,
|
||||
boxShadow: `var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) ${project.color}30`,
|
||||
}"
|
||||
class="w-3 h-3 ml-1 rounded-full"></div>
|
||||
<span class="overflow-ellipsis overflow-hidden">
|
||||
{{ project.name }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="whitespace-nowrap px-3 py-4 text-sm text-text-primary">
|
||||
<span v-if="projectTasksCount">
|
||||
{{ projectTasksCount }} {{ projectTasksCount === 1 ? 'Task' : 'Tasks' }}
|
||||
</span>
|
||||
<span v-else class="text-text-tertiary">--</span>
|
||||
<span class="text-text-secondary"> {{ projectTasksCount }} Tasks </span>
|
||||
</div>
|
||||
<div class="whitespace-nowrap min-w-0 px-3 py-4 text-sm text-text-primary">
|
||||
<div v-if="project.client_id" class="overflow-ellipsis overflow-hidden">
|
||||
|
||||
@@ -38,7 +38,7 @@ useFocus(projectNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span>Add Project Member</span>
|
||||
|
||||
@@ -63,7 +63,7 @@ useFocus(projectNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span>Edit Project Member</span>
|
||||
|
||||
@@ -79,7 +79,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Report </span>
|
||||
|
||||
@@ -96,7 +96,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Report </span>
|
||||
|
||||
@@ -36,7 +36,7 @@ useFocus(tagNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Update Tag </span>
|
||||
|
||||
@@ -50,7 +50,7 @@ useFocus(taskNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Task </span>
|
||||
|
||||
@@ -35,7 +35,7 @@ useFocus(taskNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Update Task </span>
|
||||
|
||||
@@ -63,7 +63,7 @@ const max = computed(() => {
|
||||
});
|
||||
|
||||
const backgroundColor = useCssVariable('--theme-color-card-background');
|
||||
const borderColor = useCssVariable('--color-border-secondary');
|
||||
const borderColor = useCssVariable('--color-border');
|
||||
const labelColor = useCssVariable('--color-text-secondary');
|
||||
const chartColorRaw = useCssVariable('--theme-color-chart');
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="emit('cancel')">
|
||||
<DialogModal closeable :show="show" @close="emit('cancel')" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex items-center space-x-2">
|
||||
<Coffee class="w-5 h-5 text-text-secondary" />
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
ArrowDownTrayIcon,
|
||||
LockClosedIcon,
|
||||
} from '@heroicons/vue/20/solid';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@solidtime/ui",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.22",
|
||||
"description": "Package containing the solidtime ui components",
|
||||
"main": "./dist/solidtime-ui-lib.umd.cjs",
|
||||
"module": "./dist/solidtime-ui-lib.js",
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
CommandShortcut,
|
||||
} from '../command';
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import type {
|
||||
CommandPaletteCommand,
|
||||
CommandPaletteGroup,
|
||||
@@ -37,8 +36,6 @@ const emit = defineEmits<{
|
||||
select: [command: CommandPaletteCommand | EntitySearchResult];
|
||||
}>();
|
||||
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
|
||||
// Non-empty groups for rendering
|
||||
const nonEmptyGroups = computed(() => props.groups.filter((g) => g.commands.length > 0));
|
||||
|
||||
@@ -74,9 +71,7 @@ watch(open, (isOpen) => {
|
||||
)
|
||||
">
|
||||
<DialogContent
|
||||
class="pointer-events-auto bg-default-background w-full max-w-lg border border-border-tertiary shadow-lg sm:rounded-lg outline-none overflow-hidden p-0 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||
@open-auto-focus="onOpenAutoFocus"
|
||||
@close-auto-focus="onCloseAutoFocus">
|
||||
class="pointer-events-auto bg-default-background w-full max-w-lg border border-border-tertiary shadow-lg sm:rounded-lg outline-none overflow-hidden p-0 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95">
|
||||
<CommandRoot
|
||||
v-model:search-term="searchTerm"
|
||||
class="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import Modal from './Modal.vue';
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
const emit = defineEmits(['close', 'submit']);
|
||||
|
||||
defineProps({
|
||||
show: {
|
||||
@@ -24,7 +24,12 @@ const close = () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :show="show" :max-width="maxWidth" :closeable="closeable" @close="close">
|
||||
<Modal
|
||||
:show="show"
|
||||
:max-width="maxWidth"
|
||||
:closeable="closeable"
|
||||
@close="close"
|
||||
@submit="emit('submit')">
|
||||
<div class="px-4 lg:px-6 py-4">
|
||||
<div class="text-lg font-medium text-text-primary" role="heading">
|
||||
<slot name="title" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { Dialog, DialogContent, DialogFooter } from './dialog/index';
|
||||
import { computed } from 'vue';
|
||||
import { computed, nextTick } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
show: {
|
||||
@@ -17,7 +17,7 @@ const props = defineProps({
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
const emit = defineEmits(['close', 'submit']);
|
||||
|
||||
const close = () => {
|
||||
if (props.closeable) {
|
||||
@@ -25,6 +25,25 @@ const close = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Ctrl+Enter (Cmd+Enter on macOS) submits the modal from any focused element inside it.
|
||||
// Handled in the capture phase so child elements (buttons, dropdown triggers, inputs with
|
||||
// their own Enter handlers) never see the keystroke and cannot open or double-submit.
|
||||
async function onKeydownCapture(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter' || !(event.ctrlKey || event.metaKey) || event.isComposing) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Inputs like the time and duration fields commit their value on blur, so blur first
|
||||
// and let the resulting model updates settle before submitting.
|
||||
const active = document.activeElement;
|
||||
if (active instanceof HTMLElement) {
|
||||
active.blur();
|
||||
}
|
||||
await nextTick();
|
||||
emit('submit');
|
||||
}
|
||||
|
||||
const maxWidthClass = computed(() => {
|
||||
return {
|
||||
sm: 'sm:max-w-sm',
|
||||
@@ -39,7 +58,7 @@ const maxWidthClass = computed(() => {
|
||||
<template>
|
||||
<Dialog :open="show" @update:open="close">
|
||||
<DialogContent :class="maxWidthClass">
|
||||
<div class="min-w-0">
|
||||
<div class="min-w-0" @keydown.capture="onKeydownCapture">
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ const currentClientName = computed(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Project </span>
|
||||
|
||||
@@ -30,7 +30,7 @@ useFocus(tagNameInput, { initialValue: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create Tags </span>
|
||||
|
||||
@@ -78,7 +78,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex items-center space-x-2 text-amber-600 dark:text-amber-400">
|
||||
<Coffee class="w-5 h-5" />
|
||||
|
||||
@@ -126,7 +126,7 @@ const billableProxy = computed({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Create manual time entry </span>
|
||||
|
||||
@@ -164,7 +164,7 @@ const typeProxy = computed({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Edit time entry </span>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/packages/api/src';
|
||||
import { Checkbox } from '@/packages/ui/src';
|
||||
import { TagIcon, ExclamationTriangleIcon } from '@heroicons/vue/20/solid';
|
||||
import { XMarkIcon } from '@heroicons/vue/16/solid';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
|
||||
import { Button } from '@/packages/ui/src/Buttons';
|
||||
import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
|
||||
@@ -60,6 +61,13 @@ const projectId = ref<string | null>(null);
|
||||
const billable = ref<boolean | undefined>(undefined);
|
||||
const selectedTags = ref<string[]>([]);
|
||||
|
||||
// Clearing the project puts both fields back to "leave unchanged", the same state the form
|
||||
// returns to after a successful submit.
|
||||
function resetProject() {
|
||||
projectId.value = null;
|
||||
taskId.value = undefined;
|
||||
}
|
||||
|
||||
const timeEntryBillable = computed({
|
||||
get: () => {
|
||||
if (billable.value === undefined) {
|
||||
@@ -147,7 +155,7 @@ const showBreakWarning = computed(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal closeable :show="show" @close="show = false">
|
||||
<DialogModal closeable :show="show" @close="show = false" @submit="submit">
|
||||
<template #title>
|
||||
<div class="flex space-x-2">
|
||||
<span> Update {{ timeEntries.length }} time entries </span>
|
||||
@@ -182,42 +190,59 @@ const showBreakWarning = computed(
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel for="project">Project</FieldLabel>
|
||||
<TimeTrackerProjectTaskDropdown
|
||||
v-model:project="projectId"
|
||||
v-model:task="taskId"
|
||||
variant="input"
|
||||
align="start"
|
||||
size="default"
|
||||
:clients
|
||||
:create-project
|
||||
:create-client
|
||||
:currency="currency"
|
||||
:organization-billable-rate="organizationBillableRate"
|
||||
:can-create-project
|
||||
empty-placeholder="Select project..."
|
||||
allow-reset
|
||||
:enable-estimated-time
|
||||
:projects="projects"
|
||||
:tasks="tasks"></TimeTrackerProjectTaskDropdown>
|
||||
<div class="flex items-center gap-1 min-w-0">
|
||||
<!-- the dropdown declares its own `class` prop, which goes to the
|
||||
trigger button, so the growing has to happen on a wrapper -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<TimeTrackerProjectTaskDropdown
|
||||
v-model:project="projectId"
|
||||
v-model:task="taskId"
|
||||
variant="input"
|
||||
align="start"
|
||||
size="default"
|
||||
:clients
|
||||
:create-project
|
||||
:create-client
|
||||
:currency="currency"
|
||||
:organization-billable-rate="organizationBillableRate"
|
||||
:can-create-project
|
||||
empty-placeholder="Select project..."
|
||||
:enable-estimated-time
|
||||
:projects="projects"
|
||||
:tasks="tasks"></TimeTrackerProjectTaskDropdown>
|
||||
</div>
|
||||
<button
|
||||
v-if="projectId !== null"
|
||||
type="button"
|
||||
data-testid="project_reset_button"
|
||||
class="p-1 rounded hover:bg-quaternary text-text-tertiary hover:text-text-primary"
|
||||
@click="resetProject">
|
||||
<XMarkIcon class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Tag</FieldLabel>
|
||||
<div class="flex space-x-5">
|
||||
<TagDropdown
|
||||
v-model="selectedTags"
|
||||
:create-tag
|
||||
:tags="tags"
|
||||
:show-no-tag-option="false">
|
||||
<template #trigger>
|
||||
<Button variant="input" :disabled="removeAllTags">
|
||||
<TagIcon class="h-4 text-icon-default" />
|
||||
<span v-if="selectedTags.length > 0">
|
||||
Set {{ selectedTags.length }} tags
|
||||
</span>
|
||||
<span v-else>Select Tags...</span>
|
||||
</Button>
|
||||
</template>
|
||||
</TagDropdown>
|
||||
<div class="flex items-center space-x-5">
|
||||
<!-- the dropdown root is `min-w-0`, so as a flex item it would shrink
|
||||
below its trigger and let the button overflow into the checkbox -->
|
||||
<div class="shrink-0">
|
||||
<TagDropdown
|
||||
v-model="selectedTags"
|
||||
:create-tag
|
||||
:tags="tags"
|
||||
:show-no-tag-option="false">
|
||||
<template #trigger>
|
||||
<Button variant="input" :disabled="removeAllTags">
|
||||
<TagIcon class="h-4 text-icon-default" />
|
||||
<span v-if="selectedTags.length > 0">
|
||||
Set {{ selectedTags.length }} tags
|
||||
</span>
|
||||
<span v-else>Select Tags...</span>
|
||||
</Button>
|
||||
</template>
|
||||
</TagDropdown>
|
||||
</div>
|
||||
<Field orientation="horizontal">
|
||||
<Checkbox id="no_tags" v-model:checked="removeAllTags"></Checkbox>
|
||||
<FieldLabel for="no_tags">Remove all tags</FieldLabel>
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
Client,
|
||||
} from '@/packages/api/src';
|
||||
|
||||
import { PlusCircleIcon, MinusIcon, XMarkIcon } from '@heroicons/vue/16/solid';
|
||||
import { PlusCircleIcon, MinusIcon } from '@heroicons/vue/16/solid';
|
||||
import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import { Button } from '@/packages/ui/src/Buttons';
|
||||
@@ -58,7 +58,6 @@ const props = withDefaults(
|
||||
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
|
||||
currency: string;
|
||||
emptyPlaceholder?: string;
|
||||
allowReset?: boolean;
|
||||
noProjectValue?: string | null;
|
||||
enableEstimatedTime: boolean;
|
||||
organizationBillableRate: number | null;
|
||||
@@ -70,7 +69,6 @@ const props = withDefaults(
|
||||
}>(),
|
||||
{
|
||||
emptyPlaceholder: 'No Project',
|
||||
allowReset: false,
|
||||
noProjectValue: NO_PROJECT_ID,
|
||||
variant: 'ghost',
|
||||
align: 'center',
|
||||
@@ -558,12 +556,6 @@ function selectProject(projectId: string) {
|
||||
emit('changed', project.value, task.value);
|
||||
}
|
||||
|
||||
function resetProject() {
|
||||
project.value = null;
|
||||
task.value = null;
|
||||
emit('changed', project.value, task.value);
|
||||
}
|
||||
|
||||
const showCreateProject = ref(false);
|
||||
</script>
|
||||
|
||||
@@ -571,40 +563,28 @@ const showCreateProject = ref(false);
|
||||
<Dropdown v-model="open" :close-on-content-click="false" :align="props.align">
|
||||
<template #trigger>
|
||||
<slot name="trigger">
|
||||
<div class="flex items-center gap-1">
|
||||
<Button
|
||||
:variant="props.variant"
|
||||
:size="props.size"
|
||||
:class="twMerge('w-full justify-start overflow-hidden', props.class)">
|
||||
<div
|
||||
class="w-2.5 h-2.5 rounded-full shrink-0"
|
||||
:style="{ backgroundColor: selectedProjectColor }"></div>
|
||||
<span class="truncate shrink-[1] text-text-primary">{{
|
||||
selectedProjectName
|
||||
}}</span>
|
||||
<template v-if="currentTask">
|
||||
<ChevronRightIcon class="!size-3 text-text-primary shrink-0 -mx-1" />
|
||||
<span class="truncate shrink-[100]">{{ currentTask.name }}</span>
|
||||
</template>
|
||||
<template v-if="selectedClientName">
|
||||
<span class="dark:text-text-tertiary text-text-quaternary shrink-0"
|
||||
>•</span
|
||||
>
|
||||
<span
|
||||
class="truncate shrink-[200] dark:text-text-tertiary text-text-quaternary"
|
||||
>{{ selectedClientName }}</span
|
||||
>
|
||||
</template>
|
||||
</Button>
|
||||
<button
|
||||
v-if="allowReset && project !== null"
|
||||
type="button"
|
||||
data-testid="project_reset_button"
|
||||
class="p-1 rounded hover:bg-quaternary text-text-tertiary hover:text-text-primary"
|
||||
@click.stop="resetProject">
|
||||
<XMarkIcon class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<Button
|
||||
:variant="props.variant"
|
||||
:size="props.size"
|
||||
:class="twMerge('w-full justify-start overflow-hidden', props.class)">
|
||||
<div
|
||||
class="w-2.5 h-2.5 rounded-full shrink-0"
|
||||
:style="{ backgroundColor: selectedProjectColor }"></div>
|
||||
<span class="truncate shrink-[1] text-text-primary">{{
|
||||
selectedProjectName
|
||||
}}</span>
|
||||
<template v-if="currentTask">
|
||||
<ChevronRightIcon class="!size-3 text-text-primary shrink-0 -mx-1" />
|
||||
<span class="truncate shrink-[100]">{{ currentTask.name }}</span>
|
||||
</template>
|
||||
<template v-if="selectedClientName">
|
||||
<span class="dark:text-text-tertiary text-text-quaternary shrink-0">•</span>
|
||||
<span
|
||||
class="truncate shrink-[200] dark:text-text-tertiary text-text-quaternary"
|
||||
>{{ selectedClientName }}</span
|
||||
>
|
||||
</template>
|
||||
</Button>
|
||||
</slot>
|
||||
</template>
|
||||
<template #content>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import {
|
||||
DialogContent,
|
||||
type DialogContentEmits,
|
||||
@@ -21,10 +20,6 @@ const delegatedProps = computed(() => {
|
||||
});
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
|
||||
// Forwarded consumer listeners run first, so a consumer can still take over
|
||||
// by calling preventDefault() on close-auto-focus.
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -41,9 +36,7 @@ const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
'my-3 md:my-14 xl:my-24 bg-default-background grid w-full max-w-lg border border-border-tertiary shadow-lg duration-200 rounded-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
props.class
|
||||
)
|
||||
"
|
||||
@open-auto-focus="onOpenAutoFocus"
|
||||
@close-auto-focus="onCloseAutoFocus">
|
||||
">
|
||||
<slot />
|
||||
</DialogContent>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import { X } from '@lucide/vue';
|
||||
import {
|
||||
DialogClose,
|
||||
@@ -23,10 +22,6 @@ const delegatedProps = computed(() => {
|
||||
});
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
|
||||
// Forwarded consumer listeners run first, so a consumer can still take over
|
||||
// by calling preventDefault() on close-auto-focus.
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -41,8 +36,6 @@ const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
)
|
||||
"
|
||||
v-bind="forwarded"
|
||||
@open-auto-focus="onOpenAutoFocus"
|
||||
@close-auto-focus="onCloseAutoFocus"
|
||||
@pointer-down-outside="
|
||||
(event) => {
|
||||
const originalEvent = event.detail.originalEvent;
|
||||
|
||||
@@ -32,7 +32,6 @@ import InputLabel from './Input/InputLabel.vue';
|
||||
import TextInput from './Input/TextInput.vue';
|
||||
import LoadingSpinner from './LoadingSpinner.vue';
|
||||
import Modal from './Modal.vue';
|
||||
import Pagination from './Pagination.vue';
|
||||
import ProjectBadge from './Project/ProjectBadge.vue';
|
||||
import TimeEntryCreateModal from './TimeEntry/TimeEntryCreateModal.vue';
|
||||
import TimeEntryEditModal from './TimeEntry/TimeEntryEditModal.vue';
|
||||
@@ -258,7 +257,6 @@ export {
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
Pagination,
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { useDialogFocusRestore } from './useDialogFocusRestore';
|
||||
|
||||
function closeEvent() {
|
||||
return new CustomEvent('focusScope.autoFocusOnUnmount', { cancelable: true });
|
||||
}
|
||||
|
||||
describe('useDialogFocusRestore', () => {
|
||||
it('restores focus to the element focused when the dialog opened', () => {
|
||||
vi.useFakeTimers();
|
||||
const button = document.createElement('button');
|
||||
document.body.appendChild(button);
|
||||
button.focus();
|
||||
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
onOpenAutoFocus();
|
||||
button.blur();
|
||||
|
||||
const event = closeEvent();
|
||||
onCloseAutoFocus(event);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
vi.runAllTimers();
|
||||
expect(document.activeElement).toBe(button);
|
||||
|
||||
button.remove();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('focuses nothing when the dialog was opened with nothing focused', () => {
|
||||
vi.useFakeTimers();
|
||||
const stale = document.createElement('button');
|
||||
document.body.appendChild(stale);
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
|
||||
// First open from the button, then close
|
||||
stale.focus();
|
||||
onOpenAutoFocus();
|
||||
onCloseAutoFocus(closeEvent());
|
||||
vi.runAllTimers();
|
||||
stale.blur();
|
||||
|
||||
// Second open from the body must not refocus the stale button
|
||||
onOpenAutoFocus();
|
||||
const event = closeEvent();
|
||||
onCloseAutoFocus(event);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
vi.runAllTimers();
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
|
||||
stale.remove();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('does not restore focus to an element that was removed', () => {
|
||||
vi.useFakeTimers();
|
||||
const button = document.createElement('button');
|
||||
document.body.appendChild(button);
|
||||
button.focus();
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
onOpenAutoFocus();
|
||||
button.remove();
|
||||
|
||||
onCloseAutoFocus(closeEvent());
|
||||
vi.runAllTimers();
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('leaves control to a consumer that already prevented the event', () => {
|
||||
vi.useFakeTimers();
|
||||
const button = document.createElement('button');
|
||||
document.body.appendChild(button);
|
||||
button.focus();
|
||||
const { onOpenAutoFocus, onCloseAutoFocus } = useDialogFocusRestore();
|
||||
onOpenAutoFocus();
|
||||
button.blur();
|
||||
|
||||
const event = closeEvent();
|
||||
event.preventDefault();
|
||||
onCloseAutoFocus(event);
|
||||
vi.runAllTimers();
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
|
||||
button.remove();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* Restores focus to the element that was focused when a dialog opened.
|
||||
*
|
||||
* reka-ui remembers the active element at content mount as the dialog's
|
||||
* "trigger" (only when it is not the body) and refocuses it on every close,
|
||||
* but it never clears that value. A dialog opened while nothing is focused
|
||||
* (e.g. the command palette via Cmd+K from the body) therefore refocuses
|
||||
* whatever triggered a *previous* open. Bind these handlers to
|
||||
* `DialogContent`'s `open-auto-focus` / `close-auto-focus` events to restore
|
||||
* exactly the previously focused element, or nothing.
|
||||
*
|
||||
* A consumer handler that already called `preventDefault()` on
|
||||
* `close-auto-focus` keeps control; this composable then does nothing.
|
||||
*/
|
||||
export function useDialogFocusRestore() {
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
|
||||
function onOpenAutoFocus() {
|
||||
const active = document.activeElement;
|
||||
previouslyFocused =
|
||||
active instanceof HTMLElement && active !== document.body ? active : null;
|
||||
}
|
||||
|
||||
function onCloseAutoFocus(event: Event) {
|
||||
const target = previouslyFocused;
|
||||
previouslyFocused = null;
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
// Prevents both FocusScope's default restore and reka-ui's trigger refocus
|
||||
event.preventDefault();
|
||||
// Same tick reka-ui uses, so the dialog content is fully gone first
|
||||
setTimeout(() => {
|
||||
if (target?.isConnected) {
|
||||
target.focus({ preventScroll: true });
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
return { onOpenAutoFocus, onCloseAutoFocus };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { api } from '@/packages/api/src';
|
||||
import type { TimeEntry } from '@/packages/api/src';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
@@ -57,6 +57,7 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
const currentTimeEntry = ref<TimeEntry>({ ...emptyTimeEntry });
|
||||
const { handleApiRequestNotifications } = useNotificationsStore();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useLocalStorage('solidtime/current-time-entry', currentTimeEntry, {
|
||||
deep: true,
|
||||
});
|
||||
@@ -88,12 +89,23 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
try {
|
||||
const timeEntriesResponse = await api.getMyActiveTimeEntry({});
|
||||
if (timeEntriesResponse?.data) {
|
||||
currentTimeEntry.value = timeEntriesResponse.data;
|
||||
} else if (currentTimeEntry.value.id !== '') {
|
||||
// No active time entry on server
|
||||
// Only reset if we had a previously started timer (has an ID)
|
||||
// Don't reset if user is preparing a new time entry (no ID yet)
|
||||
currentTimeEntry.value = { ...emptyTimeEntry };
|
||||
if (timeEntriesResponse.data) {
|
||||
currentTimeEntry.value = timeEntriesResponse.data;
|
||||
if (
|
||||
currentTimeEntry.value.start !== '' &&
|
||||
currentTimeEntry.value.end === null
|
||||
) {
|
||||
startLiveTimer();
|
||||
}
|
||||
} else {
|
||||
// No active time entry on server
|
||||
// Only reset if we had a previously started timer (has an ID)
|
||||
// Don't reset if user is preparing a new time entry (no ID yet)
|
||||
if (currentTimeEntry.value.id !== '') {
|
||||
currentTimeEntry.value = { ...emptyTimeEntry };
|
||||
stopLiveTimer();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// API error (e.g., 404 when no active time entry)
|
||||
@@ -101,6 +113,7 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
// Don't reset if user is preparing a new time entry (no ID yet)
|
||||
if (currentTimeEntry.value.id !== '') {
|
||||
currentTimeEntry.value = { ...emptyTimeEntry };
|
||||
stopLiveTimer();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -281,18 +294,6 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
return isActive.value && currentTimeEntry.value.type === 'break';
|
||||
});
|
||||
|
||||
watch(
|
||||
isActive,
|
||||
(active) => {
|
||||
if (active) {
|
||||
startLiveTimer();
|
||||
} else {
|
||||
stopLiveTimer();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
async function setActiveState(newState: boolean) {
|
||||
if (newState) {
|
||||
startLiveTimer();
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PasswordConfirmationTest extends TestCase
|
||||
@@ -44,43 +43,4 @@ class PasswordConfirmationTest extends TestCase
|
||||
|
||||
$response->assertSessionHasErrors();
|
||||
}
|
||||
|
||||
public function test_password_can_be_confirmed_if_a_placeholder_user_with_the_same_email_exists(): void
|
||||
{
|
||||
// Arrange
|
||||
// Placeholders created by an import have no password at all. The placeholder is created
|
||||
// first so that it would be returned by an unordered lookup by email.
|
||||
$email = 'shared@example.com';
|
||||
User::factory()->placeholder()->create(['email' => $email, 'password' => null]);
|
||||
$user = User::factory()->create(['email' => $email, 'password' => Hash::make('secret-password')]);
|
||||
|
||||
// Act
|
||||
$response = $this->actingAs($user)->post('/user/confirm-password', [
|
||||
'password' => 'secret-password',
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHasNoErrors();
|
||||
$this->assertTrue($this->app['session']->has('auth.password_confirmed_at'));
|
||||
}
|
||||
|
||||
public function test_password_confirmation_ignores_the_password_of_a_placeholder_user_with_the_same_email(): void
|
||||
{
|
||||
// Arrange
|
||||
// Placeholders created by removing a member copy the password hash as of the removal,
|
||||
// so the placeholder holds a password that the real user has since replaced.
|
||||
$email = 'shared@example.com';
|
||||
User::factory()->placeholder()->create(['email' => $email, 'password' => Hash::make('outdated-password')]);
|
||||
$user = User::factory()->create(['email' => $email, 'password' => Hash::make('current-password')]);
|
||||
|
||||
// Act
|
||||
$response = $this->actingAs($user)->post('/user/confirm-password', [
|
||||
'password' => 'outdated-password',
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertSessionHasErrors();
|
||||
$this->assertFalse($this->app['session']->has('auth.password_confirmed_at'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace Tests\Feature;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
@@ -94,62 +93,4 @@ class PasswordResetTest extends TestCase
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function test_password_reset_targets_the_real_user_when_a_placeholder_user_with_the_same_email_exists(): void
|
||||
{
|
||||
|
||||
Notification::fake();
|
||||
|
||||
// The placeholder is created first so that it would be returned by an unordered lookup by email
|
||||
$email = 'shared@example.com';
|
||||
$placeholder = User::factory()->placeholder()->create(['email' => $email]);
|
||||
$user = User::factory()->create(['email' => $email]);
|
||||
$placeholderPasswordBefore = $placeholder->password;
|
||||
|
||||
$response = $this->post('/forgot-password', [
|
||||
'email' => $email,
|
||||
]);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
Notification::assertNotSentTo($placeholder, ResetPassword::class);
|
||||
Notification::assertSentTo($user, ResetPassword::class, function (ResetPassword $notification) use ($email) {
|
||||
$response = $this->post('/reset-password', [
|
||||
'token' => $notification->token,
|
||||
'email' => $email,
|
||||
'password' => 'new-password-123',
|
||||
'password_confirmation' => 'new-password-123',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
$placeholder->refresh();
|
||||
$user->refresh();
|
||||
$this->assertSame($placeholderPasswordBefore, $placeholder->password);
|
||||
$this->assertTrue(Hash::check('new-password-123', $user->password));
|
||||
|
||||
$response = $this->post('/login', [
|
||||
'email' => $email,
|
||||
'password' => 'new-password-123',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
$this->assertAuthenticatedAs($user);
|
||||
}
|
||||
|
||||
public function test_password_reset_link_is_not_sent_if_only_a_placeholder_user_with_the_email_exists(): void
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$placeholder = User::factory()->placeholder()->create();
|
||||
|
||||
$response = $this->post('/forgot-password', [
|
||||
'email' => $placeholder->email,
|
||||
]);
|
||||
|
||||
$response->assertSessionHasErrors('email');
|
||||
Notification::assertNothingSent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth;
|
||||
|
||||
use App\Auth\ActiveUserProvider;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
|
||||
#[CoversClass(ActiveUserProvider::class)]
|
||||
class ActiveUserProviderTest extends TestCaseWithDatabase
|
||||
{
|
||||
public function test_password_broker_uses_the_active_user_provider(): void
|
||||
{
|
||||
// Act
|
||||
$brokerProvider = Auth::createUserProvider(config('auth.passwords.users.provider'));
|
||||
|
||||
// Assert
|
||||
$this->assertInstanceOf(ActiveUserProvider::class, $brokerProvider);
|
||||
}
|
||||
|
||||
public function test_api_guard_uses_the_active_user_provider(): void
|
||||
{
|
||||
// Act
|
||||
$guardProvider = Auth::createUserProvider(config('auth.guards.api.provider'));
|
||||
|
||||
// Assert
|
||||
$this->assertInstanceOf(ActiveUserProvider::class, $guardProvider);
|
||||
}
|
||||
|
||||
public function test_web_guard_uses_the_active_user_provider(): void
|
||||
{
|
||||
// Act
|
||||
$guardProvider = Auth::createUserProvider(config('auth.guards.web.provider'));
|
||||
|
||||
// Assert
|
||||
$this->assertInstanceOf(ActiveUserProvider::class, $guardProvider);
|
||||
}
|
||||
|
||||
public function test_retrieve_by_credentials_ignores_placeholder_users_with_the_same_email(): void
|
||||
{
|
||||
// Arrange
|
||||
$email = 'shared@example.com';
|
||||
$placeholder = User::factory()->placeholder()->create(['email' => $email]);
|
||||
$user = User::factory()->create(['email' => $email]);
|
||||
$provider = Auth::createUserProvider('users');
|
||||
|
||||
// Act
|
||||
$result = $provider->retrieveByCredentials(['email' => $email]);
|
||||
|
||||
// Assert
|
||||
$this->assertInstanceOf(User::class, $result);
|
||||
$this->assertTrue($user->is($result));
|
||||
$this->assertFalse($placeholder->is($result));
|
||||
}
|
||||
|
||||
public function test_retrieve_by_credentials_returns_null_if_only_a_placeholder_user_exists(): void
|
||||
{
|
||||
// Arrange
|
||||
$email = 'placeholder-only@example.com';
|
||||
User::factory()->placeholder()->create(['email' => $email]);
|
||||
$provider = Auth::createUserProvider('users');
|
||||
|
||||
// Act
|
||||
$result = $provider->retrieveByCredentials(['email' => $email]);
|
||||
|
||||
// Assert
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
public function test_retrieve_by_id_returns_null_for_placeholder_users(): void
|
||||
{
|
||||
// Arrange
|
||||
$placeholder = User::factory()->placeholder()->create();
|
||||
$user = User::factory()->create();
|
||||
$provider = Auth::createUserProvider('users');
|
||||
|
||||
// Act
|
||||
$placeholderResult = $provider->retrieveById($placeholder->getKey());
|
||||
$userResult = $provider->retrieveById($user->getKey());
|
||||
|
||||
// Assert
|
||||
$this->assertNull($placeholderResult);
|
||||
$this->assertInstanceOf(User::class, $userResult);
|
||||
$this->assertTrue($user->is($userResult));
|
||||
}
|
||||
}
|
||||
@@ -97,29 +97,6 @@ class ImportEndpointTest extends ApiEndpointTestAbstract
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_import_fails_if_data_exceeds_maximum_size(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.max_data_size' => 16]);
|
||||
$user = $this->createUserWithPermission([
|
||||
'import',
|
||||
]);
|
||||
$this->mock(ImportService::class, function (MockInterface $mock): void {
|
||||
$mock->shouldNotReceive('import');
|
||||
});
|
||||
Passport::actingAs($user->user);
|
||||
|
||||
// Act
|
||||
$response = $this->postJson(route('api.v1.import.import', ['organization' => $user->organization->getKey()]), [
|
||||
'type' => 'toggl_time_entries',
|
||||
'data' => base64_encode(str_repeat('a', 15)),
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonValidationErrors(['data']);
|
||||
}
|
||||
|
||||
public function test_import_return_error_message_if_import_fails(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
@@ -105,9 +105,6 @@ class OrganizationInvitationEndpointTest extends EndpointTestAbstract
|
||||
$this->assertDatabaseMissing(OrganizationInvitation::class, [
|
||||
'id' => $invitation->getKey(),
|
||||
]);
|
||||
// Joining sets the organization as the current one for the user, independently of the
|
||||
// placeholders that were merged into them
|
||||
$this->assertSame($user->organization->getKey(), $user2->user->fresh()->current_team_id);
|
||||
}
|
||||
|
||||
public function test_accepting_invitation_while_logged_out_redirects_to_login(): void
|
||||
|
||||
@@ -53,23 +53,6 @@ class UserModelTest extends ModelTestAbstract
|
||||
$this->assertTrue($canAccess);
|
||||
}
|
||||
|
||||
public function test_placeholder_user_with_a_super_admin_email_can_not_access_admin_panel(): void
|
||||
{
|
||||
// Arrange
|
||||
Config::set('auth.super_admins', ['some@email.test', 'other@email.test']);
|
||||
$user = User::factory()->placeholder()->create([
|
||||
'email' => 'some@email.test',
|
||||
]);
|
||||
$panelProvider = new AdminPanelProvider(app());
|
||||
$mainPanel = $panelProvider->panel(Panel::make());
|
||||
|
||||
// Act
|
||||
$canAccess = $user->canAccessPanel($mainPanel);
|
||||
|
||||
// Assert
|
||||
$this->assertFalse($canAccess);
|
||||
}
|
||||
|
||||
public function test_scope_belongs_to_organization_returns_only_users_of_organization_including_owners(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
@@ -412,11 +412,10 @@ class DeletionServiceTest extends TestCaseWithDatabase
|
||||
$this->assertDatabaseHas(Organization::class, [
|
||||
'id' => $organizationOfA->getKey(),
|
||||
]);
|
||||
// The placeholder user should exist and must not reference the deleted organization,
|
||||
// which is what caused the foreign key violation in #989
|
||||
// The placeholder user should exist with current_team_id set to the org where they are a placeholder
|
||||
$placeholderUser = User::query()->where('is_placeholder', true)->first();
|
||||
$this->assertNotNull($placeholderUser);
|
||||
$this->assertNull($placeholderUser->current_team_id);
|
||||
$this->assertSame($organizationOfA->getKey(), $placeholderUser->current_team_id);
|
||||
$this->assertDatabaseHas(Member::class, [
|
||||
'id' => $memberBInOrgA->getKey(),
|
||||
'user_id' => $placeholderUser->getKey(),
|
||||
|
||||
@@ -41,7 +41,6 @@ class ImportServiceTest extends TestCase
|
||||
$this->assertSame(1, $report->usersCreated);
|
||||
$this->assertSame(2, $report->projectsCreated);
|
||||
$this->assertSame(1, $report->clientsCreated);
|
||||
Storage::disk(config('filesystems.default'))->assertDirectoryEmpty('import');
|
||||
}
|
||||
|
||||
public function test_import_releases_lock_if_an_exception_happens_during_the_import(): void
|
||||
|
||||
@@ -42,31 +42,6 @@ class SolidtimeImporterTest extends ImporterTestAbstract
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_import_throws_exception_if_zip_exceeds_uncompressed_size_limit(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.zip_max_uncompressed_size' => 10]);
|
||||
$zipPath = $this->createTestZip('solidtime_import_test_1');
|
||||
$timezone = 'Europe/Vienna';
|
||||
$organization = Organization::factory()->create();
|
||||
$importer = new SolidtimeImporter;
|
||||
$importer->init($organization);
|
||||
$data = file_get_contents($zipPath);
|
||||
|
||||
// Act
|
||||
try {
|
||||
$importer->importData($data, $timezone);
|
||||
} catch (Exception $e) {
|
||||
// Assert
|
||||
$this->assertInstanceOf(ImportException::class, $e);
|
||||
$this->assertSame('ZIP uncompressed size exceeds the maximum of 10 bytes', $e->getMessage());
|
||||
$this->assertSame(0, $importer->getReport()->timeEntriesCreated);
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_import_of_test_file_succeeds(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
@@ -39,31 +39,6 @@ class TogglDataImporterTest extends ImporterTestAbstract
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_import_throws_exception_if_zip_contains_too_many_files(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.zip_max_files' => 1]);
|
||||
$zipPath = $this->createTestZip('toggl_data_import_test_1');
|
||||
$timezone = 'Europe/Vienna';
|
||||
$organization = Organization::factory()->create();
|
||||
$importer = new TogglDataImporter;
|
||||
$importer->init($organization);
|
||||
$data = file_get_contents($zipPath);
|
||||
|
||||
// Act
|
||||
try {
|
||||
$importer->importData($data, $timezone);
|
||||
} catch (Exception $e) {
|
||||
// Assert
|
||||
$this->assertInstanceOf(ImportException::class, $e);
|
||||
$this->assertSame('ZIP contains too many files, maximum is 1', $e->getMessage());
|
||||
$this->assertSame(0, $importer->getReport()->projectsCreated);
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_import_of_test_file_succeeds(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Service\Import\Importers;
|
||||
|
||||
use App\Service\Import\Importers\ImportException;
|
||||
use App\Service\Import\Importers\ZipImportHelper;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
#[CoversClass(ZipImportHelper::class)]
|
||||
class ZipImportHelperTest extends TestCase
|
||||
{
|
||||
private TemporaryDirectory $sourceDirectory;
|
||||
|
||||
private TemporaryDirectory $targetDirectory;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->sourceDirectory = TemporaryDirectory::make();
|
||||
$this->targetDirectory = TemporaryDirectory::make();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->sourceDirectory->delete();
|
||||
$this->targetDirectory->delete();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $files
|
||||
*/
|
||||
private function createZip(array $files): string
|
||||
{
|
||||
$zipPath = $this->sourceDirectory->path('test.zip');
|
||||
$zip = new ZipArchive;
|
||||
$zip->open($zipPath, ZipArchive::CREATE);
|
||||
foreach ($files as $name => $content) {
|
||||
$zip->addFromString($name, $content);
|
||||
}
|
||||
$zip->close();
|
||||
|
||||
return $zipPath;
|
||||
}
|
||||
|
||||
private function assertNothingExtracted(): void
|
||||
{
|
||||
$this->assertSame([], array_values(array_diff(scandir($this->targetDirectory->path()), ['.', '..'])));
|
||||
}
|
||||
|
||||
public function test_extract_extracts_files_and_nested_directories(): void
|
||||
{
|
||||
// Arrange
|
||||
$zipPath = $this->createZip([
|
||||
'meta.json' => '{"version":"1.0"}',
|
||||
'nested/dir/file.csv' => 'a,b',
|
||||
]);
|
||||
|
||||
// Act
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
|
||||
// Assert
|
||||
$this->assertSame('{"version":"1.0"}', file_get_contents($this->targetDirectory->path('meta.json')));
|
||||
$this->assertSame('a,b', file_get_contents($this->targetDirectory->path('nested/dir/file.csv')));
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_file_is_not_a_zip(): void
|
||||
{
|
||||
// Arrange
|
||||
$path = $this->sourceDirectory->path('not-a-zip.txt');
|
||||
file_put_contents($path, 'not a zip');
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($path, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('Invalid ZIP, error code: 19', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_zip_contains_too_many_files(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.zip_max_files' => 2]);
|
||||
$zipPath = $this->createZip([
|
||||
'a.txt' => 'a',
|
||||
'b.txt' => 'b',
|
||||
'c.txt' => 'c',
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP contains too many files, maximum is 2', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_before_writing_if_declared_uncompressed_size_exceeds_limit(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.zip_max_uncompressed_size' => 100]);
|
||||
$zipPath = $this->createZip([
|
||||
'a.txt' => str_repeat('a', 60),
|
||||
'b.txt' => str_repeat('b', 60),
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP uncompressed size exceeds the maximum of 100 bytes', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_actual_uncompressed_size_exceeds_limit_despite_forged_headers(): void
|
||||
{
|
||||
// Arrange
|
||||
config(['import.zip_max_uncompressed_size' => 1000]);
|
||||
$zipPath = $this->createZip([
|
||||
'bomb.bin' => str_repeat("\0", 100000),
|
||||
]);
|
||||
// Forge the uncompressed size in the local file header (offset 22) and central directory header (offset 24)
|
||||
$content = file_get_contents($zipPath);
|
||||
$forgedSize = pack('V', 10);
|
||||
$localHeaderOffset = strpos($content, "PK\x03\x04");
|
||||
$centralHeaderOffset = strpos($content, "PK\x01\x02");
|
||||
$this->assertNotFalse($localHeaderOffset);
|
||||
$this->assertNotFalse($centralHeaderOffset);
|
||||
$content = substr_replace($content, $forgedSize, $localHeaderOffset + 22, 4);
|
||||
$content = substr_replace($content, $forgedSize, $centralHeaderOffset + 24, 4);
|
||||
file_put_contents($zipPath, $content);
|
||||
$zip = new ZipArchive;
|
||||
$this->assertTrue($zip->open($zipPath, ZipArchive::RDONLY));
|
||||
$this->assertSame(10, $zip->statIndex(0)['size']);
|
||||
$zip->close();
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP uncompressed size exceeds the maximum of 1000 bytes', $e->getMessage());
|
||||
$extracted = $this->targetDirectory->path('bomb.bin');
|
||||
if (file_exists($extracted)) {
|
||||
$this->assertLessThanOrEqual(1000, filesize($extracted));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_zip_contains_path_traversal(): void
|
||||
{
|
||||
// Arrange
|
||||
$zipPath = $this->createZip([
|
||||
'../evil.txt' => 'evil',
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP contains an invalid file path: "../evil.txt"', $e->getMessage());
|
||||
$this->assertFileDoesNotExist(dirname($this->targetDirectory->path()).'/evil.txt');
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_zip_contains_nested_path_traversal(): void
|
||||
{
|
||||
// Arrange
|
||||
$zipPath = $this->createZip([
|
||||
'sub/../../evil.txt' => 'evil',
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP contains an invalid file path: "sub/../../evil.txt"', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_zip_contains_absolute_path(): void
|
||||
{
|
||||
// Arrange
|
||||
$zipPath = $this->createZip([
|
||||
'/tmp/evil.txt' => 'evil',
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP contains an invalid file path: "/tmp/evil.txt"', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
|
||||
public function test_extract_throws_exception_if_zip_contains_backslash_path(): void
|
||||
{
|
||||
// Arrange
|
||||
$zipPath = $this->createZip([
|
||||
'..\\evil.txt' => 'evil',
|
||||
]);
|
||||
|
||||
// Act
|
||||
try {
|
||||
app(ZipImportHelper::class)->extract($zipPath, $this->targetDirectory->path());
|
||||
} catch (ImportException $e) {
|
||||
// Assert
|
||||
$this->assertSame('ZIP contains an invalid file path: "..\\evil.txt"', $e->getMessage());
|
||||
$this->assertNothingExtracted();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->fail();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ use App\Models\TimeEntry;
|
||||
use App\Models\User;
|
||||
use App\Service\MemberService;
|
||||
use App\Service\UserService;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use InvalidArgumentException;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
@@ -65,48 +64,6 @@ class MemberServiceTest extends TestCaseWithDatabase
|
||||
$this->assertSame(Role::Admin->value, $oldOwnerMember->refresh()->role);
|
||||
}
|
||||
|
||||
public function test_make_member_to_placeholder_does_not_copy_the_credentials_and_account_state_of_the_user(): void
|
||||
{
|
||||
// Arrange
|
||||
$user = User::factory()->create([
|
||||
'password' => Hash::make('secret-password'),
|
||||
'remember_token' => 'remember-me-token',
|
||||
'two_factor_secret' => 'two-factor-secret',
|
||||
'two_factor_recovery_codes' => 'two-factor-recovery-codes',
|
||||
'two_factor_confirmed_at' => '2026-09-16 10:00:00',
|
||||
'email_verified_at' => '2026-09-16 09:00:00',
|
||||
'pending_email' => 'pending@example.com',
|
||||
'profile_photo_path' => 'profile-photos/photo.png',
|
||||
]);
|
||||
$organization = Organization::factory()->create();
|
||||
$member = Member::factory()->forOrganization($organization)->forUser($user)->role(Role::Employee)->create();
|
||||
|
||||
// Act
|
||||
$this->memberService->makeMemberToPlaceholder($member);
|
||||
|
||||
// Assert
|
||||
$member->refresh();
|
||||
$placeholderUser = $member->user;
|
||||
$this->assertTrue($placeholderUser->is_placeholder);
|
||||
$this->assertSame($user->email, $placeholderUser->email);
|
||||
$this->assertNull($placeholderUser->password);
|
||||
$this->assertNull($placeholderUser->remember_token);
|
||||
$this->assertNull($placeholderUser->two_factor_secret);
|
||||
$this->assertNull($placeholderUser->two_factor_recovery_codes);
|
||||
$this->assertNull($placeholderUser->two_factor_confirmed_at);
|
||||
$this->assertNull($placeholderUser->email_verified_at);
|
||||
$this->assertNull($placeholderUser->pending_email);
|
||||
$this->assertNull($placeholderUser->current_team_id);
|
||||
$this->assertNull($placeholderUser->profile_photo_path);
|
||||
// the user the placeholder was created from keeps their own credentials and state
|
||||
$user->refresh();
|
||||
$this->assertTrue(Hash::check('secret-password', (string) $user->password));
|
||||
$this->assertSame('two-factor-secret', $user->two_factor_secret);
|
||||
$this->assertNotNull($user->email_verified_at);
|
||||
$this->assertSame('pending@example.com', $user->pending_email);
|
||||
$this->assertSame('profile-photos/photo.png', $user->profile_photo_path);
|
||||
}
|
||||
|
||||
public function test_make_member_to_placeholder_creates_new_user_based_on_member_and_changes_member_to_placeholder(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
Reference in New Issue
Block a user