Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
502 changes: 222 additions & 280 deletions apps/settings/src/components/UserList.vue

Large diffs are not rendered by default.

42 changes: 21 additions & 21 deletions apps/settings/src/components/Users/EditUserDialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,25 @@
import { mount } from '@vue/test-utils'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const confirmPassword = vi.hoisted(() => vi.fn())
// `<script setup>` children and `useStore()` are invisible to VTU stubs/mocks,
// so swap them via `vi.mock` (see dialogTestHelpers).
const { confirmPassword, dispatch } = vi.hoisted(() => ({ confirmPassword: vi.fn(), dispatch: vi.fn() }))

vi.mock('@nextcloud/password-confirmation', () => ({ confirmPassword }))
vi.mock('@nextcloud/dialogs', () => ({ showError: vi.fn(), showSuccess: vi.fn() }))
vi.mock('../../store/index.js', () => ({
useStore: () => ({
dispatch,
getters: {
getGroups: [],
getServerData: { languages: [], canChangePassword: true },
getPasswordPolicyMinLength: 8,
},
}),
}))
vi.mock('@nextcloud/vue/components/NcDialog', async () => ({ default: (await import('./dialogTestHelpers.ts')).NcDialogStub }))
vi.mock('@nextcloud/vue/components/NcButton', async () => ({ default: (await import('./dialogTestHelpers.ts')).NcButtonStub }))
vi.mock('./UserFormFields.vue', async () => ({ default: (await import('./dialogTestHelpers.ts')).UserFormFieldsStub }))

