style: clean up code formatting and remove trailing whitespace
refactor: reorganize imports and fix type imports
This commit is contained in:
1 parent
d3704602fd
commit
47c04de6fe
232 files changed
+7140
-4798
No files matched your search
+29
-15
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useSocket } from "./use-socket";
|
||||
import { useSession } from "./use-session";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { Socket } from "socket.io-client";
|
||||
import { useSession } from "./use-session";
|
||||
import { useSocket } from "./use-socket";
|
||||
|
||||
export interface ChatMessage {
|
||||
_id: string;
|
||||
@@ -109,7 +109,9 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
queryKey: ["chat-messages", chatId, page],
|
||||
queryFn: async () => {
|
||||
if (!chatId) return null;
|
||||
const res = await fetch(`/api/chats/${chatId}/messages?page=${page}&limit=50`);
|
||||
const res = await fetch(
|
||||
`/api/chats/${chatId}/messages?page=${page}&limit=50`,
|
||||
);
|
||||
if (!res.ok) throw new Error("Erro ao buscar mensagens");
|
||||
return res.json();
|
||||
},
|
||||
@@ -126,7 +128,9 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
// Adicionar mensagens antigas no início
|
||||
setMessages((prev) => [...messagesData.messages, ...prev]);
|
||||
}
|
||||
setHasMore(messagesData.pagination.page < messagesData.pagination.totalPages);
|
||||
setHasMore(
|
||||
messagesData.pagination.page < messagesData.pagination.totalPages,
|
||||
);
|
||||
}
|
||||
}, [messagesData, page]);
|
||||
|
||||
@@ -139,25 +143,33 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
|
||||
// Listener para novas mensagens
|
||||
const handleNewMessage = (data: { message: ChatMessage }) => {
|
||||
console.log("[CHAT-DEBUG] useChat: new_message recebido", { message: data.message });
|
||||
|
||||
console.log("[CHAT-DEBUG] useChat: new_message recebido", {
|
||||
message: data.message,
|
||||
});
|
||||
|
||||
// Verificar se a mensagem já existe para evitar duplicação
|
||||
setMessages((prev) => {
|
||||
const messageExists = prev.some((msg) => msg._id === data.message._id);
|
||||
if (messageExists) {
|
||||
console.log("[CHAT-DEBUG] Mensagem já existe, ignorando duplicação", { messageId: data.message._id });
|
||||
console.log("[CHAT-DEBUG] Mensagem já existe, ignorando duplicação", {
|
||||
messageId: data.message._id,
|
||||
});
|
||||
return prev;
|
||||
}
|
||||
return [...prev, data.message];
|
||||
});
|
||||
|
||||
|
||||
// Invalidar cache
|
||||
queryClient.invalidateQueries({ queryKey: ["chat-messages", chatId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["chat", chatId] });
|
||||
};
|
||||
|
||||
// Listener para indicador de digitação
|
||||
const handleTyping = (data: { user_id: number; username: string; is_typing: boolean }) => {
|
||||
const handleTyping = (data: {
|
||||
user_id: number;
|
||||
username: string;
|
||||
is_typing: boolean;
|
||||
}) => {
|
||||
if (data.user_id !== user?.userId) {
|
||||
setOtherUserTyping(data.is_typing);
|
||||
}
|
||||
@@ -177,7 +189,11 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
async (content: string) => {
|
||||
if (!chatId || !socket || !isConnected || !content.trim()) return;
|
||||
|
||||
console.log("[CHAT-DEBUG] sendMessage chamado", { chatId, content, socketConnected: isConnected });
|
||||
console.log("[CHAT-DEBUG] sendMessage chamado", {
|
||||
chatId,
|
||||
content,
|
||||
socketConnected: isConnected,
|
||||
});
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
@@ -202,7 +218,7 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
setIsSending(false);
|
||||
}
|
||||
},
|
||||
[chatId, socket, isConnected, user]
|
||||
[chatId, socket, isConnected],
|
||||
);
|
||||
|
||||
// Função para carregar mais mensagens
|
||||
@@ -211,7 +227,6 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
setPage((prev) => prev + 1);
|
||||
}, [hasMore, isLoadingMessages]);
|
||||
|
||||
|
||||
return {
|
||||
chat: chatData?.chat || null,
|
||||
messages,
|
||||
@@ -230,7 +245,7 @@ export function useChat(chatId: string | null): UseChatReturn {
|
||||
export function useChatTyping(
|
||||
socket: Socket | null,
|
||||
isConnected: boolean,
|
||||
chatId: string | null
|
||||
chatId: string | null,
|
||||
) {
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
@@ -272,4 +287,3 @@ export function useChatTyping(
|
||||
|
||||
return { handleTypingStart, handleTypingStop };
|
||||
}
|
||||
|
||||
@@ -131,4 +131,3 @@ export function useInvalidateListings() {
|
||||
|
||||
return invalidate;
|
||||
}
|
||||
|
||||
@@ -68,29 +68,33 @@ export function useMyPurchaseIntentions() {
|
||||
const queryParams = new URLSearchParams();
|
||||
queryParams.set("limit", "100");
|
||||
|
||||
const { data, isLoading, error, refetch } = useQuery<PurchaseIntentionsResponse>({
|
||||
queryKey: ["my-purchase-intentions"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/purchase-intentions/my?${queryParams.toString()}`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
throw new Error("Não autenticado");
|
||||
const { data, isLoading, error, refetch } =
|
||||
useQuery<PurchaseIntentionsResponse>({
|
||||
queryKey: ["my-purchase-intentions"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(
|
||||
`/api/purchase-intentions/my?${queryParams.toString()}`,
|
||||
);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
throw new Error("Não autenticado");
|
||||
}
|
||||
throw new Error("Erro ao buscar intenções de compra");
|
||||
}
|
||||
throw new Error("Erro ao buscar intenções de compra");
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
staleTime: 1000 * 30, // 30 segundos
|
||||
refetchInterval: 1000 * 30, // Refetch a cada 30 segundos
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
enabled: true, // Sempre habilitado (autenticação é verificada no backend)
|
||||
});
|
||||
return res.json();
|
||||
},
|
||||
staleTime: 1000 * 30, // 30 segundos
|
||||
refetchInterval: 1000 * 30, // Refetch a cada 30 segundos
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
enabled: true, // Sempre habilitado (autenticação é verificada no backend)
|
||||
});
|
||||
|
||||
const normalizedIntentions = (data?.intentions || []).map((intention) => ({
|
||||
...intention,
|
||||
custom_offer_amount:
|
||||
intention.custom_offer_amount !== null && intention.custom_offer_amount !== undefined
|
||||
intention.custom_offer_amount !== null &&
|
||||
intention.custom_offer_amount !== undefined
|
||||
? Number(intention.custom_offer_amount)
|
||||
: null,
|
||||
}));
|
||||
@@ -116,4 +120,3 @@ export function useInvalidatePurchaseIntentions() {
|
||||
|
||||
return invalidate;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
export interface Server {
|
||||
serverId: number;
|
||||
@@ -70,7 +70,8 @@ export function useServers(): UseServersReturn {
|
||||
setError(data.error || "Erro ao buscar servidores");
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Erro desconhecido";
|
||||
setError("Erro ao conectar com o servidor");
|
||||
console.error("Erro ao buscar servidores:", errorMessage, err);
|
||||
} finally {
|
||||
@@ -89,4 +90,3 @@ export function useServers(): UseServersReturn {
|
||||
refetch: fetchServers,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,4 +62,3 @@ export function useSession() {
|
||||
refreshSession: refetch,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
|
||||
// Re-exportar o hook que usa React Query
|
||||
export { useSession, type SessionUser } from "./use-session-query";
|
||||
|
||||
export { type SessionUser, useSession } from "./use-session-query";
|
||||
+13
-11
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import { io, type Socket } from "socket.io-client";
|
||||
import { useSession } from "./use-session";
|
||||
|
||||
interface UseSocketReturn {
|
||||
@@ -39,15 +39,18 @@ export function useSocket(): UseSocketReturn {
|
||||
}
|
||||
|
||||
try {
|
||||
const newSocket = io(process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000", {
|
||||
path: "/api/socket",
|
||||
transports: ["websocket", "polling"],
|
||||
withCredentials: true, // Enviar cookies automaticamente
|
||||
reconnection: true,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 5000,
|
||||
reconnectionAttempts: 5,
|
||||
});
|
||||
const newSocket = io(
|
||||
process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000",
|
||||
{
|
||||
path: "/api/socket",
|
||||
transports: ["websocket", "polling"],
|
||||
withCredentials: true, // Enviar cookies automaticamente
|
||||
reconnection: true,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 5000,
|
||||
reconnectionAttempts: 5,
|
||||
},
|
||||
);
|
||||
|
||||
newSocket.on("connect", () => {
|
||||
setIsConnected(true);
|
||||
@@ -90,4 +93,3 @@ export function useSocket(): UseSocketReturn {
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
+19
-15
@@ -2,7 +2,7 @@
|
||||
* Hooks para tracking de telemetria
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useCallback } from "react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { getTelemetry } from "../telemetry/MarketTelemetry";
|
||||
import { useSession } from "./use-session";
|
||||
|
||||
@@ -49,17 +49,23 @@ export function useMarketTelemetry() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const trackSearch = useCallback((query: string, filters?: Record<string, any>) => {
|
||||
telemetryRef.current.trackSearch(query, filters);
|
||||
}, []);
|
||||
const trackSearch = useCallback(
|
||||
(query: string, filters?: Record<string, any>) => {
|
||||
telemetryRef.current.trackSearch(query, filters);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const trackFilter = useCallback((filters: Record<string, any>) => {
|
||||
telemetryRef.current.trackFilterApplied(filters);
|
||||
}, []);
|
||||
|
||||
const trackFavorite = useCallback((adId: number, action: "favorite" | "unfavorite") => {
|
||||
telemetryRef.current.trackFavorite(adId, action);
|
||||
}, []);
|
||||
const trackFavorite = useCallback(
|
||||
(adId: number, action: "favorite" | "unfavorite") => {
|
||||
telemetryRef.current.trackFavorite(adId, action);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const trackPurchase = useCallback((adId: number, price: number) => {
|
||||
telemetryRef.current.trackPurchase(adId, price);
|
||||
@@ -77,13 +83,12 @@ export function useMarketTelemetry() {
|
||||
telemetryRef.current.trackAdClick(adId, position);
|
||||
}, []);
|
||||
|
||||
const trackCustomEvent = useCallback((
|
||||
eventType: string,
|
||||
adId?: number,
|
||||
metadata?: Record<string, any>
|
||||
) => {
|
||||
telemetryRef.current.trackCustomEvent(eventType, adId, metadata);
|
||||
}, []);
|
||||
const trackCustomEvent = useCallback(
|
||||
(eventType: string, adId?: number, metadata?: Record<string, any>) => {
|
||||
telemetryRef.current.trackCustomEvent(eventType, adId, metadata);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
trackSearch,
|
||||
@@ -97,4 +102,3 @@ export function useMarketTelemetry() {
|
||||
telemetry: telemetryRef.current,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user