Prechádzať zdrojové kódy

feat: add multi-unit state management to user store

- Store tracks selectedUnit with localStorage persistence (gc_selected_unit_id)
- initSelectedUnit restores saved unit on login, falling back to first unit
- setUser/setSelectedUnit replace direct property assignment
- userUnits computed exposes available units for the selector
ebagabee 2 týždňov pred
rodič
commit
3c021b883c
2 zmenil súbory, kde vykonal 34 pridanie a 4 odobranie
  1. 3 2
      src/composables/useAuth.js
  2. 31 2
      src/stores/user.js

+ 3 - 2
src/composables/useAuth.js

@@ -5,8 +5,9 @@ import { userStore } from "src/stores/user";
 export const useAuth = () => {
   const setAuthDataFromPayload = async (tokens) => {
     const { access_token, user } = tokens;
-    userStore().user = user;
-    userStore().accessToken = access_token;
+    const store = userStore();
+    store.setUser(user);
+    store.accessToken = access_token;
     await permissionStore().fetchScopes();
   };
 

+ 31 - 2
src/stores/user.js

@@ -1,21 +1,47 @@
 import { defineStore } from "pinia";
-import { ref } from "vue";
+import { ref, computed } from "vue";
 import { getUser } from "src/api/user";
 
+const STORAGE_KEY = "gc_selected_unit_id";
+
 export const userStore = defineStore("user", () => {
   const user = ref(null);
   const accessToken = ref(null);
   const isAdmin = ref(false);
+  const selectedUnit = ref(null);
+
+  /** Lista de unidades do usuário atual */
+  const userUnits = computed(() => user.value?.units ?? []);
+
+  /** Inicializa a unidade ativa: tenta restaurar a última escolha salva ou usa a primeira */
+  const initSelectedUnit = (units) => {
+    if (!units?.length) return;
+    const savedId = parseInt(localStorage.getItem(STORAGE_KEY));
+    const saved = savedId ? units.find((u) => u.id === savedId) : null;
+    selectedUnit.value = saved || units[0];
+  };
 
   const setUser = (userData) => {
     user.value = userData;
     isAdmin.value = userData.type === "admin";
+    initSelectedUnit(userData.units);
+  };
+
+  /** Troca a unidade ativa e persiste a escolha */
+  const setSelectedUnit = (unit) => {
+    selectedUnit.value = unit;
+    if (unit?.id) {
+      localStorage.setItem(STORAGE_KEY, unit.id);
+    } else {
+      localStorage.removeItem(STORAGE_KEY);
+    }
   };
 
   const resetUser = () => {
     user.value = null;
     isAdmin.value = false;
     accessToken.value = false;
+    selectedUnit.value = null;
   };
 
   const fetchUser = async () => {
@@ -26,9 +52,12 @@ export const userStore = defineStore("user", () => {
   return {
     user,
     isAdmin,
+    accessToken,
+    selectedUnit,
+    userUnits,
     setUser,
+    setSelectedUnit,
     resetUser,
     fetchUser,
-    accessToken,
   };
 });