215 lines
No EOL
5.9 KiB
TypeScript
215 lines
No EOL
5.9 KiB
TypeScript
/**
|
|
* Serviço para gerenciar faturas via API principal
|
|
* Integração com https://bff-dev.saveinmed.com.br/api/v1/faturas
|
|
*/
|
|
import { API_V1_BASE_URL } from '@/lib/apiBase';
|
|
|
|
const API_BASE_URL = API_V1_BASE_URL;
|
|
|
|
/**
|
|
* Interface para dados da fatura na API
|
|
*/
|
|
export interface FaturaApiData {
|
|
'data-vencimento': string; // YYYY-MM-DD
|
|
status: 'pendente' | 'pago' | 'cancelado';
|
|
pedidos: string; // ID do pedido
|
|
}
|
|
|
|
/**
|
|
* Interface para resposta da API
|
|
*/
|
|
export interface FaturaApiResponse {
|
|
success: boolean;
|
|
data?: any;
|
|
error?: string;
|
|
message?: string;
|
|
}
|
|
|
|
/**
|
|
* Serviço de faturas para API principal
|
|
*/
|
|
export const faturaApiService = {
|
|
/**
|
|
* Obtém o token de autenticação do localStorage
|
|
*/
|
|
getAuthToken: (): string | null => {
|
|
return localStorage.getItem('access_token');
|
|
},
|
|
|
|
/**
|
|
* Obtém o ID do usuário atual
|
|
*/
|
|
getUserId: (): string | null => {
|
|
try {
|
|
const userStr = localStorage.getItem('user');
|
|
if (!userStr) return null;
|
|
|
|
const user = JSON.parse(userStr);
|
|
return user.$id || user.id || user.usuario_id || null;
|
|
} catch (error) {
|
|
console.error('Erro ao obter ID do usuário:', error);
|
|
return null;
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Cria uma nova fatura
|
|
*/
|
|
criar: async (
|
|
pedidoId: string,
|
|
dataVencimento?: Date
|
|
): Promise<FaturaApiResponse> => {
|
|
try {
|
|
const token = faturaApiService.getAuthToken();
|
|
if (!token) {
|
|
return { success: false, error: 'Token de autenticação não encontrado' };
|
|
}
|
|
|
|
// Se não informado, data de vencimento será 7 dias a partir de hoje
|
|
const vencimento = dataVencimento || new Date();
|
|
if (!dataVencimento) {
|
|
vencimento.setDate(vencimento.getDate() + 7);
|
|
}
|
|
|
|
const payload: FaturaApiData = {
|
|
'data-vencimento': vencimento.toISOString().split('T')[0], // YYYY-MM-DD
|
|
status: 'pendente',
|
|
pedidos: pedidoId
|
|
};
|
|
|
|
|
|
const response = await fetch(`${API_BASE_URL}/faturas`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
},
|
|
body: JSON.stringify(payload)
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
return { success: true, data };
|
|
} else {
|
|
console.error('⌠Erro ao criar fatura:', data);
|
|
return { success: false, error: data.message || 'Erro ao criar fatura' };
|
|
}
|
|
} catch (error) {
|
|
console.error('💥 Erro ao criar fatura:', error);
|
|
return { success: false, error: 'Erro de conexão ao criar fatura' };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Busca uma fatura por ID
|
|
*/
|
|
buscarPorId: async (faturaId: string): Promise<FaturaApiResponse> => {
|
|
try {
|
|
const token = faturaApiService.getAuthToken();
|
|
if (!token) {
|
|
return { success: false, error: 'Token de autenticação não encontrado' };
|
|
}
|
|
|
|
|
|
const response = await fetch(`${API_BASE_URL}/faturas/${faturaId}`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
}
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
return { success: true, data };
|
|
} else {
|
|
console.error('⌠Erro ao buscar fatura:', data);
|
|
return { success: false, error: data.message || 'Erro ao buscar fatura' };
|
|
}
|
|
} catch (error) {
|
|
console.error('💥 Erro ao buscar fatura:', error);
|
|
return { success: false, error: 'Erro de conexão ao buscar fatura' };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Lista faturas por usuário
|
|
*/
|
|
listarPorUsuario: async (): Promise<FaturaApiResponse> => {
|
|
try {
|
|
const token = faturaApiService.getAuthToken();
|
|
if (!token) {
|
|
return { success: false, error: 'Token de autenticação não encontrado' };
|
|
}
|
|
|
|
const userId = faturaApiService.getUserId();
|
|
if (!userId) {
|
|
return { success: false, error: 'ID do usuário não encontrado' };
|
|
}
|
|
|
|
|
|
const response = await fetch(`${API_BASE_URL}/faturas?usuario=${userId}`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
}
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
return { success: true, data };
|
|
} else {
|
|
console.error('⌠Erro ao listar faturas:', data);
|
|
return { success: false, error: data.message || 'Erro ao listar faturas' };
|
|
}
|
|
} catch (error) {
|
|
console.error('💥 Erro ao listar faturas:', error);
|
|
return { success: false, error: 'Erro de conexão ao listar faturas' };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Atualiza o status de uma fatura
|
|
*/
|
|
atualizarStatus: async (
|
|
faturaId: string,
|
|
novoStatus: 'pendente' | 'pago' | 'cancelado'
|
|
): Promise<FaturaApiResponse> => {
|
|
try {
|
|
const token = faturaApiService.getAuthToken();
|
|
if (!token) {
|
|
return { success: false, error: 'Token de autenticação não encontrado' };
|
|
}
|
|
|
|
const payload = { status: novoStatus };
|
|
|
|
|
|
const response = await fetch(`${API_BASE_URL}/faturas/${faturaId}`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
},
|
|
body: JSON.stringify(payload)
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
return { success: true, data };
|
|
} else {
|
|
console.error('⌠Erro ao atualizar status da fatura:', data);
|
|
return { success: false, error: data.message || 'Erro ao atualizar status da fatura' };
|
|
}
|
|
} catch (error) {
|
|
console.error('💥 Erro ao atualizar status da fatura:', error);
|
|
return { success: false, error: 'Erro de conexão ao atualizar status da fatura' };
|
|
}
|
|
}
|
|
}; |