import { defineStore, acceptHMRUpdate } from 'pinia' import axios from '@/axios' import { useUser } from './user' import { useNotifications } from './notifications' import Axios from 'axios' const user = useUser() const notifications = useNotifications() export const useEmployee = defineStore({ id: 'employee', state: () => { return { clean: { /** @type { Employee } */ employee: { id: NaN, firstName: '', lastName: '', shorthand: '', phone: '', mobile: '', email: '', contractHours: 0, isActive: false, username: '', password: '', passwordConfirm: '', role: '' }, }, /** @type Employee */ employee: { id: NaN, firstName: '', lastName: '', shorthand: '', phone: '', mobile: '', email: '', contractHours: 0, isActive: false, username: '', password: '', passwordConfirm: '', role: '' }, /** @type { EmployeeApiValidationError[] } */ apiValidationErrors: Array(), } }, actions: { assignTruthyValues(target: Object, source: Object) { for (const key in source) { if (source[key]) { target[key] = source[key] } } }, async fetchFromApi(id: string | string[]) { this.$reset() try { const data : Employee = await (await axios.get('employees/'+id, { headers: user.header })).data this.assignTruthyValues(this.employee, data) this.assignTruthyValues(this.clean.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) }, async persist() { if(this.employee.id){ this.patchEmployee() } else { this.postEmployee() } }, async patchEmployee() { try { let result let payload = Object.assign({}, this.employee) if (this.employee.password === this.clean.employee.password) { payload.username = '' payload.password = '' } result = await axios.patch( 'employees/'+this.employee.id, payload, { headers: user.header } ) this.employee.password = '' this.employee.passwordConfirm = '' Object.assign(this.clean.employee, this.employee) notifications.add('success', result.statusText) } catch(error) { if(error instanceof Error) { console.log(error) notifications.add('danger', error.message, -1) } else console.log(error) } }, async postEmployee() { let result try { result = await axios.post( 'employees', this.employee, { headers: user.header } ) this.assignTruthyValues(this.employee, result.data) this.assignTruthyValues(this.clean.employee, result.data) notifications.add('success', result.statusText) console.log(result) } catch(error){ console.log("enter catch") if(Axios.isAxiosError(error)) { console.log("enter axios error") let data = error.response?.data as { errors: EmployeeApiValidationError[] } console.log(data) this.apiValidationErrors = [...data.errors] } } }, }, getters: { userEnabled: (state) => { return state.clean.employee.username ? true : false } } }) if(import.meta.hot) { import.meta.hot.accept(acceptHMRUpdate(useEmployee, import.meta.hot)) }