import { defineStore } from 'pinia' import api from 'src/services/api' let lastRequestId = 0 export const useRoleDeptPermissionListStore = defineStore('roleDeptPermissionList', { state: () => ({ modules: [], moduleActions: [], rows: [], loading: false, error: null, filters: { search: '' } }), getters: { totalCount (state) { return state.rows.length } }, actions: { async fetchRows () { const rid = ++lastRequestId this.loading = true this.error = null try { const search = String(this.filters.search || '').trim() const params = {} if (search) params.search = search const res = await api.get('/role-dept-permissions/list', { params }) if (rid !== lastRequestId) { return } const payload = res?.data || {} this.modules = Array.isArray(payload?.modules) ? payload.modules.map((m) => ({ value: String(m.value || '').toLowerCase().trim(), label: String(m.label || '') })).filter((m) => m.value) : [] this.moduleActions = Array.isArray(payload?.module_actions) ? payload.module_actions.map((a) => ({ module_code: String(a.module_code || '').toLowerCase().trim(), action: String(a.action || '').toLowerCase().trim() })).filter((a) => a.module_code && a.action) : [] const rawRows = Array.isArray(payload?.rows) ? payload.rows : Array.isArray(res?.data) ? res.data : [] this.rows = rawRows.map((r) => { const rawFlags = (r?.module_flags && typeof r.module_flags === 'object') ? r.module_flags : {} const flags = {} Object.keys(rawFlags).forEach((k) => { flags[String(k).toLowerCase().trim()] = Boolean(rawFlags[k]) }) return { role_id: Number(r.role_id || 0), role_title: r.role_title || '', department_code: r.department_code || '', department_title: r.department_title || '', module_flags: flags } }) } catch (err) { if (rid !== lastRequestId) return this.modules = [] this.moduleActions = [] this.rows = [] this.error = err?.response?.data || err?.message || 'Yetki listesi alınamadı' } finally { if (rid === lastRequestId) { this.loading = false } } } } })