Detalhes das alterações: [Banco de Dados] - Ajuste nas constraints UNIQUE das tabelas de catálogo (cursos, empresas, tipos_eventos, etc.) para incluir a coluna `regiao`, permitindo dados duplicados entre regiões mas únicos por região. - Correção crítica na constraint da tabela `precos_tipos_eventos` para evitar conflitos de UPSERT (ON CONFLICT) durante a inicialização. - Implementação de lógica de Seed para a região 'MG': - Clonagem automática de catálogos base de 'SP' para 'MG' (Tipos de Evento, Serviços, etc.). - Inserção de tabela de preços específica para 'MG' via script de migração. [Backend - Go] - Atualização geral dos Handlers e Services para filtrar dados baseados no cabeçalho `x-regiao`. - Ajuste no Middleware de autenticação para processar e repassar o contexto da região. - Correção de queries SQL (geradas pelo sqlc) para suportar os novos filtros regionais. [Frontend - React] - Implementação do envio global do cabeçalho `x-regiao` nas requisições da API. - Correção no componente [PriceTableEditor](cci:1://file:///c:/Projetos/photum/frontend/components/System/PriceTableEditor.tsx:26:0-217:2) para carregar e salvar preços respeitando a região selecionada (fix de "Preços zerados" em MG). - Refatoração profunda na tela de Importação ([ImportData.tsx](cci:7://file:///c:/Projetos/photum/frontend/pages/ImportData.tsx:0:0-0:0)): - Adição de feedback visual detalhado para registros ignorados. - Categorização explícita de erros: "CPF Inválido", "Região Incompatível", "Linha Vazia/Separador". - Correção na lógica de contagem para considerar linhas vazias explicitamente no relatório final, garantindo que o total bata com o Excel. [Geral] - Correção de diversos erros de lint e tipagem TSX. - Padronização de logs de erro no backend para facilitar debug.
77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect } from "react";
|
|
import { useAuth } from "./AuthContext";
|
|
|
|
const REGION_KEY = "photum_selected_region";
|
|
|
|
interface RegionContextType {
|
|
currentRegion: string;
|
|
setRegion: (region: string) => void;
|
|
availableRegions: string[];
|
|
}
|
|
|
|
const RegionContext = createContext<RegionContextType>({
|
|
currentRegion: "SP",
|
|
setRegion: () => {},
|
|
availableRegions: [],
|
|
});
|
|
|
|
export const RegionProvider: React.FC<{ children: React.ReactNode }> = ({
|
|
children,
|
|
}) => {
|
|
const { user } = useAuth();
|
|
|
|
const [currentRegion, setCurrentRegion] = useState(() => {
|
|
return localStorage.getItem(REGION_KEY) || "SP";
|
|
});
|
|
|
|
// Calculate available regions based on user permissions
|
|
// If user is null (public), default to SP or both?
|
|
// Requirement: Public pages might need both for registration?
|
|
// Actually, RegionSwitcher is usually for logged in header.
|
|
// Registration page has its own selector.
|
|
// Let's assume public = SP only or no switcher.
|
|
// BUT: If user is logged out, they shouldn't see switcher anyway.
|
|
const [availableRegions, setAvailableRegions] = useState<string[]>(["SP"]);
|
|
|
|
useEffect(() => {
|
|
console.log("RegionContext Debug:", { user, allowedRegions: user?.allowedRegions });
|
|
if (user && user.allowedRegions && user.allowedRegions.length > 0) {
|
|
setAvailableRegions(user.allowedRegions);
|
|
|
|
// If current region is not in allowed list, switch to first allowed
|
|
if (!user.allowedRegions.includes(currentRegion)) {
|
|
console.log("Switching region to allowed:", user.allowedRegions[0]);
|
|
const fallback = user.allowedRegions[0];
|
|
setCurrentRegion(fallback);
|
|
localStorage.setItem(REGION_KEY, fallback);
|
|
}
|
|
} else {
|
|
// Fallback or Public
|
|
setAvailableRegions(["SP"]);
|
|
}
|
|
}, [user, user?.allowedRegions, currentRegion]);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem(REGION_KEY, currentRegion);
|
|
}, [currentRegion]);
|
|
|
|
const setRegion = (region: string) => {
|
|
// Prevent switching if not allowed
|
|
if (!availableRegions.includes(region)) return;
|
|
|
|
setCurrentRegion(region);
|
|
setTimeout(() => {
|
|
window.location.reload();
|
|
}, 100);
|
|
};
|
|
|
|
return (
|
|
<RegionContext.Provider
|
|
value={{ currentRegion, setRegion, availableRegions }}
|
|
>
|
|
{children}
|
|
</RegionContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useRegion = () => useContext(RegionContext);
|