diff --git a/src/stores/employee.ts b/src/stores/employee.ts new file mode 100644 index 0000000..dd71558 --- /dev/null +++ b/src/stores/employee.ts @@ -0,0 +1,123 @@ +import { defineStore, acceptHMRUpdate } from 'pinia' +import axios from '@/axios' +import { useUser } from './user' +import { useNotifications } from './notifications' + +type ResultData = { + employee: { + id: number, + firstName: string, + lastName: string, + shorthand: string, + phone: string, + mobile: string, + email: string, + contractHours: number, + hasUser: boolean, + }, + user?: { + id?: number, + username?: string + } +} + +const user = useUser() +const notifications = useNotifications() + +export const useEmployee = defineStore({ + id: 'employee', + + state: () => { + return { + clean: { + employee: { + id: NaN, + firstName: '', + lastName: '', + shorthand: '', + phone: '', + mobile: '', + email: '', + contractHours: NaN, + hasUser: false + }, + user: { + id: NaN, + username: '', + password: '', + passwordConfirm: '', + } + }, + + employee: { + id: NaN, + firstName: '', + lastName: '', + shorthand: '', + phone: '', + mobile: '', + email: '', + contractHours: NaN, + hasUser: false + }, + + user: { + id: NaN, + username: '', + password: '', + passwordConfirm: '' + } + } + }, + + actions: { + async fetchFromApi(id: string | string[]) { + + try { + const data : ResultData = await (await axios.get('employees/'+id, { + headers: { + 'Authorization': 'Bearer '+user.token + } + })).data + + Object.assign(this.clean.employee, data.employee) + Object.assign(this.clean.user, data.user) + Object.assign(this.employee, data.employee), + Object.assign(this.user, data.user) + } + catch(err){ + if(err instanceof Error) notifications.add('danger', err.message, -1) + else console.log(err) + } + }, + + reset() { + Object.assign(this.user, this.clean.user) + Object.assign(this.employee, this.clean.employee) + }, + + /** TODO: #23 Persist user if password is changed */ + async persist() { + try { + const result = await axios.patch('employees/'+this.employee.id, this.employee, + { + headers: { + 'Authorization': 'Bearer '+user.token + } + } + ) + Object.assign(this.clean.employee, this.employee) + Object.assign(this.clean.user, this.user) + notifications.add('success', result.statusText) + } + catch(error) { + if(error instanceof Error) notifications.add('danger', error.message, -1) + else console.log(error) + } + } + } +}) + +if(import.meta.hot) { + import.meta.hot.accept(acceptHMRUpdate(useEmployee, import.meta.hot)) +} \ No newline at end of file diff --git a/src/views/EmployeesDetails.vue b/src/views/EmployeesDetails.vue index 32331ab..d950f9d 100644 --- a/src/views/EmployeesDetails.vue +++ b/src/views/EmployeesDetails.vue @@ -69,8 +69,8 @@ {{}} - -
+ +
{{error.$message}}
@@ -99,59 +99,18 @@