mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-08-16 12:12:15 +01:00
call api for organization create/update/delete and switch
This commit is contained in:
committed by
Constantin Graf
parent
e8f632f330
commit
6c0041d249
@@ -36,8 +36,20 @@ async function createTimeEntry(page, duration: string) {
|
|||||||
test('test that organization name can be updated', async ({ page }) => {
|
test('test that organization name can be updated', async ({ page }) => {
|
||||||
await goToOrganizationSettings(page);
|
await goToOrganizationSettings(page);
|
||||||
await page.getByLabel('Organization Name').fill('NEW ORG NAME');
|
await page.getByLabel('Organization Name').fill('NEW ORG NAME');
|
||||||
await page.getByLabel('Organization Name').press('Enter');
|
await Promise.all([
|
||||||
await page.getByLabel('Organization Name').press('Meta+r');
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/api/v1/organizations/') &&
|
||||||
|
response.request().method() === 'PUT' &&
|
||||||
|
response.status() === 200
|
||||||
|
),
|
||||||
|
page
|
||||||
|
.locator('form')
|
||||||
|
.filter({ hasText: 'Organization Name' })
|
||||||
|
.getByRole('button', { name: 'Save' })
|
||||||
|
.click(),
|
||||||
|
]);
|
||||||
|
await page.reload();
|
||||||
await expect(page.locator('[data-testid="organization_switcher"]:visible')).toContainText(
|
await expect(page.locator('[data-testid="organization_switcher"]:visible')).toContainText(
|
||||||
'NEW ORG NAME'
|
'NEW ORG NAME'
|
||||||
);
|
);
|
||||||
@@ -369,6 +381,124 @@ test('test that format settings persist after page reload', async ({ page }) =>
|
|||||||
await expect(page.getByLabel('Date Format')).toContainText('DD/MM/YYYY');
|
await expect(page.getByLabel('Date Format')).toContainText('DD/MM/YYYY');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// =============================================
|
||||||
|
// Create, Delete & Switch
|
||||||
|
// =============================================
|
||||||
|
|
||||||
|
test.describe('Organization Create, Delete & Switch', () => {
|
||||||
|
async function createOrganization(page, name: string) {
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/teams/create');
|
||||||
|
await page.getByLabel('Organization Name').fill(name);
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/api/v1/organizations') &&
|
||||||
|
response.request().method() === 'POST' &&
|
||||||
|
response.status() === 201
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Create' }).click(),
|
||||||
|
]);
|
||||||
|
// The backend switches the current organization to the new one and the
|
||||||
|
// frontend reloads into its dashboard.
|
||||||
|
await expect(page.getByTestId('dashboard_view')).toBeVisible({ timeout: 10000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
test('can create a new organization and switches to it automatically', async ({ page }) => {
|
||||||
|
const newOrgName = 'CreateOrg' + Math.floor(Math.random() * 100000);
|
||||||
|
await createOrganization(page, newOrgName);
|
||||||
|
|
||||||
|
await expect(page.locator('[data-testid="organization_switcher"]:visible')).toContainText(
|
||||||
|
newOrgName
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not create an organization when the name is empty', async ({ page }) => {
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/teams/create');
|
||||||
|
|
||||||
|
// The form posts to the API, which rejects the empty name with a 422.
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/api/v1/organizations') &&
|
||||||
|
response.request().method() === 'POST' &&
|
||||||
|
response.status() === 422
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Create' }).click(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Validation failed, so we stay on the create form and never reach a
|
||||||
|
// dashboard. ('/teams/create' redirects to '/organizations/create', so
|
||||||
|
// assert on the form rather than the URL.)
|
||||||
|
await expect(page.getByText('Organization Details')).toBeVisible();
|
||||||
|
await expect(page.getByRole('alert')).toContainText('The name field is required.');
|
||||||
|
await expect(page.getByLabel('Organization Name')).toHaveAttribute('aria-invalid', 'true');
|
||||||
|
await expect(page.getByTestId('dashboard_view')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('can delete an organization', async ({ page }) => {
|
||||||
|
// Create a throwaway organization so the primary one is never deleted.
|
||||||
|
const orgName = 'DeleteOrg' + Math.floor(Math.random() * 100000);
|
||||||
|
await createOrganization(page, orgName);
|
||||||
|
|
||||||
|
// Open the (now current) throwaway organization's settings.
|
||||||
|
await goToOrganizationSettings(page);
|
||||||
|
|
||||||
|
// Open the confirmation modal, then confirm inside the dialog.
|
||||||
|
await page.getByRole('button', { name: 'Delete Organization' }).click();
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/api/v1/organizations') &&
|
||||||
|
response.request().method() === 'DELETE' &&
|
||||||
|
response.status() === 204
|
||||||
|
),
|
||||||
|
page.getByRole('dialog').getByRole('button', { name: 'Delete Organization' }).click(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// We are redirected to the dashboard of a different organization.
|
||||||
|
await expect(page.getByTestId('dashboard_view')).toBeVisible({ timeout: 10000 });
|
||||||
|
await expect(
|
||||||
|
page.locator('[data-testid="organization_switcher"]:visible')
|
||||||
|
).not.toContainText(orgName);
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
await expect(orgSwitcher).toBeVisible();
|
||||||
|
const previousOrgNameLines = (await orgSwitcher.innerText())
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const previousOrgName = previousOrgNameLines[previousOrgNameLines.length - 1];
|
||||||
|
|
||||||
|
// Ensure there are at least two organizations to switch between.
|
||||||
|
const orgName = 'SwitchOrg' + Math.floor(Math.random() * 100000);
|
||||||
|
await createOrganization(page, orgName);
|
||||||
|
|
||||||
|
await expect(orgSwitcher).toContainText(orgName);
|
||||||
|
|
||||||
|
// Open the switcher and pick a different organization.
|
||||||
|
await orgSwitcher.click();
|
||||||
|
await expect(page.getByText('Switch Organizations')).toBeVisible();
|
||||||
|
const otherOrgButton = page.getByRole('menuitem', { name: previousOrgName });
|
||||||
|
await expect(otherOrgButton).toBeVisible();
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/users/me/current-organization') &&
|
||||||
|
response.request().method() === 'PUT' &&
|
||||||
|
response.status() === 200
|
||||||
|
),
|
||||||
|
otherOrgButton.click(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await expect(orgSwitcher).not.toContainText(orgName, { timeout: 10000 });
|
||||||
|
await expect(orgSwitcher).toContainText(previousOrgName, { timeout: 10000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// =============================================
|
// =============================================
|
||||||
// Admin Permission Tests
|
// Admin Permission Tests
|
||||||
// =============================================
|
// =============================================
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
import { usePage } from '@inertiajs/vue3';
|
import { usePage } from '@inertiajs/vue3';
|
||||||
import axios from 'axios';
|
|
||||||
import ActionMessage from '@/Components/ActionMessage.vue';
|
import ActionMessage from '@/Components/ActionMessage.vue';
|
||||||
import FormSection from '@/Components/FormSection.vue';
|
import FormSection from '@/Components/FormSection.vue';
|
||||||
import { Field, FieldError, FieldLabel } from '@/packages/ui/src/field';
|
import { Field, FieldError, FieldLabel } from '@/packages/ui/src/field';
|
||||||
@@ -16,6 +15,7 @@ import {
|
|||||||
useUserQuery,
|
useUserQuery,
|
||||||
} from '@/utils/useUserQuery';
|
} from '@/utils/useUserQuery';
|
||||||
import type { UpdateUserBody, User } from '@/packages/api/src';
|
import type { UpdateUserBody, User } from '@/packages/api/src';
|
||||||
|
import { getApiValidationFieldErrors } from '@/utils/apiValidation';
|
||||||
|
|
||||||
const { user } = useUserQuery();
|
const { user } = useUserQuery();
|
||||||
const updateUser = useUpdateUserMutation();
|
const updateUser = useUpdateUserMutation();
|
||||||
@@ -58,17 +58,9 @@ const hasUploadedPhoto = computed(() => {
|
|||||||
return !!url && !url.includes('ui-avatars.com');
|
return !!url && !url.includes('ui-avatars.com');
|
||||||
});
|
});
|
||||||
|
|
||||||
const fieldErrors = computed<Record<string, string>>(() => {
|
const fieldErrors = computed<Record<string, string>>(() =>
|
||||||
const err = updateUser.error.value;
|
getApiValidationFieldErrors(updateUser.error.value)
|
||||||
if (!axios.isAxiosError(err) || err.response?.status !== 422) return {};
|
);
|
||||||
const raw = err.response.data?.errors as Record<string, string[]> | undefined;
|
|
||||||
if (!raw) return {};
|
|
||||||
const flat: Record<string, string> = {};
|
|
||||||
for (const [key, messages] of Object.entries(raw)) {
|
|
||||||
if (Array.isArray(messages) && messages[0]) flat[key] = messages[0];
|
|
||||||
}
|
|
||||||
return flat;
|
|
||||||
});
|
|
||||||
|
|
||||||
function buildPayload(): UpdateUserBody {
|
function buildPayload(): UpdateUserBody {
|
||||||
if (!user.value) return {};
|
if (!user.value) return {};
|
||||||
|
|||||||
@@ -1,25 +1,68 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useForm, usePage } from '@inertiajs/vue3';
|
import { computed, ref, watch } from 'vue';
|
||||||
|
import axios from 'axios';
|
||||||
|
import { router, usePage } from '@inertiajs/vue3';
|
||||||
import FormSection from '@/Components/FormSection.vue';
|
import FormSection from '@/Components/FormSection.vue';
|
||||||
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
|
import { Field, FieldError, FieldLabel } from '@/packages/ui/src/field';
|
||||||
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
||||||
import type { User } from '@/types/models';
|
import type { User } from '@/types/models';
|
||||||
import { initializeStores } from '@/utils/init';
|
import { useOrganizationStore } from '@/utils/useOrganization';
|
||||||
|
import { useNotificationsStore } from '@/utils/notification';
|
||||||
|
import {
|
||||||
|
getApiValidationFieldErrors,
|
||||||
|
getApiValidationMessage,
|
||||||
|
isApiValidationError,
|
||||||
|
} from '@/utils/apiValidation';
|
||||||
|
|
||||||
const form = useForm({
|
const name = ref('');
|
||||||
name: '',
|
const processing = ref(false);
|
||||||
|
const createError = ref<unknown>(null);
|
||||||
|
const organizationStore = useOrganizationStore();
|
||||||
|
const notifications = useNotificationsStore();
|
||||||
|
|
||||||
|
const fieldErrors = computed<Record<string, string>>(() =>
|
||||||
|
getApiValidationFieldErrors(createError.value)
|
||||||
|
);
|
||||||
|
|
||||||
|
watch(name, () => {
|
||||||
|
createError.value = null;
|
||||||
});
|
});
|
||||||
|
|
||||||
const createTeam = () => {
|
const createTeam = async () => {
|
||||||
form.post(route('teams.store'), {
|
processing.value = true;
|
||||||
errorBag: 'createTeam',
|
createError.value = null;
|
||||||
preserveScroll: true,
|
try {
|
||||||
onSuccess: () => {
|
const organization = await organizationStore.createOrganization(name.value);
|
||||||
initializeStores();
|
if (organization) {
|
||||||
},
|
notifications.addNotification('success', 'Organization created successfully');
|
||||||
});
|
// The backend already switched the current organization to the new one.
|
||||||
|
// Flush Inertia's prefetch cache and do a full reload so the new
|
||||||
|
// organization context is picked up everywhere.
|
||||||
|
router.flushAll();
|
||||||
|
router.visit(route('dashboard'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
createError.value = error;
|
||||||
|
if (isApiValidationError(error)) {
|
||||||
|
notifications.addNotification(
|
||||||
|
'error',
|
||||||
|
getApiValidationMessage(error, 'Failed to create organization')
|
||||||
|
);
|
||||||
|
} else if (axios.isAxiosError(error)) {
|
||||||
|
notifications.addNotification(
|
||||||
|
'error',
|
||||||
|
'Failed to create organization',
|
||||||
|
error.response?.data?.message ?? 'Please try again later.'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
notifications.addNotification('error', 'Failed to create organization');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
processing.value = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const page = usePage<{
|
const page = usePage<{
|
||||||
auth: {
|
auth: {
|
||||||
user: User;
|
user: User;
|
||||||
@@ -60,16 +103,17 @@ const page = usePage<{
|
|||||||
<FieldLabel for="name">Organization Name</FieldLabel>
|
<FieldLabel for="name">Organization Name</FieldLabel>
|
||||||
<TextInput
|
<TextInput
|
||||||
id="name"
|
id="name"
|
||||||
v-model="form.name"
|
v-model="name"
|
||||||
type="text"
|
type="text"
|
||||||
class="block w-full"
|
class="block w-full"
|
||||||
autofocus />
|
autofocus
|
||||||
<FieldError v-if="form.errors.name">{{ form.errors.name }}</FieldError>
|
:aria-invalid="Boolean(fieldErrors.name)" />
|
||||||
|
<FieldError v-if="fieldErrors.name">{{ fieldErrors.name }}</FieldError>
|
||||||
</Field>
|
</Field>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template #actions>
|
<template #actions>
|
||||||
<PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
|
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
|
||||||
Create
|
Create
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,26 +1,36 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import { useForm } from '@inertiajs/vue3';
|
import { router } from '@inertiajs/vue3';
|
||||||
import ActionSection from '@/Components/ActionSection.vue';
|
import ActionSection from '@/Components/ActionSection.vue';
|
||||||
import ConfirmationModal from '@/Components/ConfirmationModal.vue';
|
import ConfirmationModal from '@/Components/ConfirmationModal.vue';
|
||||||
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
|
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
|
||||||
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||||
|
import { useOrganizationStore } from '@/utils/useOrganization';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps<{
|
||||||
team: Object,
|
team: { id: string };
|
||||||
});
|
}>();
|
||||||
|
|
||||||
const confirmingTeamDeletion = ref(false);
|
const confirmingTeamDeletion = ref(false);
|
||||||
const form = useForm({});
|
const processing = ref(false);
|
||||||
|
const organizationStore = useOrganizationStore();
|
||||||
|
|
||||||
const confirmTeamDeletion = () => {
|
const confirmTeamDeletion = () => {
|
||||||
confirmingTeamDeletion.value = true;
|
confirmingTeamDeletion.value = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteTeam = () => {
|
const deleteTeam = async () => {
|
||||||
form.delete(route('teams.destroy', props.team), {
|
processing.value = true;
|
||||||
errorBag: 'deleteTeam',
|
try {
|
||||||
});
|
await organizationStore.deleteOrganization(props.team.id);
|
||||||
|
// 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.
|
||||||
|
processing.value = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -59,8 +69,8 @@ const deleteTeam = () => {
|
|||||||
|
|
||||||
<DangerButton
|
<DangerButton
|
||||||
class="ms-3"
|
class="ms-3"
|
||||||
:class="{ 'opacity-25': form.processing }"
|
:class="{ 'opacity-25': processing }"
|
||||||
:disabled="form.processing"
|
:disabled="processing"
|
||||||
@click="deleteTeam">
|
@click="deleteTeam">
|
||||||
Delete Organization
|
Delete Organization
|
||||||
</DangerButton>
|
</DangerButton>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Link, useForm } from '@inertiajs/vue3';
|
import { Link, router } from '@inertiajs/vue3';
|
||||||
|
import { reactive, ref } from 'vue';
|
||||||
|
import axios from 'axios';
|
||||||
import ActionMessage from '@/Components/ActionMessage.vue';
|
import ActionMessage from '@/Components/ActionMessage.vue';
|
||||||
import FormSection from '@/Components/FormSection.vue';
|
import FormSection from '@/Components/FormSection.vue';
|
||||||
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
|
import { Field, FieldLabel, FieldError } from '@/packages/ui/src/field';
|
||||||
@@ -10,22 +12,66 @@ import type { Permissions } from '@/types/jetstream';
|
|||||||
import { CreditCardIcon } from '@heroicons/vue/20/solid';
|
import { CreditCardIcon } from '@heroicons/vue/20/solid';
|
||||||
import { isBillingActivated } from '@/utils/billing';
|
import { isBillingActivated } from '@/utils/billing';
|
||||||
import { canManageBilling } from '@/utils/permissions';
|
import { canManageBilling } from '@/utils/permissions';
|
||||||
|
import { api } from '@/packages/api/src';
|
||||||
|
import { useNotificationsStore } from '@/utils/notification';
|
||||||
|
import { getApiValidationFieldErrors, isApiValidationError } from '@/utils/apiValidation';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
team: Organization;
|
team: Organization;
|
||||||
permissions: Permissions;
|
permissions: Permissions;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const form = useForm({
|
const form = reactive({
|
||||||
name: props.team.name,
|
name: props.team.name,
|
||||||
currency: props.team.currency,
|
currency: props.team.currency,
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateTeamName = () => {
|
const errors = ref<Record<string, string>>({});
|
||||||
form.put(route('teams.update', props.team.id), {
|
const processing = ref(false);
|
||||||
errorBag: 'updateTeamName',
|
const recentlySuccessful = ref(false);
|
||||||
preserveScroll: true,
|
const notifications = useNotificationsStore();
|
||||||
});
|
let recentlySuccessfulTimeout: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
const updateTeamName = async () => {
|
||||||
|
processing.value = true;
|
||||||
|
recentlySuccessful.value = false;
|
||||||
|
errors.value = {};
|
||||||
|
try {
|
||||||
|
await api.updateOrganization(
|
||||||
|
{
|
||||||
|
name: form.name,
|
||||||
|
currency: form.currency,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
params: {
|
||||||
|
organization: props.team.id,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
notifications.addNotification('success', 'Organization updated successfully');
|
||||||
|
recentlySuccessful.value = true;
|
||||||
|
if (recentlySuccessfulTimeout) {
|
||||||
|
clearTimeout(recentlySuccessfulTimeout);
|
||||||
|
}
|
||||||
|
recentlySuccessfulTimeout = setTimeout(() => {
|
||||||
|
recentlySuccessful.value = false;
|
||||||
|
}, 2000);
|
||||||
|
router.reload({ only: ['auth', 'team'] });
|
||||||
|
} catch (error) {
|
||||||
|
if (isApiValidationError(error)) {
|
||||||
|
errors.value = getApiValidationFieldErrors(error);
|
||||||
|
} else if (axios.isAxiosError(error)) {
|
||||||
|
notifications.addNotification(
|
||||||
|
'error',
|
||||||
|
'Failed to update organization',
|
||||||
|
error.response?.data?.message ?? 'Please try again later.'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
notifications.addNotification('error', 'Failed to update organization');
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
processing.value = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -74,7 +120,7 @@ const updateTeamName = () => {
|
|||||||
class="block w-full"
|
class="block w-full"
|
||||||
:disabled="!permissions.canUpdateTeam" />
|
:disabled="!permissions.canUpdateTeam" />
|
||||||
|
|
||||||
<FieldError v-if="form.errors.name">{{ form.errors.name }}</FieldError>
|
<FieldError v-if="errors.name">{{ errors.name }}</FieldError>
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<!-- Currency -->
|
<!-- Currency -->
|
||||||
@@ -94,14 +140,14 @@ const updateTeamName = () => {
|
|||||||
{{ currencyKey }} - {{ currencyTranslated }}
|
{{ currencyKey }} - {{ currencyTranslated }}
|
||||||
</option>
|
</option>
|
||||||
</select>
|
</select>
|
||||||
<FieldError v-if="form.errors.currency">{{ form.errors.currency }}</FieldError>
|
<FieldError v-if="errors.currency">{{ errors.currency }}</FieldError>
|
||||||
</Field>
|
</Field>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template v-if="permissions.canUpdateTeam" #actions>
|
<template v-if="permissions.canUpdateTeam" #actions>
|
||||||
<ActionMessage :on="form.recentlySuccessful" class="me-3"> Saved. </ActionMessage>
|
<ActionMessage :on="recentlySuccessful" class="me-3"> Saved. </ActionMessage>
|
||||||
|
|
||||||
<PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
|
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
|
||||||
Save
|
Save
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -803,6 +803,39 @@ const endpoints = makeApi([
|
|||||||
z.object({ code: z.string(), name: z.string(), symbol: z.string() }).passthrough()
|
z.object({ code: z.string(), name: z.string(), symbol: z.string() }).passthrough()
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: 'post',
|
||||||
|
path: '/v1/organizations',
|
||||||
|
alias: 'createOrganization',
|
||||||
|
requestFormat: 'json',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
name: 'body',
|
||||||
|
type: 'Body',
|
||||||
|
schema: z.object({ name: z.string().max(255) }).passthrough(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
response: z.object({ data: OrganizationResource }).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: 422,
|
||||||
|
description: `Validation error`,
|
||||||
|
schema: z
|
||||||
|
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
|
||||||
|
.passthrough(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
method: 'get',
|
method: 'get',
|
||||||
path: '/v1/organizations/:organization',
|
path: '/v1/organizations/:organization',
|
||||||
@@ -877,6 +910,37 @@ const endpoints = makeApi([
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: 'delete',
|
||||||
|
path: '/v1/organizations/:organization',
|
||||||
|
alias: 'deleteOrganization',
|
||||||
|
requestFormat: 'json',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
name: 'organization',
|
||||||
|
type: 'Path',
|
||||||
|
schema: z.string(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
response: z.void(),
|
||||||
|
errors: [
|
||||||
|
{
|
||||||
|
status: 401,
|
||||||
|
description: `Unauthenticated`,
|
||||||
|
schema: z.object({ message: z.string() }).passthrough(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 403,
|
||||||
|
description: `Authorization error`,
|
||||||
|
schema: z.object({ message: z.string() }).passthrough(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 404,
|
||||||
|
description: `Not found`,
|
||||||
|
schema: z.object({ message: z.string() }).passthrough(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
method: 'get',
|
method: 'get',
|
||||||
path: '/v1/organizations/:organization/charts/daily-tracked-hours',
|
path: '/v1/organizations/:organization/charts/daily-tracked-hours',
|
||||||
@@ -4495,6 +4559,42 @@ The report is considered public if the `is_public` field is set to &#x
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: 'put',
|
||||||
|
path: '/v1/users/me/current-organization',
|
||||||
|
alias: 'updateMyCurrentOrganization',
|
||||||
|
description: `Switches the organization that the user is currently working in. The user
|
||||||
|
must be a member of the given organization. This endpoint is independent of
|
||||||
|
the organization.`,
|
||||||
|
requestFormat: 'json',
|
||||||
|
parameters: [
|
||||||
|
{
|
||||||
|
name: 'body',
|
||||||
|
type: 'Body',
|
||||||
|
schema: z.object({ organization_id: z.string().uuid() }).passthrough(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
response: z.object({ data: UserResource }).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: 422,
|
||||||
|
description: `Validation error`,
|
||||||
|
schema: z
|
||||||
|
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
|
||||||
|
.passthrough(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
method: 'put',
|
method: 'put',
|
||||||
path: '/v1/users/:user',
|
path: '/v1/users/:user',
|
||||||
|
|||||||
31
resources/js/utils/apiValidation.ts
Normal file
31
resources/js/utils/apiValidation.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import axios, { type AxiosError } from 'axios';
|
||||||
|
|
||||||
|
type ApiValidationResponse = {
|
||||||
|
message?: string;
|
||||||
|
errors?: Record<string, string[]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isApiValidationError(error: unknown): error is AxiosError<ApiValidationResponse> {
|
||||||
|
return axios.isAxiosError<ApiValidationResponse>(error) && error.response?.status === 422;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getApiValidationFieldErrors(error: unknown): Record<string, string> {
|
||||||
|
if (!isApiValidationError(error)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const fieldErrors: Record<string, string> = {};
|
||||||
|
for (const [field, messages] of Object.entries(error.response?.data?.errors ?? {})) {
|
||||||
|
if (Array.isArray(messages) && messages[0]) {
|
||||||
|
fieldErrors[field] = messages[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fieldErrors;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getApiValidationMessage(error: unknown, fallback: string): string {
|
||||||
|
if (!isApiValidationError(error)) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return error.response?.data?.message ?? fallback;
|
||||||
|
}
|
||||||
@@ -11,23 +11,29 @@ import { useNotificationsStore } from '@/utils/notification';
|
|||||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||||
import { api } from '@/packages/api/src';
|
import { api } from '@/packages/api/src';
|
||||||
|
|
||||||
export function switchOrganization(organizationId: string) {
|
export async function switchOrganization(organizationId: string) {
|
||||||
// Clear Inertia's prefetch cache to prevent stale pages from the old
|
const { handleApiRequestNotifications } = useNotificationsStore();
|
||||||
// organization being served when navigating after the switch.
|
try {
|
||||||
router.flushAll();
|
await handleApiRequestNotifications(
|
||||||
|
() => api.updateMyCurrentOrganization({ organization_id: organizationId }),
|
||||||
|
undefined,
|
||||||
|
'Failed to switch organization'
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// The error notification is surfaced by the request handler.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
router.put(
|
// The current organization changed server-side. Clear Inertia's prefetch
|
||||||
route('current-team.update'),
|
// cache and reload into the dashboard so the new organization context
|
||||||
{
|
// (auth.user.current_team) is picked up everywhere.
|
||||||
team_id: organizationId,
|
router.flushAll();
|
||||||
|
router.visit(route('dashboard'), {
|
||||||
|
preserveState: false,
|
||||||
|
onSuccess: () => {
|
||||||
|
initializeStores();
|
||||||
},
|
},
|
||||||
{
|
});
|
||||||
preserveState: false,
|
|
||||||
onSuccess: () => {
|
|
||||||
initializeStores();
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useOrganizationStore = defineStore('organization', () => {
|
export const useOrganizationStore = defineStore('organization', () => {
|
||||||
@@ -67,9 +73,33 @@ export const useOrganizationStore = defineStore('organization', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function createOrganization(name: string): Promise<Organization | null> {
|
||||||
|
const response = await api.createOrganization({ name });
|
||||||
|
return response?.data ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteOrganization(organizationId: string) {
|
||||||
|
await handleApiRequestNotifications(
|
||||||
|
() =>
|
||||||
|
api.deleteOrganization(undefined, {
|
||||||
|
params: {
|
||||||
|
organization: organizationId,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
'Organization deleted successfully',
|
||||||
|
'Failed to delete organization'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const organization = computed<Organization | null>(() => {
|
const organization = computed<Organization | null>(() => {
|
||||||
return organizationResponse.value?.data || null;
|
return organizationResponse.value?.data || null;
|
||||||
});
|
});
|
||||||
|
|
||||||
return { organization, fetchOrganization, updateOrganization };
|
return {
|
||||||
|
organization,
|
||||||
|
fetchOrganization,
|
||||||
|
updateOrganization,
|
||||||
|
createOrganization,
|
||||||
|
deleteOrganization,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user