Compare commits

..

45 Commits

Author SHA1 Message Date
Constantin Graf
f3ec660243 Add password check to users.destroy and organizations.destroy 2026-06-17 16:16:54 +02:00
Constantin Graf
37496a7547 Add option to enable email verification locally for testing 2026-06-17 15:20:36 +02:00
Constantin Graf
8c71a43191 Add comments to events about legacy events 2026-06-17 15:20:35 +02:00
Constantin Graf
f4107a9a49 Fixed middlwares after jetstream removal 2026-06-17 15:20:35 +02:00
Gregor Vostrak
4afcb24dc9 add comprehensive 2 factor authentication e2e tests 2026-06-17 15:20:35 +02:00
Gregor Vostrak
f9271664f0 add back destroy other browser sessions endpoint (jetstream migration) 2026-06-17 15:20:35 +02:00
Gregor Vostrak
5dcd8197dc update e2e test setup to use user settings api endpoint 2026-06-17 15:20:35 +02:00
Gregor Vostrak
e8c8edb4d5 change redirects and references to new organization routes 2026-06-17 15:20:35 +02:00
Gregor Vostrak
96ecc5335a add currency to organization update endpoint 2026-06-17 15:20:35 +02:00
Gregor Vostrak
c8024de452 replace hardcoded inertia props with organization delete/update perms 2026-06-17 15:20:35 +02:00
Gregor Vostrak
eef2cdaec5 remove unused inertia organization page props 2026-06-17 15:20:35 +02:00
Gregor Vostrak
ed037d40a1 fix inertia backend role data structure after jetstream migration 2026-06-17 15:20:35 +02:00
Gregor Vostrak
6c0041d249 call api for organization create/update/delete and switch 2026-06-17 15:20:35 +02:00
Constantin Graf
e8f632f330 Fixed current organization after normal registration 2026-06-17 15:20:35 +02:00
Constantin Graf
a865469d57 Added tests 2026-06-17 15:20:35 +02:00
Gregor Vostrak
b18b4ef2ce add switch current organization endpoint 2026-06-17 15:20:35 +02:00
Constantin Graf
cb42daecbf Removed Laravel Jetstream 2026-06-17 15:20:35 +02:00
Gregor Vostrak
42f9efd570 remove jetstream inertia properties; remove unused ApiTokenManager; 2026-06-17 15:20:35 +02:00
Gregor Vostrak
4349b0dfb1 move banners on login and register cards into the cards 2026-06-17 15:20:35 +02:00
Gregor Vostrak
dba214f424 add pending email cancel button 2026-06-17 15:20:35 +02:00
Constantin Graf
acb1a07ca0 Replaces all Jetstream model trait functions and relations 2026-06-17 15:20:35 +02:00
Constantin Graf
1f4a957258 Add reset pending email endpoint to user controller 2026-06-17 15:20:35 +02:00
Gregor Vostrak
10a66fa065 move user delete to api endpoint 2026-06-17 15:20:35 +02:00
Gregor Vostrak
b2a5b7a8c1 use api routes for profile information updates 2026-06-17 15:20:35 +02:00
Gregor Vostrak
161cd258f3 show null billable rate as empty not as 0 to avoid confusion 2026-06-17 15:20:35 +02:00
Gregor Vostrak
d6ed3fb3fc fix e2e selectors to adapt to reka-ui change; 2026-06-17 15:20:35 +02:00
Gregor Vostrak
7b6cdf1d45 add pending email to UserResource and update openapi client 2026-06-17 15:20:35 +02:00
Gregor Vostrak
19e1edca31 update ui package dependencies; update lucide imports 2026-06-17 15:20:35 +02:00
Gregor Vostrak
0335c355cc add user endpoint tests for idempotence email update, unauthenticated
update and invalid email
2026-06-17 15:20:35 +02:00
Gregor Vostrak
d645588aed update npm dependencies 2026-06-17 15:20:35 +02:00
Gregor Vostrak
dc35afdae8 add profile page e2e tests 2026-06-17 15:20:35 +02:00
Gregor Vostrak
12b4633e0d update email address change info to use session based banners 2026-06-17 15:20:35 +02:00
Gregor Vostrak
002c8e66a0 add 1MB photo upload limit 2026-06-17 15:20:34 +02:00
Gregor Vostrak
15fe8beecc add photo delete logic to user update endpoint 2026-06-17 15:20:34 +02:00
Constantin Graf
15b5f4b586 Updated composer dependencies 2026-06-17 15:20:34 +02:00
Constantin Graf
390acf89e1 Add more tests 2026-06-17 15:20:34 +02:00
Constantin Graf
a54d914f13 Add migration to lower case the user emails 2026-06-17 15:20:34 +02:00
Constantin Graf
bde3ec7a75 Migrate permission away from Jetstream; Moved update user to REST API 2026-06-17 15:20:34 +02:00
Gregor Vostrak
8637437808 rephrase logged out user invite accept message to clarify that the
invite was accepted
2026-06-17 15:20:34 +02:00
Gregor Vostrak
0f6e0feeae add banners for invitation accept 2026-06-17 15:20:34 +02:00
Constantin Graf
08eba2d90b Updated invitation flow, Moved jetstream function to REST endpoints; Lower case email 2026-06-17 15:20:34 +02:00
dependabot[bot]
d732064f31 Bump actions/checkout from 4 to 6
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-08 22:58:27 +02:00
Gregor Vostrak
cb5c2547f4 fix profile setting sidebar alignment 2026-06-03 12:24:53 +02:00
Gregor Vostrak
13a25524f3 add saved/saving/error indicators to timesheets 2026-06-02 17:14:32 +02:00
Gregor Vostrak
112f6aa6a6 add invoice clone to openapi client, expose DetailedInvoice type 2026-05-29 19:07:55 +02:00
46 changed files with 746 additions and 100 deletions

View File

@@ -35,7 +35,7 @@ jobs:
steps:
- name: "Check out code"
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
@@ -96,7 +96,7 @@ jobs:
node-version: '20.x'
- name: "Checkout invoicing extension"
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
repository: solidtime-io/extension-invoicing
path: extensions/Invoicing

View File

