call api for organization create/update/delete and switch

This commit is contained in:
Gregor Vostrak
2026-06-09 00:12:55 +02:00
committed by Constantin Graf
parent 0c825a691e
commit e3e45161a1
8 changed files with 452 additions and 69 deletions

View File

@@ -1,7 +1,6 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { usePage } from '@inertiajs/vue3';
import axios from 'axios';
import ActionMessage from '@/Components/ActionMessage.vue';
import FormSection from '@/Components/FormSection.vue';
import { Field, FieldError, FieldLabel } from '@/packages/ui/src/field';
@@ -16,6 +15,7 @@ import {
useUserQuery,
} from '@/utils/useUserQuery';
import type { UpdateUserBody, User } from '@/packages/api/src';
import { getApiValidationFieldErrors } from '@/utils/apiValidation';
const { user } = useUserQuery();
const updateUser = useUpdateUserMutation();
@@ -58,17 +58,9 @@ const hasUploadedPhoto = computed(() => {
return !!url && !url.includes('ui-avatars.com');
});
const fieldErrors = computed<Record<string, string>>(() => {
const err = 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;
});
const fieldErrors = computed<Record<string, string>>(() =>
getApiValidationFieldErrors(updateUser.error.value)
);
function buildPayload(): UpdateUserBody {
if (!user.value) return {};

View File

@@ -1,25 +1,68 @@
<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 { 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 TextInput from '@/packages/ui/src/Input/TextInput.vue';
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({
name: '',
const name = ref('');
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 = () => {
form.post(route('teams.store'), {
errorBag: 'createTeam',
preserveScroll: true,
onSuccess: () => {
initializeStores();
},
});
const createTeam = async () => {
processing.value = true;
createError.value = null;
try {
const organization = await organizationStore.createOrganization(name.value);
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<{
auth: {
user: User;
@@ -60,16 +103,17 @@ const page = usePage<{
<FieldLabel for="name">Organization Name</FieldLabel>
<TextInput
id="name"
v-model="form.name"
v-model="name"
type="text"
class="block w-full"
autofocus />
<FieldError v-if="form.errors.name">{{ form.errors.name }}</FieldError>
autofocus
:aria-invalid="Boolean(fieldErrors.name)" />
<FieldError v-if="fieldErrors.name">{{ fieldErrors.name }}</FieldError>
</Field>
</template>
<template #actions>
<PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
Create
</PrimaryButton>
</template>

View File

@@ -1,26 +1,36 @@
<script setup lang="ts">
import { ref } from 'vue';
import { useForm } from '@inertiajs/vue3';
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 SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import { useOrganizationStore } from '@/utils/useOrganization';
const props = defineProps({
team: Object,
});
const props = defineProps<{
team: { id: string };
}>();
const confirmingTeamDeletion = ref(false);
const form = useForm({});
const processing = ref(false);
const organizationStore = useOrganizationStore();
const confirmTeamDeletion = () => {
confirmingTeamDeletion.value = true;
};
const deleteTeam = () => {
form.delete(route('teams.destroy', props.team), {
errorBag: 'deleteTeam',
});
const deleteTeam = async () => {
processing.value = true;
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>
@@ -59,8 +69,8 @@ const deleteTeam = () => {
<DangerButton
class="ms-3"
:class="{ 'opacity-25': form.processing }"
:disabled="form.processing"
:class="{ 'opacity-25': processing }"
:disabled="processing"
@click="deleteTeam">
Delete Organization
</DangerButton>

View File

@@ -1,5 +1,7 @@
<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 FormSection from '@/Components/FormSection.vue';
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 { isBillingActivated } from '@/utils/billing';
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<{
team: Organization;
permissions: Permissions;
}>();
const form = useForm({
const form = reactive({
name: props.team.name,
currency: props.team.currency,
});
const updateTeamName = () => {
form.put(route('teams.update', props.team.id), {
errorBag: 'updateTeamName',
preserveScroll: true,
});
const errors = ref<Record<string, string>>({});
const processing = ref(false);
const recentlySuccessful = ref(false);
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>
@@ -74,7 +120,7 @@ const updateTeamName = () => {
class="block w-full"
:disabled="!permissions.canUpdateTeam" />
<FieldError v-if="form.errors.name">{{ form.errors.name }}</FieldError>
<FieldError v-if="errors.name">{{ errors.name }}</FieldError>
</Field>
<!-- Currency -->
@@ -94,14 +140,14 @@ const updateTeamName = () => {
{{ currencyKey }} - {{ currencyTranslated }}
</option>
</select>
<FieldError v-if="form.errors.currency">{{ form.errors.currency }}</FieldError>
<FieldError v-if="errors.currency">{{ errors.currency }}</FieldError>
</Field>
</template>
<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
</PrimaryButton>
</template>