index.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { defineStore } from 'pinia'
  2. import type { UserInfo, UserState } from './helper'
  3. import { defaultSetting, getLocalState, setLocalState } from './helper'
  4. import { fetchMy } from '@/api'
  5. import { useAuthStore } from '../auth'
  6. import { useUserMemberStore } from '../memberShip'
  7. import { useCompanyStore } from '../company'
  8. export const useUserStore = defineStore('user-store', {
  9. state: (): UserState => defaultSetting(),
  10. actions: {
  11. setUserInfo(userInfo: Partial<UserInfo>) {
  12. this.userInfo = { ...this.userInfo, ...userInfo }
  13. this.recordState()
  14. },
  15. resetUserInfo() {
  16. this.userInfo = { ...defaultSetting().userInfo }
  17. this.recordState()
  18. },
  19. recordState() {
  20. setLocalState(this.$state)
  21. },
  22. async fetch() {
  23. const companyStore = useCompanyStore()
  24. if (companyStore.company.id !== 0) {
  25. useAuthStore().changeToken(`SECRET_TOKEN${companyStore.company.id}`)
  26. }
  27. const data = await fetchMy<UserInfo>()
  28. this.setUserInfo(data)
  29. if (data.id && companyStore.company.id !== 0 && !companyStore.company.code) {
  30. companyStore.getCompanyInfo(companyStore.company.id)
  31. }
  32. await useUserMemberStore().fetchMember()
  33. },
  34. logout() {
  35. this.resetUserInfo()
  36. useAuthStore().removeToken()
  37. }
  38. }
  39. })