Files
duty-schedule-fe/src/stores/employee.ts
2021-11-04 14:00:52 +01:00

116 lines
3.0 KiB
TypeScript

import { defineStore, acceptHMRUpdate } from 'pinia'
import axios from '@/axios'
import { useUser } from './user'
import { useNotifications } from './notifications'
type ResultData = {
id: number,
firstName: string,
lastName: string | undefined,
shorthand: string,
phone: string | undefined,
mobile: string | undefined,
email: string | undefined,
contractHours: number | undefined,
isActive: boolean,
username: string | undefined,
role: 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,
isActive: false,
username: '',
password: '',
passwordConfirm: ''
},
},
employee: {
id: NaN,
firstName: '',
lastName: '',
shorthand: '',
phone: '',
mobile: '',
email: '',
contractHours: NaN,
isActive: false,
username: '',
password: '',
passwordConfirm: ''
},
}
},
actions: {
async fetchFromApi(id: string | string[]) {
try {
const data : ResultData = await <ResultData>(await axios.get('employees/'+id, {
headers: user.header
})).data
console.log(this.clean.employee)
console.log(data)
Object.assign(this.clean.employee, data)
Object.assign(this.employee, data)
}
catch(err){
if(err instanceof Error) notifications.add('danger', err.message, -1)
else console.log(err)
}
},
reset() {
Object.assign(this.employee, this.clean.employee)
},
/** TODO: #23 Persist user if password is changed */
async persist() {
try {
let result
result = await axios.patch(
'employees/'+this.employee.id,
this.employee,
{
headers: user.header
}
)
Object.assign(this.clean.employee, this.employee)
notifications.add('success', result.statusText)
}
catch(error) {
if(error instanceof Error) notifications.add('danger', error.message, -1)
else console.log(error)
}
}
},
getters: {
}
})
if(import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useEmployee, import.meta.hot))
}