mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-10-08 05:43:18 +01:00
Compare commits
18 Commits
feature/bi
...
d54296e66a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d54296e66a | ||
|
|
95ddbf9ead | ||
|
|
70646a0dd4 | ||
|
|
5b12c09747 | ||
|
|
24023353f2 | ||
|
|
720d20c10e | ||
|
|
82ea9af8b5 | ||
|
|
169d522da0 | ||
|
|
45c7377802 | ||
|
|
8e57275cef | ||
|
|
efc6b55628 | ||
|
|
c12789376d | ||
|
|
4795812b60 | ||
|
|
0e00979ab8 | ||
|
|
f1426fcb5e | ||
|
|
23f512d4a4 | ||
|
|
637475e669 | ||
|
|
3ec2abb309 |
@@ -5,7 +5,8 @@ APP_KEY=base64:UNQNf1SXeASNkWux01Rj8EnHYx8FO0kAxWNDwktclkk=
|
||||
APP_DEBUG=true
|
||||
APP_URL=https://solidtime.test
|
||||
APP_FORCE_HTTPS=false
|
||||
APP_ENABLE_REGISTRATION=true
|
||||
# Supported values: on, off, invite-only (true/false are supported for backwards compatibility)
|
||||
APP_ENABLE_REGISTRATION=on
|
||||
SUPER_ADMINS=admin@example.com
|
||||
PAGINATION_PER_PAGE_DEFAULT=500
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Actions\Fortify;
|
||||
|
||||
use App\Enums\RegistrationMode;
|
||||
use App\Enums\Weekday;
|
||||
use App\Events\NewsletterRegistered;
|
||||
use App\Models\User;
|
||||
use App\Service\InvitationService;
|
||||
use App\Service\IpLookup\IpLookupServiceContract;
|
||||
use App\Service\TimezoneService;
|
||||
use App\Service\UserService;
|
||||
@@ -31,13 +33,14 @@ class CreateNewUser implements CreatesNewUsers
|
||||
*/
|
||||
public function create(array $input): User
|
||||
{
|
||||
if (! config('app.enable_registration')) {
|
||||
$registrationMode = RegistrationMode::fromConfig(config('app.enable_registration'));
|
||||
if ($registrationMode === RegistrationMode::Off) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [__('Registration is disabled.')],
|
||||
]);
|
||||
}
|
||||
|
||||
Validator::make($input, [
|
||||
$validated = Validator::make($input, [
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
@@ -60,6 +63,20 @@ class CreateNewUser implements CreatesNewUsers
|
||||
],
|
||||
])->validate();
|
||||
|
||||
if ($registrationMode === RegistrationMode::InviteOnly) {
|
||||
$invitationService = app(InvitationService::class);
|
||||
$email = (string) $validated['email'];
|
||||
if (! $invitationService->hasAcceptedInvitationForEmail($email)) {
|
||||
$message = $invitationService->hasPendingInvitationForEmail($email)
|
||||
? __('Please accept the organization invitation sent to your email address before registering.')
|
||||
: __('Registration is only available to invited users.');
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [$message],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$timezone = null;
|
||||
if (array_key_exists('timezone', $input) && is_string($input['timezone'])) {
|
||||
if (app(TimezoneService::class)->isValid($input['timezone'])) {
|
||||
|
||||
37
app/Auth/ActiveUserProvider.php
Normal file
37
app/Auth/ActiveUserProvider.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
29
app/Enums/RegistrationMode.php
Normal file
29
app/Enums/RegistrationMode.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum RegistrationMode: string
|
||||
{
|
||||
case On = 'on';
|
||||
case InviteOnly = 'invite-only';
|
||||
case Off = 'off';
|
||||
|
||||
public static function fromConfig(mixed $value): self
|
||||
{
|
||||
if ($value === true) {
|
||||
return self::On;
|
||||
}
|
||||
|
||||
if ($value === false || $value === null) {
|
||||
return self::Off;
|
||||
}
|
||||
|
||||
return match (strtolower(trim((string) $value))) {
|
||||
'1', 'on', 'true' => self::On,
|
||||
'invite-only' => self::InviteOnly,
|
||||
default => self::Off,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ class OrganizationInvitationController extends Controller
|
||||
}
|
||||
|
||||
return redirect(route('register'))
|
||||
->with('registration_email', $email)
|
||||
->with('bannerText', __('Please create an account to finish joining the :organization organization.', [
|
||||
'organization' => $organization->name,
|
||||
]))
|
||||
|
||||
@@ -24,6 +24,7 @@ class ImportRequest extends BaseFormRequest
|
||||
'data' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:'.config('import.max_data_size'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -38,7 +38,10 @@ 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
|
||||
@@ -150,7 +153,9 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
|
||||
|
||||
public function canAccessPanel(Panel $panel): bool
|
||||
{
|
||||
return in_array($this->email, config('auth.super_admins', []), true) && $this->hasVerifiedEmail();
|
||||
return $this->is_placeholder === false
|
||||
&& in_array($this->email, config('auth.super_admins', []), true)
|
||||
&& $this->hasVerifiedEmail();
|
||||
}
|
||||
|
||||
public function isMemberOfOrganization(Organization $organization): bool
|
||||
|
||||
@@ -4,11 +4,14 @@ 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
|
||||
@@ -26,6 +29,13 @@ 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',
|
||||
|
||||
@@ -45,6 +45,7 @@ class FortifyServiceProvider extends ServiceProvider
|
||||
|
||||
Fortify::registerView(function () {
|
||||
return Inertia::render('Auth/Register', [
|
||||
'email' => session('registration_email', ''),
|
||||
'terms_url' => config('auth.terms_url'),
|
||||
'privacy_policy_url' => config('auth.privacy_policy_url'),
|
||||
'newsletter_consent' => config('auth.newsletter_consent'),
|
||||
|
||||
@@ -9,11 +9,8 @@ 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
|
||||
{
|
||||
@@ -25,8 +22,6 @@ 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,7 +16,6 @@ use Illuminate\Support\Str;
|
||||
use League\Csv\Reader;
|
||||
use Override;
|
||||
use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
use ZipArchive;
|
||||
|
||||
class SolidtimeImporter extends DefaultImporter
|
||||
{
|
||||
@@ -34,16 +33,10 @@ 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();
|
||||
$zip->extractTo($temporaryDirectory->path());
|
||||
$zip->close();
|
||||
app(ZipImportHelper::class)->extract($temporaryDirectoryZip->path('import.zip'), $temporaryDirectory->path());
|
||||
|
||||
if (! file_exists($temporaryDirectory->path('meta.json'))) {
|
||||
throw new ImportException('File "meta.json" missing in ZIP');
|
||||
|
||||
@@ -13,7 +13,6 @@ use Illuminate\Support\Str;
|
||||
use Override;
|
||||
use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
use ValueError;
|
||||
use ZipArchive;
|
||||
|
||||
class TogglDataImporter extends DefaultImporter
|
||||
{
|
||||
@@ -26,16 +25,10 @@ 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();
|
||||
$zip->extractTo($temporaryDirectory->path());
|
||||
$zip->close();
|
||||
app(ZipImportHelper::class)->extract($temporaryDirectoryZip->path('import.zip'), $temporaryDirectory->path());
|
||||
if (! file_exists($temporaryDirectory->path('clients.json'))) {
|
||||
throw new ImportException('File "clients.json" missing in ZIP');
|
||||
}
|
||||
|
||||
129
app/Service/Import/Importers/ZipImportHelper.php
Normal file
129
app/Service/Import/Importers/ZipImportHelper.php
Normal file
@@ -0,0 +1,129 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,22 @@ use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class InvitationService
|
||||
{
|
||||
public function hasAcceptedInvitationForEmail(string $email): bool
|
||||
{
|
||||
return OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($email)])
|
||||
->whereNotNull('accepted_at')
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function hasPendingInvitationForEmail(string $email): bool
|
||||
{
|
||||
return OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($email)])
|
||||
->whereNull('accepted_at')
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws UserIsAlreadyMemberOfOrganizationApiException|InvitationForTheEmailAlreadyExistsApiException
|
||||
*/
|
||||
|
||||
@@ -218,7 +218,16 @@ class MemberService
|
||||
|
||||
$placeholderUser = $user->replicate();
|
||||
$placeholderUser->is_placeholder = true;
|
||||
$placeholderUser->current_team_id = $member->organization_id;
|
||||
// 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->save();
|
||||
|
||||
$member->user()->associate($placeholderUser);
|
||||
|
||||
@@ -80,6 +80,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
@@ -147,6 +151,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
@@ -203,6 +211,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
|
||||
@@ -100,7 +100,7 @@ return [
|
||||
|
||||
'force_https' => (bool) env('APP_FORCE_HTTPS', false),
|
||||
|
||||
'enable_registration' => (bool) env('APP_ENABLE_REGISTRATION', false),
|
||||
'enable_registration' => env('APP_ENABLE_REGISTRATION', 'off'),
|
||||
|
||||
'local_email_verification' => (bool) env('APP_LOCAL_EMAIL_VERIFICATION', false),
|
||||
|
||||
|
||||
34
config/import.php
Normal file
34
config/import.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?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),
|
||||
|
||||
];
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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
|
||||
{
|
||||
//
|
||||
}
|
||||
};
|
||||
32
e2e/invitation-registration-prefill.spec.ts
Normal file
32
e2e/invitation-registration-prefill.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { getInvitationAcceptUrl } from './utils/mailpit';
|
||||
|
||||
test('prefills the registration email after accepting an invitation', async ({ page, browser }) => {
|
||||
const memberId = `${Date.now()}-${Math.floor(Math.random() * 100000)}`;
|
||||
const memberEmail = `prefill-${memberId}@invitation.test`;
|
||||
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
|
||||
await page.getByRole('button', { name: 'Invite Member' }).click();
|
||||
await page.getByPlaceholder('Member Email').fill(memberEmail);
|
||||
await page.getByRole('button', { name: 'Employee' }).click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/invitations') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 204
|
||||
),
|
||||
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
|
||||
]);
|
||||
|
||||
const inviteeContext = await browser.newContext();
|
||||
const inviteePage = await inviteeContext.newPage();
|
||||
const acceptUrl = await getInvitationAcceptUrl(inviteePage.request, memberEmail);
|
||||
await inviteePage.goto(acceptUrl);
|
||||
await inviteePage.waitForURL(/\/register$/);
|
||||
|
||||
await expect(inviteePage.getByLabel('Email')).toHaveValue(memberEmail);
|
||||
|
||||
await inviteeContext.close();
|
||||
});
|
||||
@@ -9,6 +9,6 @@
|
||||
},
|
||||
"Invoicing": {
|
||||
"repository": "solidtime-io/extension-invoicing",
|
||||
"ref": "v0.0.2"
|
||||
"ref": "v0.0.6"
|
||||
}
|
||||
}
|
||||
|
||||
2195
package-lock.json
generated
2195
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -57,7 +57,7 @@
|
||||
"@floating-ui/core": "^1.7.5",
|
||||
"@floating-ui/vue": "^1.1.11",
|
||||
"@heroicons/vue": "^2.2.0",
|
||||
"@lucide/vue": "^1.14.0",
|
||||
"@lucide/vue": "^1.28.0",
|
||||
"@rushstack/eslint-patch": "^1.16.1",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tanstack/vue-form": "^1.32.0",
|
||||
@@ -67,7 +67,7 @@
|
||||
"@tanstack/vue-virtual": "^3.13.24",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
"@vue/eslint-config-typescript": "^14.7.0",
|
||||
"@vueuse/core": "^14.3.0",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@vueuse/integrations": "^14.3.0",
|
||||
"@zodios/core": "^10.9.6",
|
||||
"chroma-js": "^3.2.0",
|
||||
@@ -79,7 +79,7 @@
|
||||
"parse-duration": "^2.1.6",
|
||||
"pinia": "^3.0.4",
|
||||
"radix-vue": "^1.9.17",
|
||||
"reka-ui": "^2.9.7",
|
||||
"reka-ui": "^2.10.1",
|
||||
"tailwind-merge": "^2.6.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vue-draggable-plus": "^0.6.1",
|
||||
|
||||
@@ -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 '@/Components/Common/Pagination.vue';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import { canCreateClients } from '@/utils/permissions';
|
||||
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
||||
import {
|
||||
|
||||
@@ -6,17 +6,11 @@ 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 '@/Components/Common/Pagination.vue';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
|
||||
|
||||
export type SortColumn =
|
||||
| 'name'
|
||||
| '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';
|
||||
|
||||
@@ -63,7 +63,7 @@ const max = computed(() => {
|
||||
});
|
||||
|
||||
const backgroundColor = useCssVariable('--theme-color-card-background');
|
||||
const borderColor = useCssVariable('--color-border');
|
||||
const borderColor = useCssVariable('--color-border-secondary');
|
||||
const labelColor = useCssVariable('--color-text-secondary');
|
||||
const chartColorRaw = useCssVariable('--theme-color-chart');
|
||||
|
||||
|
||||
@@ -146,7 +146,10 @@ const changeSummary = computed<PlanLine[]>(() => {
|
||||
{ times: range(plan.breakSlot), label: 'Break' },
|
||||
{ times: range(plan.secondHalf), label: workLabel },
|
||||
...plan.shifted.map((shift) => ({
|
||||
times: moved(req.otherEntries.find((e) => e.id === shift.id)!, shift),
|
||||
times: moved(
|
||||
req.otherEntries.find((e) => e.id === shift.id)!,
|
||||
shift
|
||||
),
|
||||
label: props.entryLabel(shift.id),
|
||||
})),
|
||||
];
|
||||
|
||||
@@ -161,7 +161,7 @@ const emit = defineEmits<{
|
||||
:organization-billable-rate="organization?.billable_rate ?? null"
|
||||
:no-project-value="null"
|
||||
align="start"
|
||||
@changed="(p, t) => emit('add-row', p, t)">
|
||||
@changed="(p: string | null, t: string | null) => emit('add-row', p, t)">
|
||||
<template #trigger>
|
||||
<Button variant="ghost" size="sm" class="text-text-secondary">
|
||||
<PlusIcon class="h-4 w-4 mr-1 text-icon-default" />
|
||||
|
||||
@@ -25,16 +25,21 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
<template>
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay
|
||||
class="fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
|
||||
<AlertDialogContent
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 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 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
props.class
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</AlertDialogContent>
|
||||
class="fixed inset-0 z-50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0">
|
||||
<div class="absolute inset-0 bg-default-background opacity-30" />
|
||||
</AlertDialogOverlay>
|
||||
<div
|
||||
class="fixed top-0 left-0 z-50 pointer-events-none w-screen h-screen flex items-start px-2 pt-3 md:pt-14 xl:pt-24 justify-center overflow-auto">
|
||||
<AlertDialogContent
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'pointer-events-auto bg-default-background grid w-full max-w-lg gap-4 border border-border-tertiary p-6 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
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</AlertDialogContent>
|
||||
</div>
|
||||
</AlertDialogPortal>
|
||||
</template>
|
||||
|
||||
@@ -253,7 +253,9 @@ const page = usePage<{
|
||||
v-if="isInvoicingActivated() && canViewInvoices()"
|
||||
title="Invoices"
|
||||
:icon="DocumentTextIcon"
|
||||
:current="route().current('invoices')"
|
||||
:current="
|
||||
route().current('invoices') || route().current('invoices.*')
|
||||
"
|
||||
href="/invoices"></NavigationSidebarItem>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
@@ -8,9 +8,13 @@ import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
|
||||
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
email: string;
|
||||
}>();
|
||||
|
||||
const form = useForm({
|
||||
name: '',
|
||||
email: '',
|
||||
email: props.email,
|
||||
password: '',
|
||||
password_confirmation: '',
|
||||
terms: false,
|
||||
|
||||
@@ -35,8 +35,7 @@ async function deleteUser() {
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = error.response as
|
||||
| { status?: number; data?: { errors?: { password?: string[] } } }
|
||||
| undefined;
|
||||
{ status?: number; data?: { errors?: { password?: string[] } } } | undefined;
|
||||
if (response?.status === 422) {
|
||||
passwordError.value = response.data?.errors?.password?.[0] ?? 'Invalid password.';
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
ArrowDownTrayIcon,
|
||||
LockClosedIcon,
|
||||
} from '@heroicons/vue/20/solid';
|
||||
import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import Pagination from '@/packages/ui/src/Pagination.vue';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
|
||||
@@ -38,8 +38,7 @@ const deleteTeam = async () => {
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const response = error.response as
|
||||
| { status?: number; data?: { errors?: { password?: string[] } } }
|
||||
| undefined;
|
||||
{ status?: number; data?: { errors?: { password?: string[] } } } | undefined;
|
||||
if (response?.status === 422) {
|
||||
passwordError.value = response.data?.errors?.password?.[0] ?? 'Invalid password.';
|
||||
}
|
||||
|
||||
@@ -118,6 +118,11 @@ export type DetailedInvoiceResponse = ZodiosResponseByAlias<SolidTimeApi, 'getIn
|
||||
export type DetailedInvoice = DetailedInvoiceResponse['data'];
|
||||
|
||||
export type InvoiceIndexEntry = ZodiosResponseByAlias<SolidTimeApi, 'getInvoices'>['data'][0];
|
||||
export type InvoiceRecipient = ZodiosResponseByAlias<
|
||||
SolidTimeApi,
|
||||
'getInvoiceRecipients'
|
||||
>['data'][0];
|
||||
export type InvoiceRecipientBody = ZodiosBodyByAlias<SolidTimeApi, 'createInvoiceRecipient'>;
|
||||
|
||||
export type UpdateInvoiceSettings = ZodiosBodyByAlias<SolidTimeApi, 'updateInvoiceSettings'>;
|
||||
|
||||
|
||||
@@ -45,14 +45,54 @@ const InvitationResource = z
|
||||
const InvitationStoreRequest = z
|
||||
.object({ email: z.string().email(), role: z.enum(['admin', 'manager', 'employee']) })
|
||||
.passthrough();
|
||||
const InvoiceRecipientResource = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
organization_id: z.string(),
|
||||
name: z.string(),
|
||||
vatin: z.union([z.string(), z.null()]),
|
||||
address_line_1: z.union([z.string(), z.null()]),
|
||||
address_line_2: z.union([z.string(), z.null()]),
|
||||
address_line_3: z.union([z.string(), z.null()]),
|
||||
address_post_code: z.union([z.string(), z.null()]),
|
||||
address_city: z.union([z.string(), z.null()]),
|
||||
address_country: z.union([z.string(), z.null()]),
|
||||
phone: z.union([z.string(), z.null()]),
|
||||
email: z.union([z.string(), z.null()]),
|
||||
is_archived: z.boolean(),
|
||||
archived_at: z.union([z.string(), z.null()]),
|
||||
invoices_count: z.number().int(),
|
||||
has_non_draft_invoices: z.boolean(),
|
||||
created_at: z.union([z.string(), z.null()]),
|
||||
updated_at: z.union([z.string(), z.null()]),
|
||||
})
|
||||
.passthrough();
|
||||
const InvoiceRecipientCollection = z.array(InvoiceRecipientResource);
|
||||
const InvoiceRecipientRequest = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
vatin: z.union([z.string(), z.null()]).optional(),
|
||||
address_line_1: z.union([z.string(), z.null()]).optional(),
|
||||
address_line_2: z.union([z.string(), z.null()]).optional(),
|
||||
address_line_3: z.union([z.string(), z.null()]).optional(),
|
||||
address_post_code: z.union([z.string(), z.null()]).optional(),
|
||||
address_city: z.union([z.string(), z.null()]).optional(),
|
||||
address_country: z.union([z.string(), z.null()]).optional(),
|
||||
phone: z.union([z.string(), z.null()]).optional(),
|
||||
email: z.union([z.string(), z.null()]).optional(),
|
||||
is_archived: z.boolean().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const InvoiceResource = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
organization_id: z.string(),
|
||||
invoice_recipient_id: z.string(),
|
||||
reference: z.string(),
|
||||
seller_name: z.string(),
|
||||
buyer_name: z.string(),
|
||||
recipient: z.string(),
|
||||
status: z.string(),
|
||||
status_label: z.string(),
|
||||
date: z.string(),
|
||||
due_at: z.string(),
|
||||
paid_date: z.string(),
|
||||
@@ -76,16 +116,7 @@ const InvoiceStoreRequest = z
|
||||
seller_address_country: z.union([z.string(), z.null()]).optional(),
|
||||
seller_phone: z.union([z.string(), z.null()]).optional(),
|
||||
seller_email: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_name: z.string(),
|
||||
buyer_vatin: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_line_1: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_line_2: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_line_3: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_post_code: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_city: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_address_country: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_phone: z.union([z.string(), z.null()]).optional(),
|
||||
buyer_email: z.union([z.string(), z.null()]).optional(),
|
||||
invoice_recipient_id: z.string(),
|
||||
date: z.string(),
|
||||
billing_period_start: z.union([z.string(), z.null()]).optional(),
|
||||
billing_period_end: z.union([z.string(), z.null()]).optional(),
|
||||
@@ -130,6 +161,7 @@ const DetailedInvoiceResource = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
organization_id: z.string(),
|
||||
invoice_recipient_id: z.string(),
|
||||
reference: z.string(),
|
||||
seller_name: z.string(),
|
||||
seller_vatin: z.string(),
|
||||
@@ -141,16 +173,7 @@ const DetailedInvoiceResource = z
|
||||
seller_address_country: z.string(),
|
||||
seller_phone: z.string(),
|
||||
seller_email: z.string(),
|
||||
buyer_name: z.string(),
|
||||
buyer_vatin: z.string(),
|
||||
buyer_address_line_1: z.string(),
|
||||
buyer_address_line_2: z.string(),
|
||||
buyer_address_line_3: z.string(),
|
||||
buyer_address_post_code: z.string(),
|
||||
buyer_address_city: z.string(),
|
||||
buyer_address_country: z.string(),
|
||||
buyer_phone: z.string(),
|
||||
buyer_email: z.string(),
|
||||
recipient: InvoiceRecipientResource,
|
||||
paid_date: z.string(),
|
||||
due_at: z.string(),
|
||||
discount_type: z.string(),
|
||||
@@ -171,7 +194,7 @@ const DetailedInvoiceResource = z
|
||||
entries: z.array(InvoiceEntryResource),
|
||||
})
|
||||
.passthrough();
|
||||
const InvoiceStatus = z.enum(['draft', 'sent', 'cancelled']);
|
||||
const InvoiceStatus = z.enum(['draft', 'sent', 'paid', 'cancelled']);
|
||||
const InvoiceUpdateRequest = z
|
||||
.object({
|
||||
status: InvoiceStatus,
|
||||
@@ -187,16 +210,7 @@ const InvoiceUpdateRequest = z
|
||||
seller_address_country: z.union([z.string(), z.null()]),
|
||||
seller_phone: z.union([z.string(), z.null()]),
|
||||
seller_email: z.union([z.string(), z.null()]),
|
||||
buyer_name: z.string(),
|
||||
buyer_vatin: z.union([z.string(), z.null()]),
|
||||
buyer_address_line_1: z.union([z.string(), z.null()]),
|
||||
buyer_address_line_2: z.union([z.string(), z.null()]),
|
||||
buyer_address_line_3: z.union([z.string(), z.null()]),
|
||||
buyer_address_post_code: z.union([z.string(), z.null()]),
|
||||
buyer_address_city: z.union([z.string(), z.null()]),
|
||||
buyer_address_country: z.union([z.string(), z.null()]),
|
||||
buyer_phone: z.union([z.string(), z.null()]),
|
||||
buyer_email: z.union([z.string(), z.null()]),
|
||||
invoice_recipient_id: z.string(),
|
||||
date: z.string(),
|
||||
billing_period_start: z.union([z.string(), z.null()]),
|
||||
billing_period_end: z.union([z.string(), z.null()]),
|
||||
@@ -1897,6 +1911,125 @@ const endpoints = makeApi([
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
method: 'get',
|
||||
path: '/v1/organizations/:organization/invoice-recipients',
|
||||
alias: 'getInvoiceRecipients',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceRecipientCollection }).passthrough(),
|
||||
},
|
||||
{
|
||||
method: 'post',
|
||||
path: '/v1/organizations/:organization/invoice-recipients',
|
||||
alias: 'createInvoiceRecipient',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'body',
|
||||
type: 'Body',
|
||||
schema: InvoiceRecipientRequest,
|
||||
},
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceRecipientResource }).passthrough(),
|
||||
},
|
||||
{
|
||||
method: 'get',
|
||||
path: '/v1/organizations/:organization/invoice-recipients/:invoiceRecipient',
|
||||
alias: 'getInvoiceRecipient',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
{
|
||||
name: 'invoiceRecipient',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceRecipientResource }).passthrough(),
|
||||
},
|
||||
{
|
||||
method: 'put',
|
||||
path: '/v1/organizations/:organization/invoice-recipients/:invoiceRecipient',
|
||||
alias: 'updateInvoiceRecipient',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'body',
|
||||
type: 'Body',
|
||||
schema: InvoiceRecipientRequest,
|
||||
},
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
{
|
||||
name: 'invoiceRecipient',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceRecipientResource }).passthrough(),
|
||||
},
|
||||
{
|
||||
method: 'post',
|
||||
path: '/v1/organizations/:organization/invoice-recipients/:invoiceRecipient/duplicate',
|
||||
alias: 'duplicateInvoiceRecipient',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'body',
|
||||
type: 'Body',
|
||||
schema: InvoiceRecipientRequest,
|
||||
},
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
{
|
||||
name: 'invoiceRecipient',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceRecipientResource }).passthrough(),
|
||||
},
|
||||
{
|
||||
method: 'delete',
|
||||
path: '/v1/organizations/:organization/invoice-recipients/:invoiceRecipient',
|
||||
alias: 'deleteInvoiceRecipient',
|
||||
requestFormat: 'json',
|
||||
parameters: [
|
||||
{
|
||||
name: 'organization',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
{
|
||||
name: 'invoiceRecipient',
|
||||
type: 'Path',
|
||||
schema: z.string(),
|
||||
},
|
||||
],
|
||||
response: z.void(),
|
||||
},
|
||||
{
|
||||
method: 'get',
|
||||
path: '/v1/organizations/:organization/invoices',
|
||||
@@ -1913,6 +2046,11 @@ const endpoints = makeApi([
|
||||
type: 'Query',
|
||||
schema: z.number().int().gte(1).lte(2147483647).optional(),
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
type: 'Query',
|
||||
schema: InvoiceStatus.optional(),
|
||||
},
|
||||
],
|
||||
response: z.object({ data: InvoiceCollection }).passthrough(),
|
||||
errors: [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@solidtime/ui",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"description": "Package containing the solidtime ui components",
|
||||
"main": "./dist/solidtime-ui-lib.umd.cjs",
|
||||
"module": "./dist/solidtime-ui-lib.js",
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
CommandShortcut,
|
||||
} from '../command';
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import type {
|
||||
CommandPaletteCommand,
|
||||
CommandPaletteGroup,
|
||||
@@ -36,6 +37,8 @@ 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));
|
||||
|
||||
@@ -71,7 +74,9 @@ 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">
|
||||
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">
|
||||
<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">
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/packages/ui/src/tooltip';
|
||||
const active = defineModel({ default: false });
|
||||
const active = defineModel<boolean>({ default: false });
|
||||
const emit = defineEmits(['changed']);
|
||||
function toggleBillable() {
|
||||
active.value = !active.value;
|
||||
|
||||
@@ -16,7 +16,7 @@ const props = withDefaults(
|
||||
);
|
||||
|
||||
const emit = defineEmits(['open', 'submit']);
|
||||
const open = defineModel({ default: false });
|
||||
const open = defineModel<boolean>({ default: false });
|
||||
|
||||
function handleAutofocus(event: Event) {
|
||||
if (props.autoFocus === false) {
|
||||
|
||||
@@ -13,11 +13,11 @@ import { type ComputedRef } from 'vue';
|
||||
|
||||
const temporaryCustomTimerEntry = ref<string>('');
|
||||
|
||||
const start = defineModel('start', {
|
||||
const start = defineModel<string>('start', {
|
||||
default: '',
|
||||
});
|
||||
|
||||
const end = defineModel('end', {
|
||||
const end = defineModel<string>('end', {
|
||||
default: '',
|
||||
});
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ const NONE_ID = 'none';
|
||||
const ROW_HEIGHT = 32;
|
||||
|
||||
const model = defineModel<string[]>({
|
||||
default: [],
|
||||
default: () => [],
|
||||
});
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
ChevronRightIcon,
|
||||
EllipsisHorizontalIcon,
|
||||
} from '@heroicons/vue/20/solid';
|
||||
import { buttonVariants } from '@/packages/ui/src';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { buttonVariants } from './Buttons/index';
|
||||
import { cn } from './utils/cn';
|
||||
import { computed, watch } from 'vue';
|
||||
|
||||
const page = defineModel<number>('page', { default: 1 });
|
||||
@@ -32,7 +32,7 @@ const props = withDefaults(
|
||||
);
|
||||
|
||||
const model = defineModel<string[]>({
|
||||
default: [],
|
||||
default: () => [],
|
||||
});
|
||||
|
||||
const open = ref(false);
|
||||
|
||||
@@ -21,7 +21,7 @@ import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
|
||||
import type { TimeEntriesGroupedByType } from '@/types/time-entries';
|
||||
|
||||
const selectedTimeEntries = defineModel<TimeEntry[]>('selected', {
|
||||
default: [],
|
||||
default: () => [],
|
||||
});
|
||||
|
||||
const props = withDefaults(
|
||||
|
||||
@@ -20,7 +20,7 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const model = defineModel<string[]>({
|
||||
default: [],
|
||||
default: () => [],
|
||||
});
|
||||
|
||||
const timeEntryTags = computed<Tag[]>(() => {
|
||||
|
||||
@@ -10,7 +10,7 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const model = defineModel<string[]>({
|
||||
default: [],
|
||||
default: () => [],
|
||||
});
|
||||
const iconColorClasses = computed(() => {
|
||||
if (model.value.length > 0) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { getUserTimezone } from './utils/settings';
|
||||
import { getDayJsInstance } from './utils/time';
|
||||
import { useSessionStorage } from '@vueuse/core';
|
||||
|
||||
const show = defineModel('show', { default: false });
|
||||
const show = defineModel<boolean>('show', { default: false });
|
||||
|
||||
const emit = defineEmits<{
|
||||
update: [timezone: string];
|
||||
|
||||
25
resources/js/packages/ui/src/combobox/Combobox.vue
Normal file
25
resources/js/packages/ui/src/combobox/Combobox.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxRootEmits, ComboboxRootProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxRoot, useForwardPropsEmits } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxRootProps & { class?: HTMLAttributes['class'] }>();
|
||||
const emits = defineEmits<ComboboxRootEmits>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Keep the trigger inside this root. Reka treats anything within the root
|
||||
element as "not outside", so it suppresses its own dismissal for trigger
|
||||
clicks and ComboboxInput's blur-close ignores them. Putting the trigger
|
||||
in a separate Popover instead gives two competing open states, and the
|
||||
popover then closes on mousedown and reopens on the following click. -->
|
||||
<ComboboxRoot v-slot="slotProps" v-bind="forwarded" :class="cn('min-w-0', props.class)">
|
||||
<slot v-bind="slotProps" />
|
||||
</ComboboxRoot>
|
||||
</template>
|
||||
19
resources/js/packages/ui/src/combobox/ComboboxAnchor.vue
Normal file
19
resources/js/packages/ui/src/combobox/ComboboxAnchor.vue
Normal file
@@ -0,0 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxAnchorProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxAnchor, useForwardProps } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxAnchorProps & { class?: HTMLAttributes['class'] }>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardProps(delegatedProps);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ComboboxAnchor v-bind="forwarded" :class="cn('w-full', props.class)">
|
||||
<slot />
|
||||
</ComboboxAnchor>
|
||||
</template>
|
||||
35
resources/js/packages/ui/src/combobox/ComboboxInput.vue
Normal file
35
resources/js/packages/ui/src/combobox/ComboboxInput.vue
Normal file
@@ -0,0 +1,35 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxInputEmits, ComboboxInputProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { Search } from '@lucide/vue';
|
||||
import { ComboboxInput, useForwardPropsEmits } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false,
|
||||
});
|
||||
|
||||
const props = defineProps<ComboboxInputProps & { class?: HTMLAttributes['class'] }>();
|
||||
const emits = defineEmits<ComboboxInputEmits>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative items-center border-b border-card-background-separator">
|
||||
<ComboboxInput
|
||||
v-bind="{ ...$attrs, ...forwarded }"
|
||||
:class="
|
||||
cn(
|
||||
'h-10 w-full border-0 rounded-none bg-transparent pl-9 pr-3 text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:ring-0',
|
||||
props.class
|
||||
)
|
||||
" />
|
||||
<span class="absolute start-0 inset-y-0 flex items-center justify-center px-3">
|
||||
<Search class="size-4 text-text-tertiary" />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
27
resources/js/packages/ui/src/combobox/ComboboxItem.vue
Normal file
27
resources/js/packages/ui/src/combobox/ComboboxItem.vue
Normal file
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxItemEmits, ComboboxItemProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxItem, useForwardPropsEmits } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxItemProps & { class?: HTMLAttributes['class'] }>();
|
||||
const emits = defineEmits<ComboboxItemEmits>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ComboboxItem
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'flex w-full cursor-default items-center rounded-md px-2 py-1.5 text-sm text-text-primary data-[highlighted]:bg-card-background-active',
|
||||
props.class
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</ComboboxItem>
|
||||
</template>
|
||||
41
resources/js/packages/ui/src/combobox/ComboboxList.vue
Normal file
41
resources/js/packages/ui/src/combobox/ComboboxList.vue
Normal file
@@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxContentEmits, ComboboxContentProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxContent, ComboboxPortal, useForwardPropsEmits } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false,
|
||||
});
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<ComboboxContentProps & { class?: HTMLAttributes['class'] }>(),
|
||||
{
|
||||
position: 'popper',
|
||||
align: 'start',
|
||||
sideOffset: 4,
|
||||
class: undefined,
|
||||
}
|
||||
);
|
||||
const emits = defineEmits<ComboboxContentEmits>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ComboboxPortal>
|
||||
<ComboboxContent
|
||||
v-bind="{ ...$attrs, ...forwarded }"
|
||||
:class="
|
||||
cn(
|
||||
'z-50 w-[--reka-popper-anchor-width] min-w-60 overflow-hidden rounded-lg border border-popover-border bg-popover text-popover-foreground shadow-dropdown outline-none origin-[var(--reka-combobox-content-transform-origin)] 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
props.class
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</ComboboxContent>
|
||||
</ComboboxPortal>
|
||||
</template>
|
||||
19
resources/js/packages/ui/src/combobox/ComboboxSeparator.vue
Normal file
19
resources/js/packages/ui/src/combobox/ComboboxSeparator.vue
Normal file
@@ -0,0 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxSeparatorProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxSeparator, useForwardProps } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxSeparatorProps & { class?: HTMLAttributes['class'] }>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardProps(delegatedProps);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ComboboxSeparator
|
||||
v-bind="forwarded"
|
||||
:class="cn('my-1 h-px bg-card-background-separator', props.class)" />
|
||||
</template>
|
||||
29
resources/js/packages/ui/src/combobox/ComboboxTrigger.vue
Normal file
29
resources/js/packages/ui/src/combobox/ComboboxTrigger.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxTriggerProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxTrigger, useForwardProps } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxTriggerProps & { class?: HTMLAttributes['class'] }>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardProps(delegatedProps);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Reka hardcodes tabindex="-1" here because it expects a ComboboxInput
|
||||
next to the trigger in the anchor to be the focusable control. Our input
|
||||
lives inside ComboboxList, so this trigger is the control and has to be
|
||||
tabbable. tabindex is a fallthrough attr, which Vue applies after Reka's
|
||||
own props and therefore wins.
|
||||
|
||||
Reka also hardcodes aria-label="Show popup", which would otherwise be
|
||||
the accessible name. Pass :aria-label on the child element (it wins
|
||||
again, because Slot merges child props over attrs) to name the trigger
|
||||
after its current value. -->
|
||||
<ComboboxTrigger v-bind="forwarded" :class="cn(props.class)" tabindex="0">
|
||||
<slot />
|
||||
</ComboboxTrigger>
|
||||
</template>
|
||||
38
resources/js/packages/ui/src/combobox/ComboboxViewport.vue
Normal file
38
resources/js/packages/ui/src/combobox/ComboboxViewport.vue
Normal file
@@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
import type { ComboboxViewportProps } from 'reka-ui';
|
||||
import type { HTMLAttributes } from 'vue';
|
||||
import { reactiveOmit } from '@vueuse/core';
|
||||
import { ComboboxViewport, useForwardProps } from 'reka-ui';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
const props = defineProps<ComboboxViewportProps & { class?: HTMLAttributes['class'] }>();
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class');
|
||||
|
||||
const forwarded = useForwardProps(delegatedProps);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ComboboxViewport
|
||||
v-bind="forwarded"
|
||||
:class="cn('ui-combobox-viewport max-h-60 overflow-y-auto p-2', props.class)">
|
||||
<slot />
|
||||
</ComboboxViewport>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* Reka's ComboboxViewport injects a global style that hides scrollbars; the
|
||||
attribute+class selector below is more specific and restores them. */
|
||||
[data-reka-combobox-viewport].ui-combobox-viewport {
|
||||
scrollbar-width: thin;
|
||||
-ms-overflow-style: auto;
|
||||
}
|
||||
[data-reka-combobox-viewport].ui-combobox-viewport::-webkit-scrollbar {
|
||||
display: block;
|
||||
width: 8px;
|
||||
}
|
||||
[data-reka-combobox-viewport].ui-combobox-viewport::-webkit-scrollbar-thumb {
|
||||
background-color: rgb(127 127 127 / 0.4);
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
||||
9
resources/js/packages/ui/src/combobox/index.ts
Normal file
9
resources/js/packages/ui/src/combobox/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { default as Combobox } from './Combobox.vue';
|
||||
export { default as ComboboxAnchor } from './ComboboxAnchor.vue';
|
||||
export { default as ComboboxInput } from './ComboboxInput.vue';
|
||||
export { default as ComboboxItem } from './ComboboxItem.vue';
|
||||
export { default as ComboboxList } from './ComboboxList.vue';
|
||||
export { default as ComboboxSeparator } from './ComboboxSeparator.vue';
|
||||
export { default as ComboboxTrigger } from './ComboboxTrigger.vue';
|
||||
export { default as ComboboxViewport } from './ComboboxViewport.vue';
|
||||
export { ComboboxVirtualizer } from 'reka-ui';
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import {
|
||||
DialogContent,
|
||||
type DialogContentEmits,
|
||||
@@ -20,6 +21,10 @@ 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>
|
||||
@@ -36,7 +41,9 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
'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,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { cn } from '../utils/cn';
|
||||
import { useDialogFocusRestore } from '../utils/useDialogFocusRestore';
|
||||
import { X } from '@lucide/vue';
|
||||
import {
|
||||
DialogClose,
|
||||
@@ -22,6 +23,10 @@ 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>
|
||||
@@ -36,6 +41,8 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
)
|
||||
"
|
||||
v-bind="forwarded"
|
||||
@open-auto-focus="onOpenAutoFocus"
|
||||
@close-auto-focus="onCloseAutoFocus"
|
||||
@pointer-down-outside="
|
||||
(event) => {
|
||||
const originalEvent = event.detail.originalEvent;
|
||||
|
||||
@@ -32,6 +32,7 @@ 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';
|
||||
@@ -57,6 +58,16 @@ import {
|
||||
CalendarNextButton,
|
||||
CalendarPrevButton,
|
||||
} from './calendar/index';
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxAnchor,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxSeparator,
|
||||
ComboboxTrigger,
|
||||
ComboboxViewport,
|
||||
} from './combobox/index';
|
||||
import { CommandPalette } from './CommandPalette/index';
|
||||
import {
|
||||
ContextMenu,
|
||||
@@ -176,6 +187,14 @@ export {
|
||||
CardTitle,
|
||||
Checkbox,
|
||||
color,
|
||||
Combobox,
|
||||
ComboboxAnchor,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxSeparator,
|
||||
ComboboxTrigger,
|
||||
ComboboxViewport,
|
||||
CommandPalette,
|
||||
ContextMenu,
|
||||
ContextMenuCheckboxItem,
|
||||
@@ -239,6 +258,7 @@ export {
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
Pagination,
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
|
||||
@@ -43,6 +43,13 @@ export function formatCents(
|
||||
return formatMoney(amount / 100, currency, format, currencySymbol, numberFormat);
|
||||
}
|
||||
|
||||
/*
|
||||
* Converts a major-unit amount (e.g. 19.99) to integer hundredths (i.e. cents)
|
||||
*/
|
||||
export function toCents(value: number | undefined | null): number {
|
||||
return Math.round((value || 0) * 100);
|
||||
}
|
||||
|
||||
export function getOrganizationCurrencySymbol(currency: string) {
|
||||
return (0)
|
||||
.toLocaleString('de-DE', {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
export type NumberFormat =
|
||||
| 'point-comma'
|
||||
| 'comma-point'
|
||||
| 'space-comma'
|
||||
| 'space-point'
|
||||
| 'apostrophe-point';
|
||||
'point-comma' | 'comma-point' | 'space-comma' | 'space-point' | 'apostrophe-point';
|
||||
|
||||
/**
|
||||
* Formats a number according to the specified format
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
41
resources/js/packages/ui/src/utils/useDialogFocusRestore.ts
Normal file
41
resources/js/packages/ui/src/utils/useDialogFocusRestore.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 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 };
|
||||
}
|
||||
@@ -23,6 +23,21 @@ export function getApiValidationFieldErrors(error: unknown): Record<string, stri
|
||||
return fieldErrors;
|
||||
}
|
||||
|
||||
/*
|
||||
* Like getApiValidationFieldErrors, but with Laravel's dot-notation array
|
||||
* indices (entries.0.unit_price) converted to the bracket notation of
|
||||
* TanStack Form field names (entries[0].unit_price), so that the errors
|
||||
* attach to the mounted fields.
|
||||
*/
|
||||
export function getApiValidationFormFieldErrors(error: unknown): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(getApiValidationFieldErrors(error)).map(([field, message]) => [
|
||||
field.replace(/\.(\d+)(?=\.|$)/g, '[$1]'),
|
||||
message,
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
export function getApiValidationMessage(error: unknown, fallback: string): string {
|
||||
if (!isApiValidationError(error)) {
|
||||
return fallback;
|
||||
|
||||
@@ -27,13 +27,7 @@ import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
||||
import type { Organization } from '@/types/models';
|
||||
|
||||
export type CommandGroup =
|
||||
| 'timer'
|
||||
| 'active-timer'
|
||||
| 'navigation'
|
||||
| 'create'
|
||||
| 'theme'
|
||||
| 'organization'
|
||||
| 'entity';
|
||||
'timer' | 'active-timer' | 'navigation' | 'create' | 'theme' | 'organization' | 'entity';
|
||||
|
||||
export interface Command {
|
||||
id: string;
|
||||
|
||||
@@ -385,21 +385,19 @@ export function useCommandPalette() {
|
||||
const matching = projects.value
|
||||
.filter((p: Project) => p.name.toLowerCase().includes(query))
|
||||
.slice(0, maxPerType)
|
||||
.map(
|
||||
(p: Project): EntitySearchResult => ({
|
||||
id: `entity-project-${p.id}`,
|
||||
label: p.name,
|
||||
icon: ENTITY_ICONS.project,
|
||||
keywords: ['project'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('projects.show', { project: p.id }));
|
||||
},
|
||||
entityType: 'project',
|
||||
color: p.color,
|
||||
badgeClass: ENTITY_BADGE_CLASSES.project,
|
||||
})
|
||||
);
|
||||
.map((p: Project): EntitySearchResult => ({
|
||||
id: `entity-project-${p.id}`,
|
||||
label: p.name,
|
||||
icon: ENTITY_ICONS.project,
|
||||
keywords: ['project'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('projects.show', { project: p.id }));
|
||||
},
|
||||
entityType: 'project',
|
||||
color: p.color,
|
||||
badgeClass: ENTITY_BADGE_CLASSES.project,
|
||||
}));
|
||||
results.push(...matching);
|
||||
}
|
||||
|
||||
@@ -407,20 +405,18 @@ export function useCommandPalette() {
|
||||
const matching = clients.value
|
||||
.filter((c: Client) => c.name.toLowerCase().includes(query))
|
||||
.slice(0, maxPerType)
|
||||
.map(
|
||||
(c: Client): EntitySearchResult => ({
|
||||
id: `entity-client-${c.id}`,
|
||||
label: c.name,
|
||||
icon: ENTITY_ICONS.client,
|
||||
keywords: ['client'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('clients'));
|
||||
},
|
||||
entityType: 'client',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.client,
|
||||
})
|
||||
);
|
||||
.map((c: Client): EntitySearchResult => ({
|
||||
id: `entity-client-${c.id}`,
|
||||
label: c.name,
|
||||
icon: ENTITY_ICONS.client,
|
||||
keywords: ['client'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('clients'));
|
||||
},
|
||||
entityType: 'client',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.client,
|
||||
}));
|
||||
results.push(...matching);
|
||||
}
|
||||
|
||||
@@ -428,22 +424,20 @@ export function useCommandPalette() {
|
||||
const matching = tasks.value
|
||||
.filter((t: Task) => t.name.toLowerCase().includes(query))
|
||||
.slice(0, maxPerType)
|
||||
.map(
|
||||
(t: Task): EntitySearchResult => ({
|
||||
id: `entity-task-${t.id}`,
|
||||
label: t.name,
|
||||
icon: ENTITY_ICONS.task,
|
||||
keywords: ['task'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
if (t.project_id) {
|
||||
router.visit(route('projects.show', { project: t.project_id }));
|
||||
}
|
||||
},
|
||||
entityType: 'task',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.task,
|
||||
})
|
||||
);
|
||||
.map((t: Task): EntitySearchResult => ({
|
||||
id: `entity-task-${t.id}`,
|
||||
label: t.name,
|
||||
icon: ENTITY_ICONS.task,
|
||||
keywords: ['task'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
if (t.project_id) {
|
||||
router.visit(route('projects.show', { project: t.project_id }));
|
||||
}
|
||||
},
|
||||
entityType: 'task',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.task,
|
||||
}));
|
||||
results.push(...matching);
|
||||
}
|
||||
|
||||
@@ -451,20 +445,18 @@ export function useCommandPalette() {
|
||||
const matching = tags.value
|
||||
.filter((t: Tag) => t.name.toLowerCase().includes(query))
|
||||
.slice(0, maxPerType)
|
||||
.map(
|
||||
(t: Tag): EntitySearchResult => ({
|
||||
id: `entity-tag-${t.id}`,
|
||||
label: t.name,
|
||||
icon: ENTITY_ICONS.tag,
|
||||
keywords: ['tag'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('tags'));
|
||||
},
|
||||
entityType: 'tag',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.tag,
|
||||
})
|
||||
);
|
||||
.map((t: Tag): EntitySearchResult => ({
|
||||
id: `entity-tag-${t.id}`,
|
||||
label: t.name,
|
||||
icon: ENTITY_ICONS.tag,
|
||||
keywords: ['tag'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('tags'));
|
||||
},
|
||||
entityType: 'tag',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.tag,
|
||||
}));
|
||||
results.push(...matching);
|
||||
}
|
||||
|
||||
@@ -472,20 +464,18 @@ export function useCommandPalette() {
|
||||
const matching = members.value
|
||||
.filter((m: Member) => m.name.toLowerCase().includes(query))
|
||||
.slice(0, maxPerType)
|
||||
.map(
|
||||
(m: Member): EntitySearchResult => ({
|
||||
id: `entity-member-${m.id}`,
|
||||
label: m.name,
|
||||
icon: ENTITY_ICONS.member,
|
||||
keywords: ['member'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('members'));
|
||||
},
|
||||
entityType: 'member',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.member,
|
||||
})
|
||||
);
|
||||
.map((m: Member): EntitySearchResult => ({
|
||||
id: `entity-member-${m.id}`,
|
||||
label: m.name,
|
||||
icon: ENTITY_ICONS.member,
|
||||
keywords: ['member'],
|
||||
action: () => {
|
||||
closePaletteAfterAction();
|
||||
router.visit(route('members'));
|
||||
},
|
||||
entityType: 'member',
|
||||
badgeClass: ENTITY_BADGE_CLASSES.member,
|
||||
}));
|
||||
results.push(...matching);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { api } from '@/packages/api/src';
|
||||
import type { TimeEntry } from '@/packages/api/src';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
@@ -57,7 +57,6 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
const currentTimeEntry = ref<TimeEntry>({ ...emptyTimeEntry });
|
||||
const { handleApiRequestNotifications } = useNotificationsStore();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useLocalStorage('solidtime/current-time-entry', currentTimeEntry, {
|
||||
deep: true,
|
||||
});
|
||||
@@ -89,23 +88,12 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
|
||||
try {
|
||||
const timeEntriesResponse = await api.getMyActiveTimeEntry({});
|
||||
if (timeEntriesResponse?.data) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
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 };
|
||||
}
|
||||
} catch {
|
||||
// API error (e.g., 404 when no active time entry)
|
||||
@@ -113,7 +101,6 @@ 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 {
|
||||
@@ -294,6 +281,18 @@ 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,6 +6,7 @@ namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PasswordConfirmationTest extends TestCase
|
||||
@@ -43,4 +44,43 @@ 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,6 +7,7 @@ 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;
|
||||
@@ -93,4 +94,62 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,13 @@ use TiMacDonald\Log\LogEntry;
|
||||
|
||||
class RegistrationTest extends TestCaseWithDatabase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('app.enable_registration', 'on');
|
||||
}
|
||||
|
||||
public function test_registration_screen_can_be_rendered(): void
|
||||
{
|
||||
if (! Features::enabled(Features::registration())) {
|
||||
@@ -89,6 +96,77 @@ class RegistrationTest extends TestCaseWithDatabase
|
||||
Event::assertNotDispatched(NewsletterRegistered::class);
|
||||
}
|
||||
|
||||
public function test_user_registration_fails_without_an_invitation_if_registration_is_invite_only(): void
|
||||
{
|
||||
Config::set('app.enable_registration', 'invite-only');
|
||||
|
||||
$response = $this->post('/register', [
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
'terms' => true,
|
||||
]);
|
||||
|
||||
$response->assertInvalid([
|
||||
'email' => 'Registration is only available to invited users.',
|
||||
]);
|
||||
$this->assertFalse(User::query()->where('email', 'test@example.com')->exists());
|
||||
}
|
||||
|
||||
public function test_invited_user_can_register_if_registration_is_invite_only(): void
|
||||
{
|
||||
Config::set('app.enable_registration', 'invite-only');
|
||||
$user = $this->createUserWithPermission();
|
||||
OrganizationInvitation::factory()
|
||||
->forOrganization($user->organization)
|
||||
->role(Role::Employee)
|
||||
->accepted()
|
||||
->create([
|
||||
'email' => 'Invited.User@example.com',
|
||||
]);
|
||||
|
||||
$response = $this->post('/register', [
|
||||
'name' => 'Invited User',
|
||||
'email' => 'invited.user@example.com',
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
'terms' => true,
|
||||
]);
|
||||
|
||||
$response->assertValid();
|
||||
$this->assertAuthenticated();
|
||||
$response->assertRedirect(RouteServiceProvider::HOME);
|
||||
$newUser = User::query()->where('email', 'invited.user@example.com')->firstOrFail();
|
||||
$this->assertSame($user->organization->getKey(), $newUser->organizations()->firstOrFail()->getKey());
|
||||
}
|
||||
|
||||
public function test_user_must_accept_pending_invitation_before_registration_if_registration_is_invite_only(): void
|
||||
{
|
||||
Config::set('app.enable_registration', 'invite-only');
|
||||
$user = $this->createUserWithPermission();
|
||||
OrganizationInvitation::factory()
|
||||
->forOrganization($user->organization)
|
||||
->role(Role::Employee)
|
||||
->create([
|
||||
'email' => 'test@example.com',
|
||||
]);
|
||||
|
||||
$response = $this->post('/register', [
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
'terms' => true,
|
||||
]);
|
||||
|
||||
$response->assertInvalid([
|
||||
'email' => 'Please accept the organization invitation sent to your email address before registering.',
|
||||
]);
|
||||
$this->assertGuest();
|
||||
$this->assertFalse(User::query()->where('email', 'test@example.com')->exists());
|
||||
}
|
||||
|
||||
public function test_new_user_can_not_register_with_likely_invalid_domain(): void
|
||||
{
|
||||
// Act
|
||||
|
||||
90
tests/Unit/Auth/ActiveUserProviderTest.php
Normal file
90
tests/Unit/Auth/ActiveUserProviderTest.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?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,6 +97,29 @@ 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
|
||||
|
||||
@@ -38,6 +38,7 @@ class OrganizationInvitationEndpointTest extends EndpointTestAbstract
|
||||
$response->assertRedirect(route('register'));
|
||||
$response->assertSessionHas('bannerText', 'Please create an account to finish joining the '.$user->organization->name.' organization.');
|
||||
$response->assertSessionHas('bannerStyle', 'info');
|
||||
$response->assertSessionHas('registration_email', strtolower($invitation->email));
|
||||
$invitation->refresh();
|
||||
$this->assertNotNull($invitation->accepted_at);
|
||||
}
|
||||
@@ -64,6 +65,7 @@ class OrganizationInvitationEndpointTest extends EndpointTestAbstract
|
||||
$response->assertRedirect(route('register'));
|
||||
$response->assertSessionHas('bannerText', 'Please create an account to finish joining the '.$user->organization->name.' organization.');
|
||||
$response->assertSessionHas('bannerStyle', 'info');
|
||||
$response->assertSessionHas('registration_email', strtolower($invitation->email));
|
||||
$invitation->refresh();
|
||||
$this->assertNotNull($invitation->accepted_at);
|
||||
}
|
||||
@@ -103,6 +105,9 @@ 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
|
||||
|
||||
38
tests/Unit/Enums/RegistrationModeTest.php
Normal file
38
tests/Unit/Enums/RegistrationModeTest.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Enums;
|
||||
|
||||
use App\Enums\RegistrationMode;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
#[CoversClass(RegistrationMode::class)]
|
||||
class RegistrationModeTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @return array<string, array{mixed, RegistrationMode}>
|
||||
*/
|
||||
public static function configValueProvider(): array
|
||||
{
|
||||
return [
|
||||
'boolean true' => [true, RegistrationMode::On],
|
||||
'on' => ['on', RegistrationMode::On],
|
||||
'true' => ['true', RegistrationMode::On],
|
||||
'invite-only' => ['invite-only', RegistrationMode::InviteOnly],
|
||||
'boolean false' => [false, RegistrationMode::Off],
|
||||
'off' => ['off', RegistrationMode::Off],
|
||||
'false' => ['false', RegistrationMode::Off],
|
||||
'unsupported invite alias' => ['invite', RegistrationMode::Off],
|
||||
'unknown' => ['unknown', RegistrationMode::Off],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('configValueProvider')]
|
||||
public function test_registration_mode_is_created_from_config_value(mixed $value, RegistrationMode $expected): void
|
||||
{
|
||||
$this->assertSame($expected, RegistrationMode::fromConfig($value));
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,23 @@ 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,10 +412,11 @@ class DeletionServiceTest extends TestCaseWithDatabase
|
||||
$this->assertDatabaseHas(Organization::class, [
|
||||
'id' => $organizationOfA->getKey(),
|
||||
]);
|
||||
// The placeholder user should exist with current_team_id set to the org where they are a placeholder
|
||||
// The placeholder user should exist and must not reference the deleted organization,
|
||||
// which is what caused the foreign key violation in #989
|
||||
$placeholderUser = User::query()->where('is_placeholder', true)->first();
|
||||
$this->assertNotNull($placeholderUser);
|
||||
$this->assertSame($organizationOfA->getKey(), $placeholderUser->current_team_id);
|
||||
$this->assertNull($placeholderUser->current_team_id);
|
||||
$this->assertDatabaseHas(Member::class, [
|
||||
'id' => $memberBInOrgA->getKey(),
|
||||
'user_id' => $placeholderUser->getKey(),
|
||||
|
||||
@@ -41,6 +41,7 @@ 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,6 +42,31 @@ 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,6 +39,31 @@ 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
|
||||
|
||||
254
tests/Unit/Service/Import/Importers/ZipImportHelperTest.php
Normal file
254
tests/Unit/Service/Import/Importers/ZipImportHelperTest.php
Normal file
@@ -0,0 +1,254 @@
|
||||
<?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,6 +13,7 @@ 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;
|
||||
@@ -64,6 +65,48 @@ 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