@@ -22,7 +22,7 @@ jobs:
steps:
- name: "Check out code"
uses: actions/checkout@v5
uses: actions/checkout@v6
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
@@ -73,7 +73,7 @@ jobs:
node-version: '20.x'
- name: "Checkout billing extension"
uses: actions/checkout@v5
uses: actions/checkout@v6
with:
repository: solidtime-io/extension-billing
path: extensions/Billing
@@ -93,7 +93,7 @@ jobs:
run: cd extensions/Billing && npm ci
- name: "Checkout services extension"
uses: actions/checkout@v5
uses: actions/checkout@v6
with:
repository: solidtime-io/extension-services
path: extensions/Services
@@ -111,7 +111,7 @@ jobs:
run: cd extensions/Services && npm ci
- name: "Checkout invoicing extension"
uses: actions/checkout@v5
uses: actions/checkout@v6
with:
repository: solidtime-io/extension-invoicing
path: extensions/Invoicing

View File

@@ -36,7 +36,7 @@ jobs:
steps:
- name: "Check out code"
uses: actions/checkout@v5
uses: actions/checkout@v6
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag

View File

@@ -29,7 +29,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup PHP"
uses: shivammathur/setup-php@v2

View File

@@ -11,7 +11,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2

View File

@@ -9,7 +9,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Use Node.js"
uses: actions/setup-node@v6

View File

@@ -11,7 +11,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Use Node.js"
uses: actions/setup-node@v6

View File

@@ -11,7 +11,7 @@ jobs:
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
# Setup .npmrc file to publish to npm
- name: Install root project dependencies
run: npm ci

View File

@@ -11,7 +11,7 @@ jobs:
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v6
with:

View File

@@ -10,7 +10,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2

View File

@@ -9,7 +9,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup PHP"
uses: shivammathur/setup-php@v2

View File

@@ -36,7 +36,7 @@ jobs:
--health-retries 5
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup PHP"
uses: shivammathur/setup-php@v2

View File

@@ -9,7 +9,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Check code style"
uses: aglipanci/laravel-pint-action@2.6

View File

@@ -35,7 +35,7 @@ jobs:
steps:
- name: "Checkout code"
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: "Setup node"
uses: actions/setup-node@v6
@@ -99,7 +99,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: "Checkout code"
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: "Setup node"
uses: actions/setup-node@v4

View File