// Decouple the dialog test from form-data diffing internals: always report a
// non-empty change set so save() proceeds past its early return. Other exports
Expand All @@ -31,30 +47,14 @@ vi.mock('./userFormUtils.ts', async (importActual) => ({

import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
import EditUserDialog from './EditUserDialog.vue'
import { flushPromises, NcButtonStub, NcDialogStub, UserFormFieldsStub } from './dialogTestHelpers.ts'
import { flushPromises, NcDialogStub } from './dialogTestHelpers.ts'

function mountDialog({ dispatch = vi.fn() } = {}) {
function mountDialog() {
return mount(EditUserDialog, {
propsData: {
user: { id: 'bob', backendCapabilities: { setPassword: true } },
quotaOptions: [],
},
mocks: {
t: (_app: string, text: string) => text,
$store: {
dispatch,
getters: {
getGroups: [],
getServerData: { languages: [], canChangePassword: true },
getPasswordPolicyMinLength: 8,
},
},
},
stubs: {
NcDialog: NcDialogStub,
NcButton: NcButtonStub,
UserFormFields: UserFormFieldsStub,
},
})
}

Expand All @@ -65,8 +65,8 @@ describe('EditUserDialog loading feedback', () => {
})

it('does not dispatch a second save request while one is in flight', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()

await wrapper.find('form').trigger('submit')
await flushPromises()
Expand Down
172 changes: 76 additions & 96 deletions apps/settings/src/components/Users/EditUserDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -41,120 +41,100 @@
</NcDialog>
</template>

<script>
<script setup lang="ts">
import type { IUser } from '../../views/user-types.d.ts'
import type { QuotaOption } from './userFormUtils.ts'

import { showError, showSuccess } from '@nextcloud/dialogs'
import { translate as t } from '@nextcloud/l10n'
import { confirmPassword } from '@nextcloud/password-confirmation'
import { computed, provide, reactive, ref } from 'vue'
import NcButton from '@nextcloud/vue/components/NcButton'
import NcDialog from '@nextcloud/vue/components/NcDialog'
import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
import UserFormFields from './UserFormFields.vue'
import logger from '../../logger.ts'
import { useStore } from '../../store/index.js'
import { formDataKey } from './injectionKeys.ts'
import { diffPayload, userToFormData } from './userFormUtils.ts'

export default {
name: 'EditUserDialog',
const props = defineProps<{
user: IUser
quotaOptions: QuotaOption[]
}>()

components: {
NcButton,
NcDialog,
NcLoadingIcon,
UserFormFields,
},
const emit = defineEmits<{
closing: []
}>()

// Children inject this reactive object and mutate its properties via v-model.
// Do not reassign editedUser entirely, the injected reference would go stale.
provide() {
return {
formData: this.editedUser,
}
},
const store = useStore()

props: {
user: {
type: Object,
required: true,
},
const allGroups = store.getters.getGroups
const serverLanguages = store.getters.getServerData.languages
const formData = userToFormData(props.user, allGroups, props.quotaOptions, serverLanguages)

quotaOptions: {
type: Array,
required: true,
},
},
const initialData = structuredClone(formData)
// Children inject and mutate this object's properties; never reassign it or the
// injected reference goes stale.
const editedUser = reactive(formData)
const saving = ref(false)
const fieldErrors = ref<Record<string, string>>({})

emits: ['closing'],

data() {
const allGroups = this.$store.getters.getGroups
const serverLanguages = this.$store.getters.getServerData.languages
const formData = userToFormData(this.user, allGroups, this.quotaOptions, serverLanguages)
return {
/** Snapshot of initial state for diffing */
initialData: structuredClone(formData),
/** Mutable form state */
editedUser: formData,
saving: false,
fieldErrors: {},
}
},
provide(formDataKey, editedUser)

computed: {
settings() {
return this.$store.getters.getServerData
},

fieldConfig() {
return {
username: {
show: true,
disabled: true,
label: t('settings', 'Account name'),
},

password: {
show: this.settings.canChangePassword && this.user.backendCapabilities.setPassword,
label: t('settings', 'New password'),
},
}
},
const settings = computed(() => store.getters.getServerData)

const fieldConfig = computed(() => ({
username: {
show: true,
disabled: true,
label: t('settings', 'Account name'),
},

methods: {
async save() {
// Guard against re-submit while a request is already running. The
// button is only aria-disabled (not disabled), so it can still fire.
if (this.saving) {
return
}
this.fieldErrors = {}

const payload = diffPayload(this.initialData, this.editedUser)
if (Object.keys(payload).length === 0) {
this.$emit('closing')
return
}

this.saving = true
try {
await confirmPassword()
await this.$store.dispatch('editUserMultiField', {
userid: this.user.id,
payload,
})
showSuccess(t('settings', 'Account updated'))
this.$emit('closing')
} catch (error) {
const errors = error.response?.data?.ocs?.data?.errors
if (errors && typeof errors === 'object') {
this.fieldErrors = errors
} else {
logger.error('Failed to update account', { error })
showError(t('settings', 'Failed to update account'))
}
} finally {
this.saving = false
}
},
password: {
show: settings.value.canChangePassword && props.user.backendCapabilities.setPassword,
label: t('settings', 'New password'),
},
}))

/**
* Submit the changed fields; map a 422 to per-field errors, else close.
*/
async function save() {
// Guard against re-submit while a request is already running. The
// button is only aria-disabled (not disabled), so it can still fire.
if (saving.value) {
return
}
fieldErrors.value = {}

const payload = diffPayload(initialData, editedUser)
if (Object.keys(payload).length === 0) {
emit('closing')
return
}

saving.value = true
try {
await confirmPassword()
await store.dispatch('editUserMultiField', {
userid: props.user.id,
payload,
})
showSuccess(t('settings', 'Account updated'))
emit('closing')
} catch (error) {
const errors = (error as { response?: { data?: { ocs?: { data?: { errors?: Record<string, string> } } } } })
.response?.data?.ocs?.data?.errors
if (errors && typeof errors === 'object') {
fieldErrors.value = errors
} else {
logger.error('Failed to update account', { error })
showError(t('settings', 'Failed to update account'))
}
} finally {
saving.value = false
}
}
</script>

Expand Down
61 changes: 32 additions & 29 deletions apps/settings/src/components/Users/NewUserDialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,27 @@

import { mount } from '@vue/test-utils'
import { beforeEach, describe, expect, it, vi } from 'vitest'

// `<script setup>` children and `useStore()` are invisible to VTU stubs/mocks,
// so swap them via `vi.mock` (see dialogTestHelpers).
const { dispatch } = vi.hoisted(() => ({ dispatch: vi.fn() }))

vi.mock('../../store/index.js', () => ({
useStore: () => ({
dispatch,
getters: {
getServerData: { newUserGenerateUserID: false, newUserRequireEmail: false },
getPasswordPolicyMinLength: 8,
},
}),
}))
vi.mock('@nextcloud/vue/components/NcDialog', async () => ({ default: (await import('./dialogTestHelpers.ts')).NcDialogStub }))
vi.mock('@nextcloud/vue/components/NcButton', async () => ({ default: (await import('./dialogTestHelpers.ts')).NcButtonStub }))
vi.mock('./UserFormFields.vue', async () => ({ default: (await import('./dialogTestHelpers.ts')).UserFormFieldsStub }))

import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
import NewUserDialog from './NewUserDialog.vue'
import { flushPromises, NcButtonStub, NcDialogStub, UserFormFieldsStub } from './dialogTestHelpers.ts'
import { flushPromises, NcDialogStub } from './dialogTestHelpers.ts'

function makeNewUser(overrides = {}) {
return {
Expand All @@ -24,28 +42,13 @@ function makeNewUser(overrides = {}) {
}
}

function mountDialog({ dispatch = vi.fn(), loading = { all: false } } = {}) {
function mountDialog({ loading = { all: false } } = {}) {
return mount(NewUserDialog, {
propsData: {
loading,
newUser: makeNewUser(),
quotaOptions: [],
},
mocks: {
t: (_app: string, text: string) => text,
$store: {
dispatch,
getters: {
getServerData: { newUserGenerateUserID: false, newUserRequireEmail: false },
getPasswordPolicyMinLength: 8,
},
},
},
stubs: {
NcDialog: NcDialogStub,
NcButton: NcButtonStub,
UserFormFields: UserFormFieldsStub,
},
})
}

Expand All @@ -55,8 +58,8 @@ describe('NewUserDialog loading feedback', () => {
})

it('does not dispatch a second create request while one is in flight', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()

await wrapper.find('form').trigger('submit')
await wrapper.find('form').trigger('submit')
Expand All @@ -66,8 +69,8 @@ describe('NewUserDialog loading feedback', () => {
})

it('marks the form as busy and inert while creating', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()

await wrapper.find('form').trigger('submit')

Expand All @@ -77,8 +80,8 @@ describe('NewUserDialog loading feedback', () => {
})

it('shows a spinner and busy label on the submit button while creating', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()

await wrapper.find('form').trigger('submit')

Expand All @@ -87,8 +90,8 @@ describe('NewUserDialog loading feedback', () => {
})

it('sets aria-disabled (not disabled) on the submit button while creating', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()
const submit = wrapper.find('[data-test="submit"]')

expect(submit.attributes('aria-disabled')).toBe('false')
Expand All @@ -101,8 +104,8 @@ describe('NewUserDialog loading feedback', () => {
})

it('prevents closing the dialog while creating', async () => {
const dispatch = vi.fn().mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog({ dispatch })
dispatch.mockReturnValue(new Promise(() => {}))
const wrapper = mountDialog()
const dialog = wrapper.findComponent(NcDialogStub)

expect(dialog.props('noClose')).toBe(false)
Expand All @@ -114,9 +117,9 @@ describe('NewUserDialog loading feedback', () => {

it('re-enables the form when the request fails', async () => {
const error = { response: { data: { ocs: { meta: { statuscode: 0 } } } } }
const dispatch = vi.fn().mockRejectedValue(error)
dispatch.mockRejectedValue(error)
const loading = { all: false }
const wrapper = mountDialog({ dispatch, loading })
const wrapper = mountDialog({ loading })

await wrapper.find('form').trigger('submit')
await flushPromises()
Expand Down
Loading
Loading