445 lines
12 KiB
TypeScript
445 lines
12 KiB
TypeScript
import { GlobalFunctions } from '@/GlobalFunctions';
|
|
export interface UserProfile {
|
|
success: boolean;
|
|
id?: string;
|
|
nome: string;
|
|
email: string;
|
|
whatsapp: string;
|
|
followup: boolean;
|
|
message?: string;
|
|
}
|
|
|
|
export interface CreateUserRequest {
|
|
nome: string;
|
|
email: string;
|
|
whatsapp: string;
|
|
followup: boolean;
|
|
}
|
|
|
|
export interface UpdateUserRequest {
|
|
nome: string;
|
|
whatsapp: string;
|
|
followup: boolean;
|
|
}
|
|
|
|
export interface FinancialIndicators {
|
|
success: boolean;
|
|
id: string;
|
|
nome: string;
|
|
email: string;
|
|
total_despesas: string;
|
|
total_corporativo: string;
|
|
total_pessoal: string;
|
|
message?: string;
|
|
}
|
|
|
|
export interface ExpenseItem {
|
|
id: string;
|
|
data_hora: string;
|
|
descricao: string;
|
|
tipo: "pessoal" | "corporativo";
|
|
valor: string;
|
|
categoria_id: number;
|
|
categoria_nome: string;
|
|
usuario_nome: string;
|
|
usuario_email: string;
|
|
}
|
|
|
|
export interface ExpensesResponse {
|
|
success: boolean;
|
|
total_registros: number;
|
|
total_paginas: number;
|
|
per_page: number;
|
|
pagina_atual: number;
|
|
data: ExpenseItem[];
|
|
}
|
|
|
|
export interface ExpensesFilters {
|
|
page?: number;
|
|
per_page?: number;
|
|
descricao?: string;
|
|
categoria_id?: number;
|
|
data_inicial?: string;
|
|
data_final?: string;
|
|
}
|
|
|
|
export interface ExpenseCategory {
|
|
id: number;
|
|
nome: string;
|
|
descricao: string;
|
|
criado_em: string;
|
|
atualizado_em: string;
|
|
}
|
|
|
|
class PersonalAgent {
|
|
|
|
async getUserProfile(userEmail?: string): Promise<UserProfile> {
|
|
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
|
|
|
if (!email) {
|
|
throw {
|
|
success: false,
|
|
message: 'Email do usuário não fornecido',
|
|
};
|
|
}
|
|
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await axios.get<UserProfile>(
|
|
`https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/user/${email}`,
|
|
{ headers }
|
|
);
|
|
|
|
return response.data;
|
|
} catch (error: any) {
|
|
if (error.response?.data) {
|
|
return error.response.data;
|
|
}
|
|
|
|
throw {
|
|
success: false,
|
|
message: error.message || 'Erro ao buscar perfil do usuário',
|
|
status: error.response?.status,
|
|
};
|
|
}
|
|
}
|
|
|
|
async createUser(request: CreateUserRequest): Promise<UserProfile> {
|
|
|
|
if (!request.nome || request.nome.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'Nome é obrigatório',
|
|
};
|
|
}
|
|
|
|
if (!request.email || request.email.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'Email é obrigatório',
|
|
};
|
|
}
|
|
|
|
if (!request.whatsapp || request.whatsapp.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'WhatsApp é obrigatório',
|
|
};
|
|
}
|
|
|
|
const whatsappNumbers = request.whatsapp.replace(/\D/g, '');
|
|
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
} else {
|
|
console.warn('API_KEY não configurada');
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await axios.post<UserProfile>(
|
|
'https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/agente-pessoal/user',
|
|
{
|
|
nome: request.nome.trim(),
|
|
email: request.email.trim(),
|
|
whatsapp: whatsappNumbers,
|
|
followup: request.followup,
|
|
},
|
|
{ headers }
|
|
);
|
|
|
|
return response.data;
|
|
} catch (error: any) {
|
|
if (error.response?.data) {
|
|
throw error.response.data;
|
|
}
|
|
|
|
throw {
|
|
success: false,
|
|
message: error.message || 'Erro ao criar usuário',
|
|
status: error.response?.status,
|
|
};
|
|
}
|
|
}
|
|
|
|
async updateUser(userId: string, request: UpdateUserRequest): Promise<UserProfile> {
|
|
|
|
if (!userId || userId.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'ID do usuário é obrigatório',
|
|
};
|
|
}
|
|
|
|
if (!request.nome || request.nome.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'Nome é obrigatório',
|
|
};
|
|
}
|
|
|
|
if (!request.whatsapp || request.whatsapp.trim().length === 0) {
|
|
throw {
|
|
success: false,
|
|
message: 'WhatsApp é obrigatório',
|
|
};
|
|
}
|
|
|
|
const whatsappNumbers = request.whatsapp.replace(/\D/g, '');
|
|
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await axios.post<UserProfile>(
|
|
`https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/user/${userId}`,
|
|
{
|
|
nome: request.nome.trim(),
|
|
whatsapp: whatsappNumbers,
|
|
followup: request.followup,
|
|
},
|
|
{ headers }
|
|
);
|
|
|
|
return response.data;
|
|
} catch (error: any) {
|
|
if (error.response?.data) {
|
|
throw error.response.data;
|
|
}
|
|
|
|
throw {
|
|
success: false,
|
|
message: error.message || 'Erro ao atualizar usuário',
|
|
status: error.response?.status,
|
|
};
|
|
}
|
|
}
|
|
|
|
async getFinancialIndicators(userEmail?: string): Promise<FinancialIndicators> {
|
|
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
|
|
|
if (!email) {
|
|
throw {
|
|
success: false,
|
|
message: 'Email do usuário é obrigatório',
|
|
};
|
|
}
|
|
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await axios.get<FinancialIndicators>(
|
|
`https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/financas/indicadores/${email}`,
|
|
{ headers }
|
|
);
|
|
|
|
return response.data;
|
|
} catch (error: unknown) {
|
|
if (error && typeof error === 'object' && 'response' in error) {
|
|
const axiosError = error as { response?: { data?: FinancialIndicators } };
|
|
if (axiosError.response?.data) {
|
|
throw axiosError.response.data;
|
|
}
|
|
}
|
|
|
|
throw {
|
|
success: false,
|
|
message: error instanceof Error ? error.message : 'Erro ao buscar indicadores financeiros',
|
|
status: error && typeof error === 'object' && 'response' in error
|
|
? (error as { response?: { status?: number } }).response?.status
|
|
: undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
async getExpenses(userEmail?: string, filters?: ExpensesFilters): Promise<ExpensesResponse> {
|
|
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
|
|
|
if (!email) {
|
|
throw {
|
|
success: false,
|
|
message: 'Email do usuário é obrigatório',
|
|
};
|
|
}
|
|
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
// Constrói query params
|
|
const params = new URLSearchParams();
|
|
if (filters?.page) params.append('page', filters.page.toString());
|
|
if (filters?.per_page) params.append('per_page', filters.per_page.toString());
|
|
if (filters?.descricao) params.append('descricao', filters.descricao);
|
|
if (filters?.categoria_id) params.append('categoria_id', filters.categoria_id.toString());
|
|
if (filters?.data_inicial) params.append('data_inicial', filters.data_inicial);
|
|
if (filters?.data_final) params.append('data_final', filters.data_final);
|
|
|
|
const queryString = params.toString();
|
|
const url = `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/financas/${email}${queryString ? `?${queryString}` : ''}`;
|
|
|
|
const response = await axios.get<ExpensesResponse[]>(url, { headers });
|
|
|
|
if (Array.isArray(response.data) && response.data.length > 0) {
|
|
const expensesResponse = response.data[0];
|
|
|
|
// Valida e limpa o array de dados, removendo objetos vazios
|
|
if (expensesResponse.data && Array.isArray(expensesResponse.data)) {
|
|
// Filtra objetos vazios (sem propriedades ou apenas com propriedades vazias)
|
|
expensesResponse.data = expensesResponse.data.filter((item) => {
|
|
// Verifica se o objeto tem pelo menos uma propriedade válida
|
|
return item && typeof item === 'object' && Object.keys(item).length > 0 && item.id;
|
|
});
|
|
|
|
// Se após filtrar não há dados, garante que data seja um array vazio
|
|
if (expensesResponse.data.length === 0) {
|
|
expensesResponse.data = [];
|
|
expensesResponse.total_registros = 0;
|
|
expensesResponse.total_paginas = 0;
|
|
}
|
|
} else {
|
|
// Se data não é um array válido, inicializa como array vazio
|
|
expensesResponse.data = [];
|
|
expensesResponse.total_registros = 0;
|
|
expensesResponse.total_paginas = 0;
|
|
}
|
|
|
|
return expensesResponse;
|
|
}
|
|
|
|
// Fallback caso a estrutura seja diferente - retorna resposta vazia
|
|
return {
|
|
success: true,
|
|
total_registros: 0,
|
|
total_paginas: 0,
|
|
per_page: filters?.per_page || 10,
|
|
pagina_atual: filters?.page || 1,
|
|
data: [],
|
|
};
|
|
} catch (error: unknown) {
|
|
// Retorna o erro da API se existir
|
|
if (error && typeof error === 'object' && 'response' in error) {
|
|
const axiosError = error as { response?: { data?: ExpensesResponse } };
|
|
if (axiosError.response?.data) {
|
|
throw axiosError.response.data;
|
|
}
|
|
}
|
|
|
|
throw {
|
|
success: false,
|
|
message: error instanceof Error ? error.message : 'Erro ao buscar despesas',
|
|
status: error && typeof error === 'object' && 'response' in error
|
|
? (error as { response?: { status?: number } }).response?.status
|
|
: undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
async getCategories(): Promise<ExpenseCategory[]> {
|
|
try {
|
|
const axios = (await import('axios')).default;
|
|
|
|
const token = await GlobalFunctions.getToken();
|
|
const apiKey = import.meta.env.VITE_API_KEY || '';
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (apiKey) {
|
|
headers['apikey'] = apiKey;
|
|
}
|
|
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const response = await axios.get<ExpenseCategory[]>('https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/agente-pessoal/categorias', { headers });
|
|
|
|
// A API retorna um array de categorias
|
|
if (Array.isArray(response.data)) {
|
|
return response.data;
|
|
}
|
|
|
|
return [];
|
|
} catch (error: unknown) {
|
|
console.error('Erro ao buscar categorias:', error);
|
|
|
|
return [];
|
|
}
|
|
}
|
|
}
|
|
|
|
export const personalAgent = new PersonalAgent();
|