@@ -9,6 +9,9 @@ use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Replaces legacy TeamMemberAdded event.
*/
class MemberAdded
{
use Dispatchable;

View File

@@ -9,6 +9,9 @@ use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Replaces legacy AddingTeamMember event.
*/
class MemberAdding
{
use Dispatchable;

View File

@@ -9,6 +9,9 @@ use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Replaces legacy InvitingTeamMember event.
*/
class OrganizationInvitationAdding
{
use Dispatchable;

View File

@@ -6,6 +6,7 @@ namespace App\Http\Controllers\Api\V1;
use App\Enums\Role;
use App\Events\AfterCreateOrganization;
use App\Http\Requests\V1\Organization\OrganizationDestroyRequest;
use App\Http\Requests\V1\Organization\OrganizationStoreRequest;
use App\Http\Requests\V1\Organization\OrganizationUpdateRequest;
use App\Http\Resources\V1\Organization\OrganizationResource;
@@ -124,7 +125,7 @@ class OrganizationController extends Controller
*
* @throws AuthorizationException
*/
public function destroy(Organization $organization, DeletionService $deletionService): JsonResponse
public function destroy(Organization $organization, OrganizationDestroyRequest $request, DeletionService $deletionService): JsonResponse
{
$this->checkPermission($organization, 'organizations:delete');

View File

@@ -6,6 +6,7 @@ namespace App\Http\Controllers\Api\V1;
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
use App\Exceptions\Api\UserResendEmailVerificationNoPendingEmailApiException;
use App\Http\Requests\V1\User\UserDestroyRequest;
use App\Http\Requests\V1\User\UserUpdateCurrentOrganizationRequest;
use App\Http\Requests\V1\User\UserUpdateRequest;
use App\Http\Resources\V1\User\UserResource;
@@ -193,7 +194,7 @@ class UserController extends Controller
* @throws AuthorizationException Thrown when the authenticated user does not match the user to be deleted.
* @throws CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers Thrown when the user to be deleted is the owner of an organization with multiple members.
*/
public function destroy(User $user, DeletionService $deletionService): JsonResponse
public function destroy(User $user, UserDestroyRequest $request, DeletionService $deletionService): JsonResponse
{
if ($user->getKey() !== $this->user()->getKey()) {
throw new AuthorizationException;

View File

@@ -17,7 +17,7 @@ class EnsureEmailIsVerified
*/
public function handle(Request $request, Closure $next, ?string $redirectToRoute = null): Response
{
if (! app()->isLocal()) {
if (! app()->isLocal() || config('app.local_email_verification')) {
if ($request->user() === null ||
(! $request->user()->hasVerifiedEmail())) {
return $request->expectsJson()

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\Organization;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Validator;
class OrganizationDestroyRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string>>
*/
public function rules(): array
{
return [
'password' => [
'required',
'string',
],
];
}
/**
* @return array<int, callable(Validator): void>
*/
public function after(): array
{
return [
function (Validator $validator): void {
if ($validator->errors()->has('password')) {
return;
}
$user = $this->user();
$password = $this->input('password');
if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) {
$validator->errors()->add('password', __('The password is incorrect.'));
}
},
];
}
}

View File

@@ -12,6 +12,7 @@ use App\Enums\TimeFormat;
use App\Http\Requests\V1\BaseFormRequest;
use App\Models\Organization;
use App\Rules\CurrencyRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rule;
/**
@@ -22,7 +23,7 @@ class OrganizationUpdateRequest extends BaseFormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|\Illuminate\Contracts\Validation\ValidationRule>>
* @return array<string, array<string|\Illuminate\Contracts\Validation\Rule|ValidationRule>>
*/
public function rules(): array
{

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\V1\User;
use App\Http\Requests\V1\BaseFormRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Validator;
class UserDestroyRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string>>
*/
public function rules(): array
{
return [
'password' => [
'required',
'string',
],
];
}
/**
* @return array<int, callable(Validator): void>
*/
public function after(): array
{
return [
function (Validator $validator): void {
if ($validator->errors()->has('password')) {
return;
}
$user = $this->user();
$password = $this->input('password');
if (! is_string($password) || $user === null || ! Hash::check($password, (string) $user->password)) {
$validator->errors()->add('password', __('The password is incorrect.'));
}
},
];
}
}

View File

@@ -81,6 +81,8 @@ return [
'enable_registration' => (bool) env('APP_ENABLE_REGISTRATION', false),
'local_email_verification' => (bool) env('APP_LOCAL_EMAIL_VERIFICATION', false),
/*
|--------------------------------------------------------------------------
| Application Timezone

View File

@@ -107,7 +107,7 @@ services:
- sail
- reverse-proxy
playwright:
image: mcr.microsoft.com/playwright:v1.59.1-jammy
image: mcr.microsoft.com/playwright:v1.60.0-jammy
command: ['npx', 'playwright', 'test', '--ui-port=8080', '--ui-host=0.0.0.0']
working_dir: /src
extra_hosts:

View File

@@ -1,5 +1,5 @@
import { expect, test } from '../playwright/fixtures';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { PLAYWRIGHT_BASE_URL, TEST_USER_PASSWORD } from '../playwright/config';
async function goToOrganizationSettings(page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
@@ -471,6 +471,7 @@ test.describe('Organization Create, Delete & Switch', () => {
// Open the confirmation modal, then confirm inside the dialog.
await page.getByRole('button', { name: 'Delete Organization' }).click();
await page.getByRole('dialog').getByPlaceholder('Password').fill(TEST_USER_PASSWORD);
await Promise.all([
page.waitForResponse(
(response) =>
@@ -488,6 +489,28 @@ test.describe('Organization Create, Delete & Switch', () => {
).not.toContainText(orgName);
});
test('delete organization shows an error when the password is wrong', async ({ page }) => {
const orgName = 'DeleteOrgWrongPassword' + Math.floor(Math.random() * 100000);
await createOrganization(page, orgName);
await goToOrganizationSettings(page);
await page.getByRole('button', { name: 'Delete Organization' }).click();
const dialog = page.getByRole('dialog');
await dialog.getByPlaceholder('Password').fill('not-the-real-password');
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/api/v1/organizations') &&
response.request().method() === 'DELETE' &&
response.status() === 422
),
dialog.getByRole('button', { name: 'Delete Organization' }).click(),
]);
await expect(dialog.getByRole('alert')).toBeVisible();
await expect(dialog).toBeVisible();
});
test('can switch the current organization via the organization switcher', async ({ page }) => {
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
const orgSwitcher = page.locator('[data-testid="organization_switcher"]:visible');

View File

@@ -342,8 +342,8 @@ test('delete account shows an error when the password is wrong', async ({ page }
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/user/confirm-password') &&
response.request().method() === 'POST' &&
response.url().includes('/api/v1/users/') &&
response.request().method() === 'DELETE' &&
response.status() === 422
),
dialog.getByRole('button', { name: 'Delete Account' }).click(),

View File

@@ -62,4 +62,35 @@ describe('TimesheetCell', () => {
expect(wrapper.emitted('update')).toBeUndefined();
expect((input.element as HTMLInputElement).value).toBe(previousValue);
});
it('shows a pending 0 (delete in flight) over the cell total', () => {
const wrapper = mount(TimesheetCell, {
props: {
cell: buildCell(2 * 3600),
dayIndex: 0,
date: '2026-04-13',
isToday: false,
hasRunningEntry: false,
pendingSeconds: 0,
},
});
// `??` (not `||`): a pending 0 must win over the 2h cell total.
expect((wrapper.get('input').element as HTMLInputElement).value).toBe('');
});
it('disables editing while the cell is saving', () => {
const wrapper = mount(TimesheetCell, {
props: {
cell: buildCell(2 * 3600),
dayIndex: 0,
date: '2026-04-13',
isToday: false,
hasRunningEntry: false,
saveStatus: 'saving',
},
});
expect((wrapper.get('input').element as HTMLInputElement).disabled).toBe(true);
});
});

View File

@@ -1,5 +1,8 @@
<script setup lang="ts">
import { computed } from 'vue';
import { CheckIcon } from '@heroicons/vue/16/solid';
import DurationSecondsInput from '@/packages/ui/src/Input/DurationSecondsInput.vue';
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
import {
Tooltip,
TooltipContent,
@@ -7,18 +10,40 @@ import {
TooltipTrigger,
} from '@/packages/ui/src/tooltip';
import type { TimesheetCell } from '@/utils/useTimesheetGrid';
import type { CellSaveStatus } from '@/utils/timesheet/useTimesheetCellMutations';
defineProps<{
const props = defineProps<{
cell?: TimesheetCell;
dayIndex: number;
date: string;
isToday: boolean;
hasRunningEntry: boolean;
saveStatus?: CellSaveStatus;
pendingSeconds?: number;
}>();
const emit = defineEmits<{
update: [newSeconds: number];
}>();
// Show the optimistic value while saving; `??` (not `||`) so a pending 0 (delete) wins.
const displaySeconds = computed(() => props.pendingSeconds ?? props.cell?.totalSeconds ?? 0);
const isSaving = computed(() => props.saveStatus === 'saving');
// Swap the border color (don't layer) to avoid same-specificity fights.
const inputClass = computed(() => {
const border = props.saveStatus === 'error' ? 'border-red-500/70' : 'border-input-border';
return [
'w-[80px] mx-auto text-center font-medium',
'bg-transparent text-text-primary placeholder:text-text-quaternary',
'rounded-lg border shadow-none',
border,
'hover:bg-card-background',
'focus-visible:bg-tertiary focus-visible:border-transparent',
'focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
'disabled:cursor-wait disabled:opacity-70',
].join(' ');
});
</script>
<template>
@@ -46,18 +71,26 @@ const emit = defineEmits<{
<TooltipContent> Stop the running time entry to edit the timesheet </TooltipContent>
</Tooltip>
</TooltipProvider>
<DurationSecondsInput
v-else
:model-value="cell?.totalSeconds ?? 0"
default-unit="hours"
placeholder="-"
size="sm"
input-class="w-[80px] mx-auto text-center font-medium
bg-transparent text-text-primary placeholder:text-text-quaternary
rounded-lg border border-input-border shadow-none
hover:bg-card-background
focus-visible:bg-tertiary focus-visible:border-transparent
focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
@commit="(seconds) => emit('update', seconds ?? 0)" />
<template v-else>
<span class="relative inline-flex items-center">
<DurationSecondsInput
:model-value="displaySeconds"
default-unit="hours"
placeholder="-"
size="sm"
:disabled="isSaving"
:input-class="inputClass"
@commit="(seconds) => emit('update', seconds ?? 0)" />
<span
v-if="saveStatus === 'saving' || saveStatus === 'saved'"
class="pointer-events-none absolute left-full top-1/2 ml-1.5 flex -translate-y-1/2 items-center"
:aria-label="saveStatus === 'saving' ? 'Saving' : 'Saved'">
<LoadingSpinner
v-if="saveStatus === 'saving'"
class="h-3 w-3 m-0 text-text-tertiary" />
<CheckIcon v-else class="h-3 w-3 text-text-tertiary" />
</span>
</span>
</template>
</div>
</template>

View File

@@ -15,6 +15,7 @@ import type {
Task,
} from '@/packages/api/src';
import type { TimesheetRow as TimesheetRowType, TimesheetRowKey } from '@/utils/useTimesheetGrid';
import type { CellSaveStatus } from '@/utils/timesheet/useTimesheetCellMutations';
const organization = inject<ComputedRef<Organization>>('organization');
const dayjs = getDayJsInstance();
@@ -36,6 +37,8 @@ defineProps<{
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
createTag: (name: string) => Promise<Tag | undefined>;
formatDuration: (seconds: number) => string;
cellStatuses: Record<string, CellSaveStatus>;
cellPendingSeconds: Record<string, number>;
}>();
const emit = defineEmits<{
@@ -60,7 +63,7 @@ const emit = defineEmits<{
class="grid min-w-full w-max border-y border-default-background-separator"
style="
grid-template-columns:
minmax(420px, 1fr) repeat(7, minmax(96px, 120px)) minmax(100px, auto)
minmax(420px, 1fr) repeat(7, minmax(116px, 120px)) minmax(100px, auto)
40px;
">
<!-- Header row -->
@@ -100,6 +103,8 @@ const emit = defineEmits<{
:create-client="createClient"
:create-tag="createTag"
:format-duration="formatDuration"
:cell-statuses="cellStatuses"
:cell-pending-seconds="cellPendingSeconds"
@remove-row="$emit('remove-row', $event)"
@cell-update="
(dayIndex, seconds) => $emit('cell-update', row, dayIndex, seconds)

View File

@@ -15,6 +15,10 @@ import type {
Organization,
} from '@/packages/api/src';
import type { TimesheetRow, TimesheetRowKey } from '@/utils/useTimesheetGrid';
import {
makeCellStatusKey,
type CellSaveStatus,
} from '@/utils/timesheet/useTimesheetCellMutations';
import { Button } from '@/packages/ui/src/Buttons';
const organization = inject<ComputedRef<Organization>>('organization');
@@ -34,6 +38,8 @@ const props = defineProps<{
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
createTag: (name: string) => Promise<Tag | undefined>;
formatDuration: (seconds: number) => string;
cellStatuses: Record<string, CellSaveStatus>;
cellPendingSeconds: Record<string, number>;
}>();
const emit = defineEmits<{
@@ -109,6 +115,8 @@ function hasRunningEntry(dayIndex: number): boolean {
:date="day"
:is-today="day === todayDate"
:has-running-entry="hasRunningEntry(dayIndex)"
:save-status="cellStatuses[makeCellStatusKey(row.key, dayIndex)]"
:pending-seconds="cellPendingSeconds[makeCellStatusKey(row.key, dayIndex)]"
@update="(seconds) => emit('cellUpdate', dayIndex, seconds)" />
<!-- Row total -->

View File

@@ -298,7 +298,7 @@ const page = usePage<{
<div class="justify-self-end">
<UpdateSidebarNotification></UpdateSidebarNotification>
<ul
class="border-t border-default-background-separator pt-3 gap-1 pr-2 flex justify-between items-center">
class="border-t border-default-background-separator pt-3 gap-1 flex justify-between items-center">
<UserSettingsIcon></UserSettingsIcon>
<NavigationSidebarItem

View File

@@ -1,15 +1,14 @@
<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import ActionSection from '@/Components/ActionSection.vue';
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import { useDeleteUserMutation, useUserQuery } from '@/utils/useUserQuery';
import { useDeleteUserMutation } from '@/utils/useUserQuery';
import { getCurrentUserId } from '@/utils/useUser';
const { user } = useUserQuery();
const deleteUserMutation = useDeleteUserMutation();
const confirmingUserDeletion = ref(false);
@@ -24,26 +23,26 @@ function confirmUserDeletion() {
}
async function deleteUser() {
if (!user.value || processing.value) return;
if (processing.value) return;
processing.value = true;
passwordError.value = '';
try {
await axios.post(route('password.confirm'), { password: password.value });
} catch (error) {
processing.value = false;
if (axios.isAxiosError(error) && error.response?.status === 422) {
passwordError.value = error.response.data?.errors?.password?.[0] ?? 'Invalid password.';
} else {
passwordError.value = 'Could not confirm password. Please try again.';
}
passwordInput.value?.focus();
return;
}
try {
await deleteUserMutation.mutateAsync(user.value.id);
await deleteUserMutation.mutateAsync({
userId: getCurrentUserId(),
body: { password: password.value },
});
window.location.href = '/';
} catch {
} catch (error) {
if (error && typeof error === 'object' && 'response' in error) {
const response = error.response as
| { status?: number; data?: { errors?: { password?: string[] } } }
| undefined;
if (response?.status === 422) {
passwordError.value = response.data?.errors?.password?.[0] ?? 'Invalid password.';
}
}
processing.value = false;
passwordInput.value?.focus();
}
}

View File

@@ -2,9 +2,11 @@
import { ref } from 'vue';
import { router } from '@inertiajs/vue3';
import ActionSection from '@/Components/ActionSection.vue';
import ConfirmationModal from '@/Components/ConfirmationModal.vue';
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { Field, FieldError } from '@/packages/ui/src/field';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import { useOrganizationStore } from '@/utils/useOrganization';
const props = defineProps<{
@@ -12,26 +14,46 @@ const props = defineProps<{
}>();
const confirmingTeamDeletion = ref(false);
const passwordInput = ref<HTMLInputElement | null>(null);
const password = ref('');
const passwordError = ref('');
const processing = ref(false);
const organizationStore = useOrganizationStore();
const confirmTeamDeletion = () => {
confirmingTeamDeletion.value = true;
setTimeout(() => passwordInput.value?.focus(), 250);
};
const deleteTeam = async () => {
if (processing.value) return;
processing.value = true;
passwordError.value = '';
try {
await organizationStore.deleteOrganization(props.team.id);
await organizationStore.deleteOrganization(props.team.id, { password: password.value });
// The backend reassigns the user's current organization after deletion,
// so flush the prefetch cache and reload into the dashboard.
router.flushAll();
router.visit(route('dashboard'));
} catch {
// Request errors are surfaced as notifications by the store.
} catch (error) {
if (error && typeof error === 'object' && 'response' in error) {
const response = error.response as
| { status?: number; data?: { errors?: { password?: string[] } } }
| undefined;
if (response?.status === 422) {
passwordError.value = response.data?.errors?.password?.[0] ?? 'Invalid password.';
}
}
processing.value = false;
passwordInput.value?.focus();
}
};
const closeModal = () => {
confirmingTeamDeletion.value = false;
password.value = '';
passwordError.value = '';
};
</script>
<template>
@@ -52,20 +74,30 @@ const deleteTeam = async () => {
</div>
<!-- Delete Organization Confirmation Modal -->
<ConfirmationModal
:show="confirmingTeamDeletion"
@close="confirmingTeamDeletion = false">
<DialogModal :show="confirmingTeamDeletion" @close="closeModal">
<template #title> Delete Organization </template>
<template #content>
Are you sure you want to delete this organization? Once a organization is
deleted, all of its resources and data will be permanently deleted.
deleted, all of its resources and data will be permanently deleted. Please enter
your password to confirm you would like to permanently delete this organization.
<Field class="mt-4">
<TextInput
ref="passwordInput"
v-model="password"
type="password"
class="block w-3/4"
placeholder="Password"
autocomplete="current-password"
@keyup.enter="deleteTeam" />
<FieldError v-if="passwordError">{{ passwordError }}</FieldError>
</Field>
</template>
<template #footer>
<SecondaryButton @click="confirmingTeamDeletion = false">
Cancel
</SecondaryButton>
<SecondaryButton @click="closeModal"> Cancel </SecondaryButton>
<DangerButton
class="ms-3"
@@ -75,7 +107,7 @@ const deleteTeam = async () => {
Delete Organization
</DangerButton>
</template>
</ConfirmationModal>
</DialogModal>
</template>
</ActionSection>
</template>

View File

@@ -90,7 +90,12 @@ const weekRangeDisplay = computed(() => {
});
// ── Cell / row mutation handlers ──────────────────────────────────
const { handleCellUpdate } = useTimesheetCellMutations(weekDays, timeEntries, rows, removeSlot);
const { handleCellUpdate, cellStatus, cellPendingSeconds } = useTimesheetCellMutations(
weekDays,
timeEntries,
rows,
removeSlot
);
const { handleRowIdentityChange, handleAddRow } = useTimesheetRowMutations(
mutations,
@@ -167,6 +172,8 @@ async function createTag(name: string): Promise<Tag | undefined> {
:create-client="createClient"
:create-tag="createTag"
:format-duration="formatDuration"
:cell-statuses="cellStatus"
:cell-pending-seconds="cellPendingSeconds"
@remove-row="handleRemoveRow"
@cell-update="handleCellUpdate"
@project-task-change="

View File

@@ -114,6 +114,8 @@ export type ApiToken = ApiTokenIndexResponse['data'][0];
export type DetailedInvoiceResponse = ZodiosResponseByAlias<SolidTimeApi, 'getInvoice'>;
export type DetailedInvoice = DetailedInvoiceResponse['data'];
export type InvoiceIndexEntry = ZodiosResponseByAlias<SolidTimeApi, 'getInvoices'>['data'][0];
export type UpdateInvoiceSettings = ZodiosBodyByAlias<SolidTimeApi, 'updateInvoiceSettings'>;
@@ -124,6 +126,8 @@ export type UpdateInvoiceBody = ZodiosBodyByAlias<SolidTimeApi, 'updateInvoice'>
export type User = ZodiosResponseByAlias<SolidTimeApi, 'getMe'>['data'];
export type UpdateUserBody = ZodiosBodyByAlias<SolidTimeApi, 'updateUser'>;
export type DeleteUserBody = ZodiosBodyByAlias<SolidTimeApi, 'deleteUser'>;
export type DeleteOrganizationBody = ZodiosBodyByAlias<SolidTimeApi, 'deleteOrganization'>;
const api = createApiClient('/api', { validate: 'none' });

View File

@@ -37,6 +37,7 @@ const ClientStoreRequest = z.object({ name: z.string().min(1).max(255) }).passth
const ClientUpdateRequest = z
.object({ name: z.string().min(1).max(255), is_archived: z.boolean().optional() })
.passthrough();
const DestroyWithPasswordRequest = z.object({ password: z.string() }).passthrough();
const ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
const InvitationResource = z
.object({ id: z.string(), email: z.string(), role: z.string() })
@@ -917,6 +918,11 @@ const endpoints = makeApi([
alias: 'deleteOrganization',
requestFormat: 'json',
parameters: [
{
name: 'body',
type: 'Body',
schema: DestroyWithPasswordRequest,
},
{
name: 'organization',
type: 'Path',
@@ -1963,6 +1969,54 @@ const endpoints = makeApi([
},
],
},
{
method: 'post',
path: '/v1/organizations/:organization/invoices/:invoice/copy',
alias: 'copyInvoice',
requestFormat: 'json',
parameters: [
{
name: 'body',
type: 'Body',
schema: z.object({ reference: z.string() }).passthrough(),
},
{
name: 'organization',
type: 'Path',
schema: z.string(),
},
{
name: 'invoice',
type: 'Path',
schema: z.string(),
},
],
response: z.object({ data: DetailedInvoiceResource }).passthrough(),
errors: [
{
status: 401,
description: `Unauthenticated`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 403,
description: `Authorization error`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 404,
description: `Not found`,
schema: z.object({ message: z.string() }).passthrough(),
},
{
status: 422,
description: `Validation error`,
schema: z
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
},
{
method: 'get',
path: '/v1/organizations/:organization/invoices/:invoice',
@@ -4594,6 +4648,11 @@ the organization.`,
description: `This endpoint is independent of the organization.`,
requestFormat: 'json',
parameters: [
{
name: 'body',
type: 'Body',
schema: DestroyWithPasswordRequest,
},
{
name: 'user',
type: 'Path',

View File

@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ref } from 'vue';
import { createPinia, setActivePinia } from 'pinia';
import { useTimesheetCellMutations } from './useTimesheetCellMutations';
import { useTimesheetCellMutations, makeCellStatusKey } from './useTimesheetCellMutations';
import { api } from '@/packages/api/src';
import type { TimesheetRow, TimesheetCell } from '@/utils/useTimesheetGrid';
import type { TimeEntry } from '@/packages/api/src';
@@ -549,3 +549,119 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
});
});
});
describe('useTimesheetCellMutations save status', () => {
// Timer handles keep old fade-outs from clearing newer status, and
// the same-cell saving guard prevents concurrent writes from stale rows.
it('does not let a stale fade-out timer clear a newer edit on the same cell', async () => {
const { cellMutations } = setup([]);
const row = buildEmptyRow('p-1');
const key = makeCellStatusKey(row.key, 0);
await cellMutations.handleCellUpdate(row, 0, HOUR);
expect(cellMutations.cellStatus.value[key]).toBe('saved');
// Re-edit the same cell partway through the first "saved" window.
vi.advanceTimersByTime(1000);
await cellMutations.handleCellUpdate(row, 0, 2 * HOUR);
expect(cellMutations.cellPendingSeconds.value[key]).toBe(2 * HOUR);
// Advance past the FIRST timer's deadline: it must not wipe the newer state.
vi.advanceTimersByTime(2000);
expect(cellMutations.cellStatus.value[key]).toBe('saved');
expect(cellMutations.cellPendingSeconds.value[key]).toBe(2 * HOUR);
});
it('ignores another commit while the same cell is saving', async () => {
const { cellMutations } = setup([]);
const row = buildEmptyRow('p-1');
const key = makeCellStatusKey(row.key, 0);
let release!: () => void;
const gateA = new Promise<void>((res) => {
release = () => res();
});
apiMocks.createTimeEntry.mockImplementationOnce(async () => {
await gateA;
return { data: { id: 'a' } } as never;
});
const save = cellMutations.handleCellUpdate(row, 0, HOUR);
expect(cellMutations.cellStatus.value[key]).toBe('saving');
expect(cellMutations.cellPendingSeconds.value[key]).toBe(HOUR);
// The second commit would be planned from the same stale row, so it is ignored.
await cellMutations.handleCellUpdate(row, 0, 2 * HOUR);
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
expect(cellMutations.cellPendingSeconds.value[key]).toBe(HOUR);
release();
await save;
expect(cellMutations.cellStatus.value[key]).toBe('saved');
expect(cellMutations.cellPendingSeconds.value[key]).toBe(HOUR);
});
it('marks error and drops the optimistic value when the save fails', async () => {
const { cellMutations } = setup([]);
const row = buildEmptyRow('p-1');
const key = makeCellStatusKey(row.key, 0);
apiMocks.createTimeEntry.mockRejectedValueOnce(new Error('boom'));
await cellMutations.handleCellUpdate(row, 0, HOUR);
expect(cellMutations.cellStatus.value[key]).toBe('error');
expect(cellMutations.cellPendingSeconds.value[key]).toBeUndefined();
expect(addNotification).toHaveBeenCalledWith(
'error',
'Failed to update timesheet',
expect.any(String)
);
});
it('marks error and drops the optimistic value when the day is full', async () => {
// Block all but the last 2h, then ask for 3h → NoFreeWindowError.
const blocker = entry('2026-04-10T00:00:00Z', '2026-04-10T22:00:00Z', { id: 'blocker' });
const { cellMutations } = setup([blocker]);
const row = buildEmptyRow('p-1');
const key = makeCellStatusKey(row.key, 0);
await cellMutations.handleCellUpdate(row, 0, 3 * HOUR);
expect(cellMutations.cellStatus.value[key]).toBe('error');
expect(cellMutations.cellPendingSeconds.value[key]).toBeUndefined();
expect(addNotification).toHaveBeenCalledWith(
'error',
"This day can't fit any more work",
expect.any(String)
);
});
it('creates no status when the committed value is unchanged', async () => {
const cellEntry = entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z');
const { cellMutations } = setup([cellEntry]);
const row = buildRow('p-1', [cellEntry]);
const key = makeCellStatusKey(row.key, 0);
await cellMutations.handleCellUpdate(row, 0, HOUR);
expect(cellMutations.cellStatus.value[key]).toBeUndefined();
expect(cellMutations.cellPendingSeconds.value[key]).toBeUndefined();
});
it('tracks save status independently for each cell', async () => {
const { cellMutations } = setup([]);
const row = buildEmptyRow('p-1');
const mondayKey = makeCellStatusKey(row.key, 0);
const tuesdayKey = makeCellStatusKey(row.key, 1);
await cellMutations.handleCellUpdate(row, 0, HOUR);
await cellMutations.handleCellUpdate(row, 1, 2 * HOUR);
expect(cellMutations.cellStatus.value[mondayKey]).toBe('saved');
expect(cellMutations.cellStatus.value[tuesdayKey]).toBe('saved');
expect(cellMutations.cellPendingSeconds.value[mondayKey]).toBe(HOUR);
expect(cellMutations.cellPendingSeconds.value[tuesdayKey]).toBe(2 * HOUR);
});
});

View File

@@ -1,4 +1,4 @@
import type { Ref } from 'vue';
import { ref, type Ref } from 'vue';
import { useQueryClient } from '@tanstack/vue-query';
import { api, type CreateTimeEntryBody, type TimeEntry } from '@/packages/api/src';
import { formatHumanReadableDuration, getDayJsInstance } from '@/packages/ui/src/utils/time';
@@ -19,6 +19,17 @@ import {
type FreeWindow,
} from './cellMath';
export type CellSaveStatus = 'saving' | 'saved' | 'error';
/** Map key for a cell's save state (row + day). */
export function makeCellStatusKey(rowKey: TimesheetRowKey, dayIndex: number): string {
return `${rowKey}:${dayIndex}`;
}
/** How long the saved/error state stays visible before fading. */
const SAVED_VISIBLE_MS = 2800;
const ERROR_VISIBLE_MS = 2500;
/**
* Cell-level edit dispatcher. Picks one of four strategies based on
* the diff between current and requested totals:
@@ -48,15 +59,58 @@ export function useTimesheetCellMutations(
const queryClient = useQueryClient();
const notifications = useNotificationsStore();
// Save status + the optimistic value shown while saving, so a saved cell
// doesn't flicker back to its old total before the refetch lands.
const cellStatus = ref<Record<string, CellSaveStatus>>({});
const cellPendingSeconds = ref<Record<string, number>>({});
const statusClearTimers: Record<string, ReturnType<typeof setTimeout>> = {};
function clearStatusTimer(key: string): void {
clearTimeout(statusClearTimers[key]);
delete statusClearTimers[key];
}
function beginSaving(key: string, seconds: number): void {
clearStatusTimer(key);
cellPendingSeconds.value[key] = seconds;
cellStatus.value[key] = 'saving';
}
function markSaved(key: string): void {
clearStatusTimer(key);
cellStatus.value[key] = 'saved';
statusClearTimers[key] = setTimeout(() => {
delete cellStatus.value[key];
delete cellPendingSeconds.value[key];
delete statusClearTimers[key];
}, SAVED_VISIBLE_MS);
}
function markError(key: string): void {
clearStatusTimer(key);
cellStatus.value[key] = 'error';
// Drop the optimistic value so the cell shows server truth after refetch.
delete cellPendingSeconds.value[key];
statusClearTimers[key] = setTimeout(() => {
delete cellStatus.value[key];
delete statusClearTimers[key];
}, ERROR_VISIBLE_MS);
}
async function handleCellUpdate(
row: TimesheetRow,
dayIndex: number,
newTotalSeconds: number
): Promise<void> {
const statusKey = makeCellStatusKey(row.key, dayIndex);
if (cellStatus.value[statusKey] === 'saving') return;
const cell = row.cells.get(dayIndex);
const existingSeconds = cell?.totalSeconds ?? 0;
if (newTotalSeconds === existingSeconds) return;
beginSaving(statusKey, newTotalSeconds);
// Capture row state before the mutation: a row that was empty
// and shares identity with another slot collapses after the
// first entry lands, so the entry naturally identity-routes to
@@ -74,7 +128,9 @@ export function useTimesheetCellMutations(
'Another row with the same project, task, billable status and tags already exists.'
);
}
markSaved(statusKey);
} catch (err) {
markError(statusKey);
if (err instanceof NoFreeWindowError) {
const friendlyDuration = formatHumanReadableDuration(
err.requiredSeconds,
@@ -93,7 +149,6 @@ export function useTimesheetCellMutations(
'Failed to update timesheet',
'Please try again later.'
);
throw err;
} finally {
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
}
@@ -316,5 +371,5 @@ export function useTimesheetCellMutations(
return best;
}
return { handleCellUpdate };
return { handleCellUpdate, cellStatus, cellPendingSeconds };
}

View File

@@ -2,9 +2,11 @@ import { router } from '@inertiajs/vue3';
import { initializeStores } from '@/utils/init';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import axios from 'axios';
import type {
Organization,
OrganizationResponse,
DeleteOrganizationBody,
UpdateOrganizationBody,
} from '@/packages/api/src';
import { useNotificationsStore } from '@/utils/notification';
@@ -38,7 +40,7 @@ export async function switchOrganization(organizationId: string) {
export const useOrganizationStore = defineStore('organization', () => {
const organizationResponse = ref<OrganizationResponse | null>(null);
const { handleApiRequestNotifications } = useNotificationsStore();
const { addNotification, handleApiRequestNotifications } = useNotificationsStore();
async function fetchOrganization() {
const organization = getCurrentOrganizationId();
@@ -78,17 +80,26 @@ export const useOrganizationStore = defineStore('organization', () => {
return response?.data ?? null;
}
async function deleteOrganization(organizationId: string) {
await handleApiRequestNotifications(
() =>
api.deleteOrganization(undefined, {
params: {
organization: organizationId,
},
}),
'Organization deleted successfully',
'Failed to delete organization'
);
async function deleteOrganization(organizationId: string, body: DeleteOrganizationBody) {
try {
await api.deleteOrganization(body, {
params: {
organization: organizationId,
},
});
addNotification('success', 'Organization deleted successfully');
} catch (error) {
if (!axios.isAxiosError(error) || error.response?.status !== 422) {
addNotification(
'error',
'Failed to delete organization',
axios.isAxiosError(error)
? (error.response?.data?.message ?? 'Please try again later.')
: 'Please try again later.'
);
}
throw error;
}
}
const organization = computed<Organization | null>(() => {

View File

@@ -1,7 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query';
import { computed } from 'vue';
import axios from 'axios';
import { api, type UpdateUserBody, type User } from '@/packages/api/src';
import { api, type DeleteUserBody, type UpdateUserBody, type User } from '@/packages/api/src';
import { useNotificationsStore } from '@/utils/notification';
const ME_QUERY_KEY = ['me'] as const;
@@ -61,9 +61,9 @@ export function useDeleteUserMutation() {
const { addNotification } = useNotificationsStore();
return useMutation({
mutationFn: async (userId: string) => {
mutationFn: async ({ userId, body }: { userId: string; body: DeleteUserBody }) => {
try {
await api.deleteUser(undefined, { params: { user: userId } });
await api.deleteUser(body, { params: { user: userId } });
} catch (error) {
if (!axios.isAxiosError(error) || error.response?.status !== 422) {
addNotification(

View File

@@ -33,6 +33,7 @@ Route::get('/shared-report', function () {
Route::middleware([
'auth:web',
'auth.session',
'verified',
])->group(function (): void {
Route::get('/dashboard', [DashboardController::class, 'dashboard'])->name('dashboard');

View File

@@ -441,7 +441,9 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]), [
'password' => 'password',
]);
// Assert
$response->assertForbidden();
@@ -456,12 +458,54 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', ['not-uuid']));
$response = $this->deleteJson(route('api.v1.organizations.destroy', ['not-uuid']), [
'password' => 'password',
]);
// Assert
$response->assertNotFound();
}
public function test_delete_endpoint_fails_without_password(): void
{
// Arrange
$data = $this->createUserWithPermission([
'organizations:delete',
]);
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(Organization::class, [
'id' => $data->organization->getKey(),
]);
}
public function test_delete_endpoint_fails_with_wrong_password(): void
{
// Arrange
$data = $this->createUserWithPermission([
'organizations:delete',
]);
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]), [
'password' => 'wrong-password',
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(Organization::class, [
'id' => $data->organization->getKey(),
]);
}
public function test_delete_endpoint_can_delete_organization(): void
{
// Arrange
@@ -472,7 +516,9 @@ class OrganizationEndpointTest extends ApiEndpointTestAbstract
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]));
$response = $this->deleteJson(route('api.v1.organizations.destroy', [$data->organization->getKey()]), [
'password' => 'password',
]);
// Assert
$response->assertNoContent();

View File

@@ -649,7 +649,9 @@ class UserEndpointTest extends ApiEndpointTestAbstract
Passport::actingAs($otherData->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()), [
'password' => 'password',
]);
// Assert
$response->assertForbidden();
@@ -674,13 +676,15 @@ class UserEndpointTest extends ApiEndpointTestAbstract
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', 'not-valid'));
$response = $this->deleteJson(route('api.v1.users.destroy', 'not-valid'), [
'password' => 'password',
]);
// Assert
$response->assertNotFound();
}
public function test_delete_removes_user(): void
public function test_delete_fails_without_password(): void
{
// Arrange
$data = $this->createUserWithPermission();
@@ -689,6 +693,40 @@ class UserEndpointTest extends ApiEndpointTestAbstract
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()));
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(User::class, ['id' => $data->user->getKey()]);
}
public function test_delete_fails_with_wrong_password(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()), [
'password' => 'wrong-password',
]);
// Assert
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['password']);
$this->assertDatabaseHas(User::class, ['id' => $data->user->getKey()]);
}
public function test_delete_removes_user(): void
{
// Arrange
$data = $this->createUserWithPermission();
Passport::actingAs($data->user);
// Act
$response = $this->deleteJson(route('api.v1.users.destroy', $data->user->getKey()), [
'password' => 'password',
]);
// Assert
$response->assertNoContent();
$this->assertDatabaseMissing(User::class, ['id' => $data->user->getKey()]);

View File

@@ -4,12 +4,17 @@ declare(strict_types=1);
namespace Tests\Unit\Filament\Resources;
use App\Enums\Role;
use App\Events\OrganizationInvitationAdding;
use App\Filament\Resources\OrganizationResource;
use App\Mail\OrganizationInvitationMail;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
use App\Models\User;
use App\Service\DeletionService;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\UsesClass;
@@ -112,4 +117,34 @@ class OrganizationResourceTest extends FilamentTestCase
$response->assertSuccessful();
$response->assertCanSeeTableRecords($organizationInvitations);
}
public function test_can_create_related_invitation(): void
{
// Arrange
Event::fake([
OrganizationInvitationAdding::class,
]);
Mail::fake();
$organization = Organization::factory()->create();
// Act
$response = Livewire::test(OrganizationResource\RelationManagers\InvitationsRelationManager::class, [
'ownerRecord' => $organization,
'pageClass' => OrganizationResource\Pages\EditOrganization::class,
])->callTableAction('create', data: [
'email' => 'new-user@example.com',
'role' => Role::Employee->value,
]);
// Assert
$response->assertSuccessful();
$response->assertHasNoTableActionErrors();
$this->assertDatabaseHas(OrganizationInvitation::class, [
'organization_id' => $organization->getKey(),
'email' => 'new-user@example.com',
'role' => Role::Employee->value,
]);
Event::assertDispatched(OrganizationInvitationAdding::class);
Mail::assertQueued(OrganizationInvitationMail::class);
}
}

View File

@@ -73,13 +73,14 @@ class EnsureEmailIsVerifiedMiddlewareTest extends MiddlewareTestAbstract
$response->assertOk();
}
public function test_users_with_unverified_email_can_access_route_in_local_environment(): void
public function test_users_with_unverified_email_can_access_route_in_local_environment_if_local_email_verification_is_disabled(): void
{
// Arrange
$user = User::factory()->unverified()->create();
$route = $this->createTestRoute();
$this->actingAs($user);
$this->app->detectEnvironment(fn () => 'local');
config(['app.local_email_verification' => false]);
// Act
$response = $this->get($route);
@@ -87,4 +88,36 @@ class EnsureEmailIsVerifiedMiddlewareTest extends MiddlewareTestAbstract
// Assert
$response->assertOk();
}
public function tests_users_with_unverified_email_are_redirected_in_non_local_environment_even_if_local_email_verification_is_disabled(): void
{
// Arrange
$user = User::factory()->unverified()->create();
$route = $this->createTestRoute();
$this->actingAs($user);
$this->assertSame('testing', config('app.env'));
config(['app.local_email_verification' => false]);
// Act
$response = $this->get($route);
// Assert
$response->assertRedirect(route('verification.notice'));
}
public function test_users_with_unverified_email_are_redirected_in_local_environment_if_local_email_verification_is_enabled(): void
{
// Arrange
$user = User::factory()->unverified()->create();
$route = $this->createTestRoute();
$this->actingAs($user);
$this->app->detectEnvironment(fn () => 'local');
config(['app.local_email_verification' => true]);
// Act
$response = $this->get($route);
// Assert
$response->assertRedirect(route('verification.notice'));
}
}