Files
agenciapsilmno/src/stores/tenantStore.js
2026-02-18 22:36:45 -03:00

87 lines
2.4 KiB
JavaScript

// src/stores/tenantStore.js
import { defineStore } from 'pinia'
import { supabase } from '@/lib/supabase/client'
export const useTenantStore = defineStore('tenant', {
state: () => ({
loading: false,
loaded: false,
user: null, // auth user
memberships: [], // [{ tenant_id, role, status }]
activeTenantId: null,
activeRole: null,
needsTenantLink: false,
error: null
}),
actions: {
async loadSessionAndTenant () {
if (this.loading) return
this.loading = true
this.error = null
try {
// 1) auth user (estável)
const { data, error } = await supabase.auth.getSession()
if (error) throw error
this.user = data?.session?.user ?? null
// sem sessão -> não chama RPC, só marca estado
if (!this.user) {
this.memberships = []
this.activeTenantId = null
this.activeRole = null
this.needsTenantLink = false
this.loaded = true
return
}
// 2) memberships via RPC
const { data: mem, error: mErr } = await supabase.rpc('my_tenants')
if (mErr) throw mErr
this.memberships = Array.isArray(mem) ? mem : []
// 3) define active tenant (primeiro active)
const firstActive = this.memberships.find(x => x.status === 'active')
this.activeTenantId = firstActive?.tenant_id ?? null
this.activeRole = firstActive?.role ?? null
// se logou mas não tem vínculo ativo
this.needsTenantLink = !this.activeTenantId
this.loaded = true
} catch (e) {
console.warn('[tenantStore] loadSessionAndTenant falhou:', e)
this.error = e
// ⚠️ NÃO zera tudo agressivamente por erro transitório.
// Mantém o que já tinha (se tiver), mas marca loaded pra não travar o app.
// Se você preferir ser mais “duro”, só zere quando não houver sessão:
// (a sessão já foi lida acima; se der erro antes, user pode estar null)
if (!this.user) {
this.memberships = []
this.activeTenantId = null
this.activeRole = null
this.needsTenantLink = false
}
this.loaded = true
} finally {
this.loading = false
}
}
,
setActiveTenant (tenantId) {
const found = this.memberships.find(x => x.tenant_id === tenantId && x.status === 'active')
this.activeTenantId = found?.tenant_id ?? null
this.activeRole = found?.role ?? null
this.needsTenantLink = !this.activeTenantId
}
}
})