feat(api): implement product caching mechanism
- Add NODE_ENV=production to .env for environment configuration - Enhance product API route with JSON cache manager for local storage and retrieval - Introduce cache-only mode and detailed logging for better performance and offline support - Update UI to display cache status and storage statistics
This commit is contained in:
1 parent
bddf19e5c8
commit
c173fec668
19 files changed
+9240
-175
No files matched your search
Vendored
+32
@@ -0,0 +1,32 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { jsonCacheManager } from "@/lib/jsonCacheManager";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { products } = await request.json();
|
||||||
|
|
||||||
|
if (!products || !Array.isArray(products)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Produtos inválidos" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Salvar produtos no cache
|
||||||
|
const result = await jsonCacheManager.saveProducts(products);
|
||||||
|
|
||||||
|
console.log(`[Cache Sync] ${result.saved} novos produtos salvos`);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
saved: result.saved,
|
||||||
|
failed: result.failed,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao sincronizar cache:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erro ao sincronizar cache" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { jsonCacheManager } from "@/lib/jsonCacheManager";
|
||||||
|
|
||||||
const USER_AGENT = "NutriScan/1.0 (https://nutriscan.com.br)";
|
const USER_AGENT = "NutriScan/1.0 (https://nutriscan.com.br)";
|
||||||
|
|
||||||
@@ -7,6 +8,8 @@ export async function GET(
|
|||||||
{ params }: { params: { barcode: string } }
|
{ params }: { params: { barcode: string } }
|
||||||
) {
|
) {
|
||||||
const { barcode } = params;
|
const { barcode } = params;
|
||||||
|
const searchParams = request.nextUrl.searchParams;
|
||||||
|
const cacheOnly = searchParams.get("cache_only") === "true";
|
||||||
|
|
||||||
// Validar código de barras
|
// Validar código de barras
|
||||||
const cleanBarcode = barcode.replace(/\D/g, "");
|
const cleanBarcode = barcode.replace(/\D/g, "");
|
||||||
@@ -18,6 +21,36 @@ export async function GET(
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log(`[API] Iniciando busca de produto: ${cleanBarcode}`);
|
||||||
|
|
||||||
|
// Primeiro, buscar no cache JSON
|
||||||
|
console.log(`[API] Buscando produto ${cleanBarcode} no cache JSON...`);
|
||||||
|
const localProduct = await jsonCacheManager.getProductByCode(cleanBarcode);
|
||||||
|
|
||||||
|
if (localProduct) {
|
||||||
|
console.log(`Produto ${cleanBarcode} encontrado no cache JSON`);
|
||||||
|
return NextResponse.json({
|
||||||
|
...localProduct,
|
||||||
|
fromCache: true,
|
||||||
|
fromAPI: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se modo cache-only, retornar 404 se não encontrar no cache
|
||||||
|
if (cacheOnly || process.env.NEXT_PUBLIC_CACHE_ONLY_MODE === "true") {
|
||||||
|
console.log(
|
||||||
|
`[Cache-Only Mode] Produto ${cleanBarcode} não encontrado no cache JSON`
|
||||||
|
);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Produto não encontrado no cache JSON" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se não encontrou no cache JSON, buscar na API externa
|
||||||
|
console.log(
|
||||||
|
`Produto ${cleanBarcode} não encontrado no cache JSON, buscando na API externa...`
|
||||||
|
);
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`https://world.openfoodfacts.org/api/v2/product/${cleanBarcode}.json`,
|
`https://world.openfoodfacts.org/api/v2/product/${cleanBarcode}.json`,
|
||||||
{
|
{
|
||||||
@@ -44,11 +77,30 @@ export async function GET(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(data.product);
|
// Salvar produto no cache JSON
|
||||||
|
if (data.product) {
|
||||||
|
console.log(`Salvando produto ${cleanBarcode} no cache JSON...`);
|
||||||
|
const saveResult = await jsonCacheManager.saveProduct(data.product);
|
||||||
|
if (saveResult) {
|
||||||
|
console.log(`Produto ${cleanBarcode} salvo no cache JSON com sucesso`);
|
||||||
|
} else {
|
||||||
|
console.log(`Falha ao salvar produto ${cleanBarcode} no cache JSON`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
...data.product,
|
||||||
|
fromCache: false,
|
||||||
|
fromAPI: true,
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao buscar produto:", error);
|
console.error("[API] Erro ao buscar produto:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Erro ao buscar produto" },
|
{
|
||||||
|
error: "Erro interno do servidor",
|
||||||
|
fromCache: false,
|
||||||
|
fromAPI: false,
|
||||||
|
},
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+132
-18
@@ -1,4 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { jsonCacheManager } from "@/lib/jsonCacheManager";
|
||||||
|
import { Product } from "@/lib/openFoodFactsApi";
|
||||||
|
import { sortByRelevance } from "@/lib/searchUtils";
|
||||||
|
|
||||||
const USER_AGENT = "NutriScan/1.0 (https://nutriscan.com.br)";
|
const USER_AGENT = "NutriScan/1.0 (https://nutriscan.com.br)";
|
||||||
|
|
||||||
@@ -8,6 +11,7 @@ export async function GET(request: NextRequest) {
|
|||||||
const country = searchParams.get("country");
|
const country = searchParams.get("country");
|
||||||
const page = searchParams.get("page") || "1";
|
const page = searchParams.get("page") || "1";
|
||||||
const pageSize = searchParams.get("page_size") || "20";
|
const pageSize = searchParams.get("page_size") || "20";
|
||||||
|
const cacheOnly = searchParams.get("cache_only") === "true";
|
||||||
|
|
||||||
if (!query) {
|
if (!query) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -27,9 +31,9 @@ export async function GET(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isNaN(pageSizeNum) || pageSizeNum < 1 || pageSizeNum > 50) {
|
if (isNaN(pageSizeNum) || pageSizeNum < 1 || pageSizeNum > 100) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Invalid page_size parameter (max 50)" },
|
{ error: "Invalid page_size parameter (max 100)" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -180,29 +184,139 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
console.log(
|
||||||
`https://world.openfoodfacts.org/cgi/search.pl?${params.toString()}`,
|
`[API] Iniciando busca: "${query}" (país: ${
|
||||||
{
|
country || "todos"
|
||||||
headers: {
|
}, page_size: ${pageSizeNum})`
|
||||||
"User-Agent": USER_AGENT,
|
|
||||||
Accept: "application/json",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!response.ok) {
|
// Primeiro, buscar no cache JSON
|
||||||
return NextResponse.json(
|
console.log(`[API] Buscando "${query}" no cache JSON...`);
|
||||||
{ error: "Erro ao buscar produtos" },
|
const localResults = await jsonCacheManager.searchProducts(
|
||||||
{ status: response.status }
|
query,
|
||||||
|
country || undefined,
|
||||||
|
pageSizeNum
|
||||||
|
);
|
||||||
|
|
||||||
|
// Se modo cache-only estiver ativo, retornar apenas resultados locais
|
||||||
|
if (cacheOnly || process.env.NEXT_PUBLIC_CACHE_ONLY_MODE === "true") {
|
||||||
|
console.log(
|
||||||
|
`[Cache-Only Mode] Retornando apenas ${localResults.products.length} produtos do cache`
|
||||||
);
|
);
|
||||||
|
return NextResponse.json({
|
||||||
|
products: localResults.products,
|
||||||
|
count: localResults.products.length,
|
||||||
|
page: pageNum,
|
||||||
|
page_size: pageSizeNum,
|
||||||
|
fromCache: true,
|
||||||
|
fromAPI: false,
|
||||||
|
cacheOnly: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
let fromAPI = false;
|
||||||
return NextResponse.json(data);
|
let apiProducts: Product[] = [];
|
||||||
|
|
||||||
|
// Se não encontrou resultados suficientes no cache JSON, buscar na API externa
|
||||||
|
if (localResults.products.length < pageSizeNum) {
|
||||||
|
console.log(
|
||||||
|
`Cache JSON retornou ${localResults.products.length} produtos, buscando na API externa...`
|
||||||
|
);
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`https://world.openfoodfacts.org/cgi/search.pl?${params.toString()}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"User-Agent": USER_AGENT,
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const apiData = await response.json();
|
||||||
|
apiProducts = apiData.products || [];
|
||||||
|
fromAPI = true;
|
||||||
|
|
||||||
|
// Ordenar produtos da API por relevância
|
||||||
|
if (apiProducts.length > 0) {
|
||||||
|
console.log(
|
||||||
|
`Ordenando ${apiProducts.length} produtos da API por relevância...`
|
||||||
|
);
|
||||||
|
apiProducts = sortByRelevance(apiProducts, query);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Salvando ${apiProducts.length} produtos da API no cache JSON...`
|
||||||
|
);
|
||||||
|
const saveResult = await jsonCacheManager.saveProducts(apiProducts);
|
||||||
|
console.log(
|
||||||
|
`Cache JSON atualizado: ${saveResult.saved} salvos, ${saveResult.failed} falharam`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combinar resultados JSON e da API
|
||||||
|
const allProducts: Product[] = [...localResults.products];
|
||||||
|
const localProductCodes = new Set(localResults.products.map((p) => p.code));
|
||||||
|
|
||||||
|
// Adicionar apenas produtos da API que não estão no cache JSON
|
||||||
|
const newApiProducts = apiProducts.filter(
|
||||||
|
(p) => !localProductCodes.has(p.code)
|
||||||
|
);
|
||||||
|
allProducts.push(...newApiProducts);
|
||||||
|
|
||||||
|
// Reordenar a lista combinada por relevância
|
||||||
|
console.log(
|
||||||
|
`Reordenando ${allProducts.length} produtos combinados por relevância...`
|
||||||
|
);
|
||||||
|
const sortedProducts = sortByRelevance(allProducts, query);
|
||||||
|
|
||||||
|
// Limitar ao tamanho da página solicitada
|
||||||
|
const paginatedProducts = sortedProducts.slice(0, pageSizeNum);
|
||||||
|
|
||||||
|
const responseData = {
|
||||||
|
products: paginatedProducts,
|
||||||
|
count: allProducts.length,
|
||||||
|
page: pageNum,
|
||||||
|
page_size: pageSizeNum,
|
||||||
|
skip: (pageNum - 1) * pageSizeNum,
|
||||||
|
fromCache: localResults.fromCache,
|
||||||
|
fromAPI: fromAPI,
|
||||||
|
cacheStats: {
|
||||||
|
localProducts: localResults.products.length,
|
||||||
|
apiProducts: apiProducts.length,
|
||||||
|
newProducts: newApiProducts.length,
|
||||||
|
totalReturned: paginatedProducts.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Busca finalizada: ${paginatedProducts.length} produtos (${localResults.products.length} do cache JSON, ${newApiProducts.length} novos da API)`
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json(responseData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erro ao buscar produtos:", error);
|
console.error("[API] Erro ao buscar produtos:", error);
|
||||||
|
|
||||||
|
// Retornar resposta de erro estruturada em vez de quebrar
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Erro ao buscar produtos" },
|
{
|
||||||
|
products: [],
|
||||||
|
count: 0,
|
||||||
|
page: pageNum,
|
||||||
|
page_size: pageSizeNum,
|
||||||
|
skip: (pageNum - 1) * pageSizeNum,
|
||||||
|
fromCache: false,
|
||||||
|
fromAPI: false,
|
||||||
|
error: "Erro interno do servidor",
|
||||||
|
cacheStats: {
|
||||||
|
localProducts: 0,
|
||||||
|
apiProducts: 0,
|
||||||
|
newProducts: 0,
|
||||||
|
totalReturned: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { jsonCacheManager } from "@/lib/jsonCacheManager";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
console.log("[API] Iniciando busca de estatísticas do storage...");
|
||||||
|
|
||||||
|
// Verificar se o cache JSON está inicializado
|
||||||
|
const isInitialized = await jsonCacheManager.isInitialized();
|
||||||
|
if (!isInitialized) {
|
||||||
|
console.log("[API] Cache JSON não inicializado, retornando dados vazios");
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
totalProducts: 0,
|
||||||
|
storageSizeMB: 0,
|
||||||
|
lastUpdated: 0,
|
||||||
|
averageProductSize: 0,
|
||||||
|
},
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obter estatísticas do storage JSON
|
||||||
|
const stats = await jsonCacheManager.getStorageStats();
|
||||||
|
console.log("[API] Estatísticas obtidas:", stats);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
data: stats,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[API] Erro ao obter estatísticas do storage:", error);
|
||||||
|
|
||||||
|
// Retornar dados vazios em caso de erro para não quebrar o frontend
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
totalProducts: 0,
|
||||||
|
storageSizeMB: 0,
|
||||||
|
lastUpdated: 0,
|
||||||
|
averageProductSize: 0,
|
||||||
|
},
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Database, Globe } from "lucide-react";
|
||||||
|
|
||||||
|
export function CacheOnlySwitch() {
|
||||||
|
const [cacheOnly, setCacheOnly] = useState(false);
|
||||||
|
const isProd = process.env.NODE_ENV === "production";
|
||||||
|
|
||||||
|
// Carregar preferência do localStorage
|
||||||
|
useEffect(() => {
|
||||||
|
const saved = localStorage.getItem("cache_only_mode");
|
||||||
|
if (saved) {
|
||||||
|
setCacheOnly(saved === "true");
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Salvar preferência
|
||||||
|
const handleToggle = (checked: boolean) => {
|
||||||
|
setCacheOnly(checked);
|
||||||
|
localStorage.setItem("cache_only_mode", checked.toString());
|
||||||
|
};
|
||||||
|
|
||||||
|
// Só exibir em produção
|
||||||
|
if (!isProd) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 p-3 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||||
|
{cacheOnly ? (
|
||||||
|
<Database className="w-4 h-4 text-blue-600" />
|
||||||
|
) : (
|
||||||
|
<Globe className="w-4 h-4 text-green-600" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Label htmlFor="cache-only" className="cursor-pointer">
|
||||||
|
{cacheOnly ? "Modo Cache Local" : "Modo Online"}
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
id="cache-only"
|
||||||
|
checked={cacheOnly}
|
||||||
|
onCheckedChange={handleToggle}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Filter, X, AlertTriangle, Zap } from "lucide-react";
|
import {
|
||||||
|
Filter,
|
||||||
|
X,
|
||||||
|
AlertTriangle,
|
||||||
|
Zap,
|
||||||
|
Grid,
|
||||||
|
List,
|
||||||
|
RefreshCw,
|
||||||
|
ArrowUpDown,
|
||||||
|
LayoutGrid,
|
||||||
|
Tag,
|
||||||
|
Beaker,
|
||||||
|
BarChart3,
|
||||||
|
} from "lucide-react";
|
||||||
import * as LucideIcons from "lucide-react";
|
import * as LucideIcons from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -17,6 +30,8 @@ import {
|
|||||||
} from "@/components/ui/accordion";
|
} from "@/components/ui/accordion";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Separator } from "@/components/ui/separator";
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { SortDropdown } from "@/app/components/SortDropdown";
|
||||||
|
import { FilterBadges } from "@/app/components/FilterBadge";
|
||||||
import {
|
import {
|
||||||
ProductFilters,
|
ProductFilters,
|
||||||
NUTRITION_GRADES,
|
NUTRITION_GRADES,
|
||||||
@@ -32,6 +47,14 @@ interface FilterSidebarProps {
|
|||||||
isLoading?: boolean;
|
isLoading?: boolean;
|
||||||
totalResults?: number;
|
totalResults?: number;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
sortBy?: string;
|
||||||
|
onSortChange?: (sortBy: string) => void;
|
||||||
|
viewMode?: "grid" | "list";
|
||||||
|
onViewModeChange?: (mode: "grid" | "list") => void;
|
||||||
|
onRefresh?: () => void;
|
||||||
|
onClearCache?: () => void;
|
||||||
|
isCached?: boolean;
|
||||||
|
onRemoveFilter?: (key: string, value?: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FilterSidebar({
|
export function FilterSidebar({
|
||||||
@@ -41,6 +64,14 @@ export function FilterSidebar({
|
|||||||
isLoading = false,
|
isLoading = false,
|
||||||
totalResults = 0,
|
totalResults = 0,
|
||||||
className = "",
|
className = "",
|
||||||
|
sortBy = "relevance",
|
||||||
|
onSortChange,
|
||||||
|
viewMode = "grid",
|
||||||
|
onViewModeChange,
|
||||||
|
onRefresh,
|
||||||
|
onClearCache,
|
||||||
|
isCached = false,
|
||||||
|
onRemoveFilter,
|
||||||
}: FilterSidebarProps) {
|
}: FilterSidebarProps) {
|
||||||
const [searchBrands, setSearchBrands] = useState("");
|
const [searchBrands, setSearchBrands] = useState("");
|
||||||
const [searchCategories, setSearchCategories] = useState("");
|
const [searchCategories, setSearchCategories] = useState("");
|
||||||
@@ -117,11 +148,116 @@ export function FilterSidebar({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Controles de Visualização e Cache */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Modo de Visualização */}
|
||||||
|
{onViewModeChange && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-sm font-medium">Modo de visualização</div>
|
||||||
|
<div className="flex items-center border border-gray-100 dark:border-gray-800 rounded-lg">
|
||||||
|
<Button
|
||||||
|
variant={viewMode === "grid" ? "default" : "ghost"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onViewModeChange("grid")}
|
||||||
|
className="rounded-r-none flex-1"
|
||||||
|
>
|
||||||
|
<Grid className="w-4 h-4 mr-2" />
|
||||||
|
Grade
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={viewMode === "list" ? "default" : "ghost"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onViewModeChange("list")}
|
||||||
|
className="rounded-l-none flex-1"
|
||||||
|
>
|
||||||
|
<List className="w-4 h-4 mr-2" />
|
||||||
|
Lista
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Controles de Cache */}
|
||||||
|
{(onRefresh || onClearCache) && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-sm font-medium">Controles</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{onRefresh && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={onRefresh}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="flex-1"
|
||||||
|
title="Atualizar busca"
|
||||||
|
>
|
||||||
|
<RefreshCw
|
||||||
|
className={`w-4 h-4 mr-2 ${
|
||||||
|
isLoading ? "animate-spin" : ""
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
Atualizar
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{onClearCache && isCached && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={onClearCache}
|
||||||
|
className="flex-1"
|
||||||
|
title="Limpar cache e refazer busca"
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4 mr-2" />
|
||||||
|
Limpar Cache
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filtros Ativos */}
|
||||||
|
{onRemoveFilter && hasActiveFilters && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="text-sm font-medium">Filtros ativos</div>
|
||||||
|
<FilterBadges
|
||||||
|
filters={filters}
|
||||||
|
onRemoveFilter={onRemoveFilter}
|
||||||
|
onClearAll={onClearFilters}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<Accordion
|
<Accordion
|
||||||
type="multiple"
|
type="multiple"
|
||||||
defaultValue={["nutrition", "categories"]}
|
defaultValue={["sorting"]}
|
||||||
className="space-y-4"
|
className="space-y-4"
|
||||||
>
|
>
|
||||||
|
{/* Ordenação */}
|
||||||
|
<AccordionItem
|
||||||
|
value="sorting"
|
||||||
|
className="border border-gray-100 dark:border-gray-800 rounded-lg"
|
||||||
|
>
|
||||||
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ArrowUpDown className="h-4 w-4 text-indigo-500" />
|
||||||
|
<span className="font-medium">Ordenação</span>
|
||||||
|
</div>
|
||||||
|
</AccordionTrigger>
|
||||||
|
<AccordionContent className="px-4 pb-4">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="text-sm font-medium mb-3">Ordenar por</div>
|
||||||
|
{onSortChange && (
|
||||||
|
<SortDropdown
|
||||||
|
value={sortBy}
|
||||||
|
onValueChange={onSortChange}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
|
||||||
{/* Nutri-Score */}
|
{/* Nutri-Score */}
|
||||||
<AccordionItem
|
<AccordionItem
|
||||||
value="nutrition"
|
value="nutrition"
|
||||||
@@ -219,7 +355,7 @@ export function FilterSidebar({
|
|||||||
>
|
>
|
||||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="h-4 w-4 rounded bg-blue-500" />
|
<LayoutGrid className="h-4 w-4 text-blue-500" />
|
||||||
<span className="font-medium">Categorias</span>
|
<span className="font-medium">Categorias</span>
|
||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
@@ -286,7 +422,7 @@ export function FilterSidebar({
|
|||||||
>
|
>
|
||||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="h-4 w-4 rounded bg-purple-500" />
|
<Tag className="h-4 w-4 text-purple-500" />
|
||||||
<span className="font-medium">Marcas</span>
|
<span className="font-medium">Marcas</span>
|
||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
@@ -360,7 +496,7 @@ export function FilterSidebar({
|
|||||||
>
|
>
|
||||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="h-4 w-4 rounded bg-orange-500" />
|
<Beaker className="h-4 w-4 text-orange-500" />
|
||||||
<span className="font-medium">Aditivos</span>
|
<span className="font-medium">Aditivos</span>
|
||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
@@ -393,7 +529,7 @@ export function FilterSidebar({
|
|||||||
>
|
>
|
||||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="h-4 w-4 rounded bg-green-500" />
|
<BarChart3 className="h-4 w-4 text-green-500" />
|
||||||
<span className="font-medium">Valores Nutricionais</span>
|
<span className="font-medium">Valores Nutricionais</span>
|
||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Search } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
|
||||||
|
interface SearchBarProps {
|
||||||
|
initialQuery?: string;
|
||||||
|
className?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchBar({
|
||||||
|
initialQuery = "",
|
||||||
|
className = "",
|
||||||
|
placeholder = "Buscar produtos...",
|
||||||
|
}: SearchBarProps) {
|
||||||
|
const [query, setQuery] = useState(initialQuery);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const handleSearch = () => {
|
||||||
|
if (query.trim()) {
|
||||||
|
router.push(`/resultados?q=${encodeURIComponent(query.trim())}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
handleSearch();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex items-center gap-2 ${className}`}>
|
||||||
|
<div className="relative flex-1 max-w-md">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
onKeyPress={handleKeyPress}
|
||||||
|
className="pl-10 pr-4 h-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={handleSearch}
|
||||||
|
disabled={!query.trim()}
|
||||||
|
className="h-10 px-4"
|
||||||
|
>
|
||||||
|
<Search className="h-4 w-4 mr-2" />
|
||||||
|
Buscar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -48,12 +48,14 @@ interface SortDropdownProps {
|
|||||||
value: string;
|
value: string;
|
||||||
onValueChange: (value: string) => void;
|
onValueChange: (value: string) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
align?: "start" | "center" | "end";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SortDropdown({
|
export function SortDropdown({
|
||||||
value,
|
value,
|
||||||
onValueChange,
|
onValueChange,
|
||||||
className = "",
|
className = "",
|
||||||
|
align = "start",
|
||||||
}: SortDropdownProps) {
|
}: SortDropdownProps) {
|
||||||
const selectedOption =
|
const selectedOption =
|
||||||
SORT_OPTIONS.find((option) => option.value === value) || SORT_OPTIONS[0];
|
SORT_OPTIONS.find((option) => option.value === value) || SORT_OPTIONS[0];
|
||||||
@@ -73,43 +75,48 @@ export function SortDropdown({
|
|||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
|
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
align="end"
|
align={align}
|
||||||
className="w-72 border-gray-100 dark:border-gray-800"
|
side="bottom"
|
||||||
|
sideOffset={4}
|
||||||
|
avoidCollisions={false}
|
||||||
|
className="w-64 max-w-[calc(100vw-2rem)] border-gray-100 dark:border-gray-800 z-50 p-0"
|
||||||
>
|
>
|
||||||
{SORT_OPTIONS.map((option) => {
|
<div className="max-h-80 overflow-y-auto">
|
||||||
const IconComponent = SORT_ICONS[option.value];
|
{SORT_OPTIONS.map((option) => {
|
||||||
return (
|
const IconComponent = SORT_ICONS[option.value];
|
||||||
<DropdownMenuItem
|
return (
|
||||||
key={option.value}
|
<DropdownMenuItem
|
||||||
onClick={() => onValueChange(option.value)}
|
key={option.value}
|
||||||
className={`flex items-start gap-3 p-3 ${
|
onClick={() => onValueChange(option.value)}
|
||||||
value === option.value ? "bg-accent" : ""
|
className={`flex items-start gap-3 p-3 ${
|
||||||
}`}
|
value === option.value ? "bg-accent" : ""
|
||||||
>
|
}`}
|
||||||
{/* Ícone */}
|
>
|
||||||
<div className="mt-0.5">
|
{/* Ícone */}
|
||||||
{IconComponent && (
|
<div className="mt-0.5">
|
||||||
<IconComponent className="w-4 h-4 text-muted-foreground" />
|
{IconComponent && (
|
||||||
)}
|
<IconComponent className="w-4 h-4 text-muted-foreground" />
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Conteúdo */}
|
|
||||||
<div className="flex-1">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="font-medium">{option.label}</span>
|
|
||||||
{value === option.value && (
|
|
||||||
<Check className="w-4 h-4 text-primary" />
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{option.description && (
|
|
||||||
<span className="text-xs text-muted-foreground mt-1 block">
|
{/* Conteúdo */}
|
||||||
{option.description}
|
<div className="flex-1">
|
||||||
</span>
|
<div className="flex items-center justify-between">
|
||||||
)}
|
<span className="font-medium">{option.label}</span>
|
||||||
</div>
|
{value === option.value && (
|
||||||
</DropdownMenuItem>
|
<Check className="w-4 h-4 text-primary" />
|
||||||
);
|
)}
|
||||||
})}
|
</div>
|
||||||
|
{option.description && (
|
||||||
|
<span className="text-xs text-muted-foreground mt-1 block">
|
||||||
|
{option.description}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
);
|
);
|
||||||
|
|||||||
+150
-106
@@ -5,28 +5,26 @@ import {
|
|||||||
Search,
|
Search,
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Loader2,
|
Loader2,
|
||||||
Grid,
|
|
||||||
List,
|
|
||||||
SlidersHorizontal,
|
SlidersHorizontal,
|
||||||
RefreshCw,
|
|
||||||
Database,
|
Database,
|
||||||
X,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
||||||
import { Product, sortProducts, fetchAllResults } from "@/lib/openFoodFactsApi";
|
|
||||||
import { ProductCard } from "@/app/components/ProductCard";
|
import { ProductCard } from "@/app/components/ProductCard";
|
||||||
import { ProductCardSkeleton } from "@/app/components/ProductCardSkeleton";
|
import { ProductCardSkeleton } from "@/app/components/ProductCardSkeleton";
|
||||||
import { FilterSidebar } from "@/app/components/FilterSidebar";
|
import { FilterSidebar } from "@/app/components/FilterSidebar";
|
||||||
import { FilterBadges } from "@/app/components/FilterBadge";
|
import { SearchBar } from "@/app/components/SearchBar";
|
||||||
import { SortDropdown } from "@/app/components/SortDropdown";
|
|
||||||
import { Pagination } from "@/app/components/Pagination";
|
import { Pagination } from "@/app/components/Pagination";
|
||||||
import { useProductFilters } from "@/hooks/useProductFilters";
|
import { useProductFilters } from "@/hooks/useProductFilters";
|
||||||
import { useSearchCache } from "@/hooks/useSearchCache";
|
import { useSearchCache } from "@/hooks/useSearchCache";
|
||||||
|
import { useStorageMonitor } from "@/hooks/useStorageMonitor";
|
||||||
|
import { useCacheOnlyMode } from "@/hooks/useCacheOnlyMode";
|
||||||
|
import { CacheOnlySwitch } from "@/app/components/CacheOnlySwitch";
|
||||||
import { detectUserCountry } from "@/lib/geolocation";
|
import { detectUserCountry } from "@/lib/geolocation";
|
||||||
import { FilterRecord } from "@/lib/cacheManager";
|
import { FilterRecord } from "@/lib/cacheManager";
|
||||||
import { ProductFilters } from "@/lib/types";
|
import { ProductFilters } from "@/lib/types";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { Product, sortProducts } from "@/lib/openFoodFactsApi";
|
||||||
|
|
||||||
// Função para converter ProductFilters para FilterRecord
|
// Função para converter ProductFilters para FilterRecord
|
||||||
function convertFiltersToRecord(filters: ProductFilters): FilterRecord {
|
function convertFiltersToRecord(filters: ProductFilters): FilterRecord {
|
||||||
@@ -65,7 +63,6 @@ function ResultadosContent() {
|
|||||||
getCachedSearch,
|
getCachedSearch,
|
||||||
saveSearch,
|
saveSearch,
|
||||||
clearCache,
|
clearCache,
|
||||||
updateProgress,
|
|
||||||
setError: setCacheError,
|
setError: setCacheError,
|
||||||
setLoading: setCacheLoading,
|
setLoading: setCacheLoading,
|
||||||
} = useSearchCache();
|
} = useSearchCache();
|
||||||
@@ -80,6 +77,13 @@ function ResultadosContent() {
|
|||||||
setIsLoading,
|
setIsLoading,
|
||||||
} = useProductFilters();
|
} = useProductFilters();
|
||||||
|
|
||||||
|
// Hook de monitoramento de storage
|
||||||
|
const { stats: storageStats, refreshStats: refreshStorageStats } =
|
||||||
|
useStorageMonitor();
|
||||||
|
|
||||||
|
// Hook de modo cache-only
|
||||||
|
const { cacheOnly } = useCacheOnlyMode();
|
||||||
|
|
||||||
// Detectar país do usuário
|
// Detectar país do usuário
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const detectCountry = async () => {
|
const detectCountry = async () => {
|
||||||
@@ -124,15 +128,31 @@ function ResultadosContent() {
|
|||||||
|
|
||||||
console.log("Fazendo busca completa na API");
|
console.log("Fazendo busca completa na API");
|
||||||
|
|
||||||
// Fazer busca completa
|
// Construir parâmetros da API
|
||||||
const result = await fetchAllResults(
|
const params = new URLSearchParams({
|
||||||
query,
|
q: query,
|
||||||
countryToUse,
|
country: countryToUse,
|
||||||
10, // Máximo 10 páginas (500 produtos)
|
page: "1",
|
||||||
(currentPage, totalPages, loadedProducts) => {
|
page_size: "50", // Buscar até 50 produtos por página
|
||||||
updateProgress(currentPage, totalPages, loadedProducts, 0);
|
});
|
||||||
}
|
|
||||||
);
|
if (cacheOnly) {
|
||||||
|
params.append("cache_only", "true");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fazer busca na API
|
||||||
|
const response = await fetch(`/api/search?${params.toString()}`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error || "Erro ao buscar produtos");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
products: data.products || [],
|
||||||
|
totalCount: data.count || 0,
|
||||||
|
actualPages: 1,
|
||||||
|
};
|
||||||
|
|
||||||
// Salvar no cache
|
// Salvar no cache
|
||||||
const searchId = saveSearch(
|
const searchId = saveSearch(
|
||||||
@@ -163,9 +183,9 @@ function ResultadosContent() {
|
|||||||
detectedCountry,
|
detectedCountry,
|
||||||
countryParam,
|
countryParam,
|
||||||
filters,
|
filters,
|
||||||
|
cacheOnly,
|
||||||
getCachedSearch,
|
getCachedSearch,
|
||||||
saveSearch,
|
saveSearch,
|
||||||
updateProgress,
|
|
||||||
setIsLoading,
|
setIsLoading,
|
||||||
setTotalResults,
|
setTotalResults,
|
||||||
setCacheLoading,
|
setCacheLoading,
|
||||||
@@ -180,6 +200,18 @@ function ResultadosContent() {
|
|||||||
}
|
}
|
||||||
}, [query, countryParam, detectedCountry, loadProducts, forceRefresh]);
|
}, [query, countryParam, detectedCountry, loadProducts, forceRefresh]);
|
||||||
|
|
||||||
|
// Sincronizar produtos com cache do servidor
|
||||||
|
useEffect(() => {
|
||||||
|
if (allProducts.length > 0) {
|
||||||
|
// Enviar produtos para cache em background
|
||||||
|
fetch("/api/cache/sync", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ products: allProducts }),
|
||||||
|
}).catch((err) => console.error("Erro ao sincronizar cache:", err));
|
||||||
|
}
|
||||||
|
}, [allProducts]);
|
||||||
|
|
||||||
// Produtos filtrados e ordenados para exibição
|
// Produtos filtrados e ordenados para exibição
|
||||||
const filteredAndSortedProducts = useMemo(() => {
|
const filteredAndSortedProducts = useMemo(() => {
|
||||||
let filtered = [...allProducts];
|
let filtered = [...allProducts];
|
||||||
@@ -221,6 +253,10 @@ function ResultadosContent() {
|
|||||||
setForceRefresh(true);
|
setForceRefresh(true);
|
||||||
}, [clearCache, query, detectedCountry, countryParam, filters]);
|
}, [clearCache, query, detectedCountry, countryParam, filters]);
|
||||||
|
|
||||||
|
const handleRefreshStorageStats = useCallback(() => {
|
||||||
|
refreshStorageStats();
|
||||||
|
}, [refreshStorageStats]);
|
||||||
|
|
||||||
const handleSortChange = useCallback(
|
const handleSortChange = useCallback(
|
||||||
(sortBy: string) => {
|
(sortBy: string) => {
|
||||||
updateFilters({
|
updateFilters({
|
||||||
@@ -288,67 +324,38 @@ function ResultadosContent() {
|
|||||||
{cacheState.isCached && (
|
{cacheState.isCached && (
|
||||||
<span className="ml-2 inline-flex items-center gap-1 text-blue-600 dark:text-blue-400">
|
<span className="ml-2 inline-flex items-center gap-1 text-blue-600 dark:text-blue-400">
|
||||||
<Database className="w-3 h-3" />
|
<Database className="w-3 h-3" />
|
||||||
Cache
|
Cache Local
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{storageStats && (
|
||||||
|
<span className="ml-2 text-xs text-gray-400">
|
||||||
|
• Storage: {storageStats.storageSizeMB} MB (
|
||||||
|
{storageStats.totalProducts} produtos)
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Controles de visualização - Desktop */}
|
{/* Switch Cache-Only em produção */}
|
||||||
<div className="hidden lg:flex items-center gap-3">
|
<CacheOnlySwitch />
|
||||||
<SortDropdown
|
|
||||||
value={filters.sortBy || "relevance"}
|
{/* Barra de Pesquisa - Desktop */}
|
||||||
onValueChange={handleSortChange}
|
<div className="hidden lg:flex items-center">
|
||||||
|
<SearchBar
|
||||||
|
initialQuery={query}
|
||||||
|
className="w-full max-w-md"
|
||||||
|
placeholder="Buscar outros produtos..."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="flex items-center border border-gray-100 dark:border-gray-800 rounded-lg">
|
|
||||||
<Button
|
|
||||||
variant={viewMode === "grid" ? "default" : "ghost"}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setViewMode("grid")}
|
|
||||||
className="rounded-r-none"
|
|
||||||
>
|
|
||||||
<Grid className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={viewMode === "list" ? "default" : "ghost"}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setViewMode("list")}
|
|
||||||
className="rounded-l-none"
|
|
||||||
>
|
|
||||||
<List className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Botões de controle de cache */}
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleRefresh}
|
|
||||||
disabled={loading}
|
|
||||||
title="Atualizar busca"
|
|
||||||
>
|
|
||||||
<RefreshCw
|
|
||||||
className={`w-4 h-4 ${loading ? "animate-spin" : ""}`}
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
{cacheState.isCached && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleClearCache}
|
|
||||||
title="Limpar cache e refazer busca"
|
|
||||||
>
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filtros Mobile */}
|
{/* Mobile Controls */}
|
||||||
<div className="lg:hidden">
|
<div className="lg:hidden flex items-center gap-2">
|
||||||
|
<SearchBar
|
||||||
|
initialQuery={query}
|
||||||
|
className="flex-1"
|
||||||
|
placeholder="Buscar..."
|
||||||
|
/>
|
||||||
<Sheet>
|
<Sheet>
|
||||||
<SheetTrigger asChild>
|
<SheetTrigger asChild>
|
||||||
<Button variant="outline" size="sm">
|
<Button variant="outline" size="sm">
|
||||||
@@ -366,6 +373,25 @@ function ResultadosContent() {
|
|||||||
onClearFilters={clearFilters}
|
onClearFilters={clearFilters}
|
||||||
isLoading={loading}
|
isLoading={loading}
|
||||||
totalResults={totalItems}
|
totalResults={totalItems}
|
||||||
|
sortBy={filters.sortBy || "relevance"}
|
||||||
|
onSortChange={handleSortChange}
|
||||||
|
viewMode={viewMode}
|
||||||
|
onViewModeChange={setViewMode}
|
||||||
|
onRefresh={handleRefresh}
|
||||||
|
onClearCache={handleClearCache}
|
||||||
|
isCached={cacheState.isCached}
|
||||||
|
onRemoveFilter={(key, value) => {
|
||||||
|
if (value) {
|
||||||
|
const currentArray =
|
||||||
|
(filters[key as keyof typeof filters] as string[]) ||
|
||||||
|
[];
|
||||||
|
updateFilters({
|
||||||
|
[key]: currentArray.filter((item) => item !== value),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
updateFilters({ [key]: undefined });
|
||||||
|
}
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</SheetContent>
|
</SheetContent>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
@@ -374,29 +400,6 @@ function ResultadosContent() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filtros ativos */}
|
|
||||||
{hasActiveFilters && (
|
|
||||||
<div className="bg-white dark:bg-gray-800 border-b border-gray-100 dark:border-gray-800">
|
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
|
|
||||||
<FilterBadges
|
|
||||||
filters={filters}
|
|
||||||
onRemoveFilter={(key, value) => {
|
|
||||||
if (value) {
|
|
||||||
const currentArray =
|
|
||||||
(filters[key as keyof typeof filters] as string[]) || [];
|
|
||||||
updateFilters({
|
|
||||||
[key]: currentArray.filter((item) => item !== value),
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
updateFilters({ [key]: undefined });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClearAll={clearFilters}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Layout principal */}
|
{/* Layout principal */}
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
<div className="flex gap-8">
|
<div className="flex gap-8">
|
||||||
@@ -409,6 +412,24 @@ function ResultadosContent() {
|
|||||||
onClearFilters={clearFilters}
|
onClearFilters={clearFilters}
|
||||||
isLoading={loading}
|
isLoading={loading}
|
||||||
totalResults={totalItems}
|
totalResults={totalItems}
|
||||||
|
sortBy={filters.sortBy || "relevance"}
|
||||||
|
onSortChange={handleSortChange}
|
||||||
|
viewMode={viewMode}
|
||||||
|
onViewModeChange={setViewMode}
|
||||||
|
onRefresh={handleRefresh}
|
||||||
|
onClearCache={handleClearCache}
|
||||||
|
isCached={cacheState.isCached}
|
||||||
|
onRemoveFilter={(key, value) => {
|
||||||
|
if (value) {
|
||||||
|
const currentArray =
|
||||||
|
(filters[key as keyof typeof filters] as string[]) || [];
|
||||||
|
updateFilters({
|
||||||
|
[key]: currentArray.filter((item) => item !== value),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
updateFilters({ [key]: undefined });
|
||||||
|
}
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -546,19 +567,42 @@ function ResultadosContent() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Informações adicionais */}
|
{/* Informações adicionais */}
|
||||||
{cacheState.isCached && (
|
<div className="text-center mt-6">
|
||||||
<div className="text-center mt-6">
|
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
{cacheState.isCached ? (
|
||||||
Dados carregados do cache •
|
<>
|
||||||
<button
|
Dados carregados do cache local •
|
||||||
onClick={handleRefresh}
|
<button
|
||||||
className="ml-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 underline"
|
onClick={handleRefresh}
|
||||||
>
|
className="ml-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 underline"
|
||||||
Atualizar busca
|
>
|
||||||
</button>
|
Atualizar busca
|
||||||
</p>
|
</button>
|
||||||
</div>
|
</>
|
||||||
)}
|
) : (
|
||||||
|
<>
|
||||||
|
Dados carregados da API externa •
|
||||||
|
<button
|
||||||
|
onClick={handleRefresh}
|
||||||
|
className="ml-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 underline"
|
||||||
|
>
|
||||||
|
Atualizar busca
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{storageStats && (
|
||||||
|
<>
|
||||||
|
{" • "}
|
||||||
|
<button
|
||||||
|
onClick={handleRefreshStorageStats}
|
||||||
|
className="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 underline"
|
||||||
|
>
|
||||||
|
Storage: {storageStats.storageSizeMB} MB
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const labelVariants = cva(
|
||||||
|
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||||
|
);
|
||||||
|
|
||||||
|
const Label = React.forwardRef<
|
||||||
|
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||||
|
VariantProps<typeof labelVariants>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
className={cn(labelVariants(), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
Label.displayName = LabelPrimitive.Root.displayName;
|
||||||
|
|
||||||
|
export { Label };
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
|
||||||
|
export function useCacheOnlyMode() {
|
||||||
|
const [cacheOnly, setCacheOnly] = useState(false);
|
||||||
|
const isProd = process.env.NODE_ENV === "production";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isProd) {
|
||||||
|
const saved = localStorage.getItem("cache_only_mode");
|
||||||
|
setCacheOnly(saved === "true");
|
||||||
|
}
|
||||||
|
}, [isProd]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleStorageChange = () => {
|
||||||
|
const saved = localStorage.getItem("cache_only_mode");
|
||||||
|
setCacheOnly(saved === "true");
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("storage", handleStorageChange);
|
||||||
|
return () => window.removeEventListener("storage", handleStorageChange);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
cacheOnly: isProd ? cacheOnly : false,
|
||||||
|
isProd,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/**
|
||||||
|
* Hook para monitoramento de storage JSON
|
||||||
|
* Exibe estatísticas no console apenas para IP específico
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } from "react";
|
||||||
|
import { StorageStats } from "@/lib/types";
|
||||||
|
|
||||||
|
interface UseStorageMonitorReturn {
|
||||||
|
stats: StorageStats | null;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
refreshStats: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// IP específico para monitoramento (conforme requisito)
|
||||||
|
const MONITOR_IP = "45.166.53.159";
|
||||||
|
|
||||||
|
export function useStorageMonitor(): UseStorageMonitorReturn {
|
||||||
|
const [stats, setStats] = useState<StorageStats | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se o IP do cliente é o IP de monitoramento
|
||||||
|
*/
|
||||||
|
const isMonitoringIP = useCallback(async (): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
// Fazer uma requisição para obter o IP público do cliente
|
||||||
|
const response = await fetch("https://api.ipify.org?format=json");
|
||||||
|
const data = await response.json();
|
||||||
|
return data.ip === MONITOR_IP;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("Não foi possível verificar IP do cliente:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca estatísticas do storage
|
||||||
|
*/
|
||||||
|
const fetchStats = useCallback(async (): Promise<void> => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const response = await fetch("/api/storage-stats");
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
setStats(data.data);
|
||||||
|
|
||||||
|
// Verificar se deve exibir no console
|
||||||
|
const shouldMonitor = await isMonitoringIP();
|
||||||
|
if (shouldMonitor) {
|
||||||
|
console.log(
|
||||||
|
`[JSON Cache] Storage: ${data.data.storageSizeMB} MB | Produtos: ${
|
||||||
|
data.data.totalProducts
|
||||||
|
} | Última atualização: ${new Date(
|
||||||
|
data.data.lastUpdated
|
||||||
|
).toLocaleString()}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error(data.error || "Erro ao obter estatísticas");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage =
|
||||||
|
err instanceof Error ? err.message : "Erro desconhecido";
|
||||||
|
setError(errorMessage);
|
||||||
|
console.error("Erro ao buscar estatísticas do storage:", errorMessage);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [isMonitoringIP]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atualiza estatísticas manualmente
|
||||||
|
*/
|
||||||
|
const refreshStats = useCallback(async (): Promise<void> => {
|
||||||
|
await fetchStats();
|
||||||
|
}, [fetchStats]);
|
||||||
|
|
||||||
|
// Buscar estatísticas ao montar o componente
|
||||||
|
useEffect(() => {
|
||||||
|
fetchStats();
|
||||||
|
}, [fetchStats]);
|
||||||
|
|
||||||
|
// Monitoramento automático para todos os usuários
|
||||||
|
useEffect(() => {
|
||||||
|
let intervalId: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
const startMonitoring = async () => {
|
||||||
|
// Executar imediatamente
|
||||||
|
await fetchAndDisplayStats();
|
||||||
|
|
||||||
|
// Depois executar a cada 10 segundos
|
||||||
|
intervalId = setInterval(async () => {
|
||||||
|
await fetchAndDisplayStats();
|
||||||
|
}, 10000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchAndDisplayStats = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/storage-stats");
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
console.log(
|
||||||
|
`[Monitor] Total de produtos no cache: ${data.data.totalProducts} produtos`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Monitor] Erro ao buscar estatísticas:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
startMonitoring();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (intervalId) {
|
||||||
|
clearInterval(intervalId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
stats,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
refreshStats,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,427 @@
|
|||||||
|
/**
|
||||||
|
* Gerenciador de Cache de Produtos baseado em JSON
|
||||||
|
* Gerencia armazenamento, busca e merge inteligente de dados no servidor
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { promises as fs } from "fs";
|
||||||
|
import fsSync from "fs";
|
||||||
|
import path from "path";
|
||||||
|
import { Product } from "./openFoodFactsApi";
|
||||||
|
import { CachedProduct, StorageStats } from "./types";
|
||||||
|
|
||||||
|
interface JsonCacheData {
|
||||||
|
products: { [key: string]: CachedProduct };
|
||||||
|
lastUpdated: number;
|
||||||
|
version: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class JsonCacheManager {
|
||||||
|
private cacheFilePath: string;
|
||||||
|
private cacheData: JsonCacheData | null = null;
|
||||||
|
private static instance: JsonCacheManager;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// Definir caminho do arquivo de cache JSON
|
||||||
|
this.cacheFilePath = path.join(
|
||||||
|
process.cwd(),
|
||||||
|
"data",
|
||||||
|
"products-cache.json"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Criar diretório se não existir
|
||||||
|
const dataDir = path.dirname(this.cacheFilePath);
|
||||||
|
try {
|
||||||
|
if (!fsSync.existsSync(dataDir)) {
|
||||||
|
fsSync.mkdirSync(dataDir, { recursive: true });
|
||||||
|
console.log(`[JSON Cache] Diretório criado: ${dataDir}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao criar diretório:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Singleton pattern para garantir uma única instância
|
||||||
|
*/
|
||||||
|
static getInstance(): JsonCacheManager {
|
||||||
|
if (!JsonCacheManager.instance) {
|
||||||
|
JsonCacheManager.instance = new JsonCacheManager();
|
||||||
|
}
|
||||||
|
return JsonCacheManager.instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carrega dados do cache do arquivo JSON
|
||||||
|
*/
|
||||||
|
private async loadCache(): Promise<void> {
|
||||||
|
if (this.cacheData) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (fsSync.existsSync(this.cacheFilePath)) {
|
||||||
|
const fileContent = await fs.readFile(this.cacheFilePath, "utf-8");
|
||||||
|
this.cacheData = JSON.parse(fileContent) as JsonCacheData;
|
||||||
|
console.log(
|
||||||
|
`[JSON Cache] Cache carregado: ${
|
||||||
|
Object.keys(this.cacheData.products).length
|
||||||
|
} produtos`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.cacheData = {
|
||||||
|
products: {},
|
||||||
|
lastUpdated: 0,
|
||||||
|
version: "1.0.0",
|
||||||
|
};
|
||||||
|
console.log("[JSON Cache] Cache inicializado vazio");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao carregar cache:", error);
|
||||||
|
this.cacheData = {
|
||||||
|
products: {},
|
||||||
|
lastUpdated: 0,
|
||||||
|
version: "1.0.0",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Salva dados do cache no arquivo JSON
|
||||||
|
*/
|
||||||
|
private async saveCache(): Promise<void> {
|
||||||
|
if (!this.cacheData) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.writeFile(
|
||||||
|
this.cacheFilePath,
|
||||||
|
JSON.stringify(this.cacheData, null, 2),
|
||||||
|
"utf-8"
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`[JSON Cache] Cache salvo: ${
|
||||||
|
Object.keys(this.cacheData.products).length
|
||||||
|
} produtos`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao salvar cache:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converte Product para CachedProduct
|
||||||
|
*/
|
||||||
|
private convertToCachedProduct(product: Product): CachedProduct {
|
||||||
|
return {
|
||||||
|
...product,
|
||||||
|
_metadata: {
|
||||||
|
firstSeen: Date.now(),
|
||||||
|
lastUpdated: Date.now(),
|
||||||
|
updateCount: 1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converte CachedProduct para Product
|
||||||
|
*/
|
||||||
|
private convertToAPIProduct(cachedProduct: CachedProduct): Product {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
const { _metadata, ...product } = cachedProduct;
|
||||||
|
return product as Product;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge inteligente de dados de produto
|
||||||
|
*/
|
||||||
|
private mergeProductData(
|
||||||
|
existing: CachedProduct,
|
||||||
|
newData: Product
|
||||||
|
): CachedProduct {
|
||||||
|
return {
|
||||||
|
...existing,
|
||||||
|
...newData,
|
||||||
|
_metadata: {
|
||||||
|
...existing._metadata,
|
||||||
|
lastUpdated: Date.now(),
|
||||||
|
updateCount: existing._metadata.updateCount + 1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcula score de relevância de um produto em relação à query
|
||||||
|
*/
|
||||||
|
private calculateRelevanceScore(
|
||||||
|
product: Product,
|
||||||
|
searchTerm: string
|
||||||
|
): number {
|
||||||
|
const productName = product.product_name?.toLowerCase() || "";
|
||||||
|
const lowerSearchTerm = searchTerm.toLowerCase();
|
||||||
|
|
||||||
|
// Nome exato = maior prioridade
|
||||||
|
if (productName === lowerSearchTerm) {
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nome começa com a query = alta prioridade
|
||||||
|
if (productName.startsWith(lowerSearchTerm)) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nome contém a query = média prioridade
|
||||||
|
if (productName.includes(lowerSearchTerm)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correspondência em marca ou categoria = baixa prioridade
|
||||||
|
if (
|
||||||
|
product.brands?.toLowerCase().includes(lowerSearchTerm) ||
|
||||||
|
product.categories?.toLowerCase().includes(lowerSearchTerm)
|
||||||
|
) {
|
||||||
|
return 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca produto por código de barras
|
||||||
|
*/
|
||||||
|
async getProductByCode(code: string): Promise<Product | null> {
|
||||||
|
try {
|
||||||
|
await this.loadCache();
|
||||||
|
|
||||||
|
if (!this.cacheData) return null;
|
||||||
|
|
||||||
|
const cachedProduct = this.cacheData.products[code];
|
||||||
|
if (cachedProduct) {
|
||||||
|
console.log(`[JSON Cache] Produto encontrado: ${code}`);
|
||||||
|
return this.convertToAPIProduct(cachedProduct);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[JSON Cache] Produto não encontrado: ${code}`);
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao buscar produto por código:", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca produtos por query (nome, marca, categoria)
|
||||||
|
*/
|
||||||
|
async searchProducts(
|
||||||
|
query: string,
|
||||||
|
country?: string,
|
||||||
|
limit: number = 50
|
||||||
|
): Promise<{
|
||||||
|
products: Product[];
|
||||||
|
totalCount: number;
|
||||||
|
fromCache: boolean;
|
||||||
|
fromAPI: boolean;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
await this.loadCache();
|
||||||
|
|
||||||
|
if (!this.cacheData) {
|
||||||
|
return {
|
||||||
|
products: [],
|
||||||
|
totalCount: 0,
|
||||||
|
fromCache: false,
|
||||||
|
fromAPI: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const searchTerm = query.toLowerCase();
|
||||||
|
console.log(
|
||||||
|
`[JSON Cache] Buscando: "${searchTerm}" (país: ${country || "todos"})`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Filtrar produtos
|
||||||
|
const filteredProducts = Object.values(this.cacheData.products)
|
||||||
|
.filter((cachedProduct) => {
|
||||||
|
const product = this.convertToAPIProduct(cachedProduct);
|
||||||
|
|
||||||
|
// Verificar se corresponde à query
|
||||||
|
const matchesQuery =
|
||||||
|
product.product_name?.toLowerCase().includes(searchTerm) ||
|
||||||
|
product.brands?.toLowerCase().includes(searchTerm) ||
|
||||||
|
product.categories?.toLowerCase().includes(searchTerm);
|
||||||
|
|
||||||
|
// Verificar país se especificado
|
||||||
|
const matchesCountry =
|
||||||
|
!country ||
|
||||||
|
product.countries_tags?.includes(country) ||
|
||||||
|
product.countries?.toLowerCase().includes(country.toLowerCase());
|
||||||
|
|
||||||
|
return matchesQuery && matchesCountry;
|
||||||
|
})
|
||||||
|
.map((cachedProduct) => this.convertToAPIProduct(cachedProduct))
|
||||||
|
// Ordenar por relevância
|
||||||
|
.sort((a, b) => {
|
||||||
|
const scoreA = this.calculateRelevanceScore(a, searchTerm);
|
||||||
|
const scoreB = this.calculateRelevanceScore(b, searchTerm);
|
||||||
|
return scoreB - scoreA;
|
||||||
|
})
|
||||||
|
.slice(0, limit);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[JSON Cache] Encontrados ${filteredProducts.length} produtos`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
products: filteredProducts,
|
||||||
|
totalCount: filteredProducts.length,
|
||||||
|
fromCache: true,
|
||||||
|
fromAPI: false,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao buscar produtos:", error);
|
||||||
|
return {
|
||||||
|
products: [],
|
||||||
|
totalCount: 0,
|
||||||
|
fromCache: false,
|
||||||
|
fromAPI: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Salva ou atualiza produto no cache
|
||||||
|
*/
|
||||||
|
async saveProduct(product: Product): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await this.loadCache();
|
||||||
|
|
||||||
|
if (!this.cacheData) {
|
||||||
|
this.cacheData = {
|
||||||
|
products: {},
|
||||||
|
lastUpdated: 0,
|
||||||
|
version: "1.0.0",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = product.code;
|
||||||
|
const existingProduct = this.cacheData.products[code];
|
||||||
|
|
||||||
|
if (existingProduct) {
|
||||||
|
this.cacheData.products[code] = this.mergeProductData(
|
||||||
|
existingProduct,
|
||||||
|
product
|
||||||
|
);
|
||||||
|
console.log(`[JSON Cache] Produto atualizado: ${code}`);
|
||||||
|
} else {
|
||||||
|
this.cacheData.products[code] = this.convertToCachedProduct(product);
|
||||||
|
console.log(`[JSON Cache] Produto adicionado: ${code}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cacheData.lastUpdated = Date.now();
|
||||||
|
await this.saveCache();
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao salvar produto:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Salva múltiplos produtos no cache
|
||||||
|
*/
|
||||||
|
async saveProducts(products: Product[]): Promise<{
|
||||||
|
saved: number;
|
||||||
|
failed: number;
|
||||||
|
}> {
|
||||||
|
let saved = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
for (const product of products) {
|
||||||
|
const success = await this.saveProduct(product);
|
||||||
|
if (success) {
|
||||||
|
saved++;
|
||||||
|
} else {
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[JSON Cache] Salvos: ${saved}, Falharam: ${failed}`);
|
||||||
|
return { saved, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém estatísticas do cache
|
||||||
|
*/
|
||||||
|
async getStorageStats(): Promise<StorageStats> {
|
||||||
|
try {
|
||||||
|
await this.loadCache();
|
||||||
|
|
||||||
|
if (!this.cacheData) {
|
||||||
|
return {
|
||||||
|
totalProducts: 0,
|
||||||
|
storageSizeMB: 0,
|
||||||
|
lastUpdated: 0,
|
||||||
|
averageProductSize: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const productCount = Object.keys(this.cacheData.products).length;
|
||||||
|
|
||||||
|
// Calcular tamanho do arquivo
|
||||||
|
let fileSize = 0;
|
||||||
|
try {
|
||||||
|
const stats = await fs.stat(this.cacheFilePath);
|
||||||
|
fileSize = stats.size;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao obter tamanho do arquivo:", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeInMB = fileSize / (1024 * 1024);
|
||||||
|
const averageSize = productCount > 0 ? fileSize / productCount : 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalProducts: productCount,
|
||||||
|
storageSizeMB: parseFloat(sizeInMB.toFixed(2)),
|
||||||
|
lastUpdated: this.cacheData.lastUpdated,
|
||||||
|
averageProductSize: parseFloat(averageSize.toFixed(0)),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao obter estatísticas:", error);
|
||||||
|
return {
|
||||||
|
totalProducts: 0,
|
||||||
|
storageSizeMB: 0,
|
||||||
|
lastUpdated: 0,
|
||||||
|
averageProductSize: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Limpa todo o cache
|
||||||
|
*/
|
||||||
|
async clearCache(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
this.cacheData = {
|
||||||
|
products: {},
|
||||||
|
lastUpdated: 0,
|
||||||
|
version: "1.0.0",
|
||||||
|
};
|
||||||
|
await this.saveCache();
|
||||||
|
console.log("[JSON Cache] Cache limpo");
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[JSON Cache] Erro ao limpar cache:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se o cache está inicializado
|
||||||
|
*/
|
||||||
|
async isInitialized(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await this.loadCache();
|
||||||
|
return this.cacheData !== null;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exportar instância singleton
|
||||||
|
export const jsonCacheManager = JsonCacheManager.getInstance();
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { Product } from "./openFoodFactsApi";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calcula score de relevância de um produto em relação à query
|
||||||
|
*/
|
||||||
|
export function calculateRelevanceScore(
|
||||||
|
product: Product,
|
||||||
|
searchTerm: string
|
||||||
|
): number {
|
||||||
|
const productName = product.product_name?.toLowerCase() || "";
|
||||||
|
const lowerSearchTerm = searchTerm.toLowerCase();
|
||||||
|
|
||||||
|
// Nome exato = maior prioridade
|
||||||
|
if (productName === lowerSearchTerm) {
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nome começa com a query = alta prioridade
|
||||||
|
if (productName.startsWith(lowerSearchTerm)) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nome contém a query = média prioridade
|
||||||
|
if (productName.includes(lowerSearchTerm)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correspondência em marca ou categoria = baixa prioridade
|
||||||
|
if (
|
||||||
|
product.brands?.toLowerCase().includes(lowerSearchTerm) ||
|
||||||
|
product.categories?.toLowerCase().includes(lowerSearchTerm)
|
||||||
|
) {
|
||||||
|
return 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ordena produtos por relevância em relação à query
|
||||||
|
*/
|
||||||
|
export function sortByRelevance(
|
||||||
|
products: Product[],
|
||||||
|
searchTerm: string
|
||||||
|
): Product[] {
|
||||||
|
return products
|
||||||
|
.map((product) => ({
|
||||||
|
product,
|
||||||
|
relevanceScore: calculateRelevanceScore(product, searchTerm),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.relevanceScore - a.relevanceScore)
|
||||||
|
.map(({ product }) => product);
|
||||||
|
}
|
||||||
@@ -332,3 +332,58 @@ export interface PaginationProps {
|
|||||||
config?: Partial<PaginationConfig>;
|
config?: Partial<PaginationConfig>;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tipos para Cache de Produtos
|
||||||
|
export interface CachedProduct {
|
||||||
|
code: string;
|
||||||
|
product_name: string;
|
||||||
|
brands?: string;
|
||||||
|
categories?: string;
|
||||||
|
ingredients_text?: string;
|
||||||
|
nutriments?: {
|
||||||
|
energy_100g?: number;
|
||||||
|
fat_100g?: number;
|
||||||
|
carbohydrates_100g?: number;
|
||||||
|
proteins_100g?: number;
|
||||||
|
sugars_100g?: number;
|
||||||
|
fiber_100g?: number;
|
||||||
|
sodium_100g?: number;
|
||||||
|
};
|
||||||
|
nutrition_grades?: string;
|
||||||
|
nova_group?: number;
|
||||||
|
image_url?: string;
|
||||||
|
image_small_url?: string;
|
||||||
|
image_front_url?: string;
|
||||||
|
image_front_small_url?: string;
|
||||||
|
countries?: string;
|
||||||
|
countries_tags?: string[];
|
||||||
|
allergens_tags?: string[];
|
||||||
|
additives_tags?: string[];
|
||||||
|
_metadata: {
|
||||||
|
firstSeen: number;
|
||||||
|
lastUpdated: number;
|
||||||
|
updateCount: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StorageStats {
|
||||||
|
totalProducts: number;
|
||||||
|
storageSizeMB: number;
|
||||||
|
lastUpdated: number;
|
||||||
|
averageProductSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CacheSearchResult {
|
||||||
|
products: CachedProduct[];
|
||||||
|
totalCount: number;
|
||||||
|
fromCache: boolean;
|
||||||
|
fromAPI: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CacheFile {
|
||||||
|
products: Record<string, CachedProduct>;
|
||||||
|
metadata: {
|
||||||
|
totalProducts: number;
|
||||||
|
lastSync: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"@radix-ui/react-checkbox": "^1.3.3",
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
"@radix-ui/react-dialog": "^1.1.2",
|
"@radix-ui/react-dialog": "^1.1.2",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.2",
|
"@radix-ui/react-dropdown-menu": "^2.1.2",
|
||||||
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
"@radix-ui/react-radio-group": "^1.3.8",
|
"@radix-ui/react-radio-group": "^1.3.8",
|
||||||
"@radix-ui/react-select": "^2.1.2",
|
"@radix-ui/react-select": "^2.1.2",
|
||||||
"@radix-ui/react-separator": "^1.1.7",
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
|
|||||||
Generated
+25
-8
@@ -26,6 +26,9 @@ importers:
|
|||||||
'@radix-ui/react-dropdown-menu':
|
'@radix-ui/react-dropdown-menu':
|
||||||
specifier: ^2.1.2
|
specifier: ^2.1.2
|
||||||
version: 2.1.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
version: 2.1.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||||
|
'@radix-ui/react-label':
|
||||||
|
specifier: ^2.1.7
|
||||||
|
version: 2.1.7(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||||
'@radix-ui/react-radio-group':
|
'@radix-ui/react-radio-group':
|
||||||
specifier: ^1.3.8
|
specifier: ^1.3.8
|
||||||
version: 1.3.8(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
version: 1.3.8(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||||
@@ -53,9 +56,6 @@ importers:
|
|||||||
framer-motion:
|
framer-motion:
|
||||||
specifier: ^11.12.0
|
specifier: ^11.12.0
|
||||||
version: 11.12.0([email protected]([email protected]))([email protected])
|
version: 11.12.0([email protected]([email protected]))([email protected])
|
||||||
html5-qrcode:
|
|
||||||
specifier: ^2.3.8
|
|
||||||
version: 2.3.8
|
|
||||||
lucide-react:
|
lucide-react:
|
||||||
specifier: ^0.460.0
|
specifier: ^0.460.0
|
||||||
version: 0.460.0([email protected])
|
version: 0.460.0([email protected])
|
||||||
@@ -565,6 +565,19 @@ packages:
|
|||||||
'@types/react':
|
'@types/react':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@radix-ui/[email protected]':
|
||||||
|
resolution: {integrity: sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ==}
|
||||||
|
peerDependencies:
|
||||||
|
'@types/react': '*'
|
||||||
|
'@types/react-dom': '*'
|
||||||
|
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||||
|
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||||
|
peerDependenciesMeta:
|
||||||
|
'@types/react':
|
||||||
|
optional: true
|
||||||
|
'@types/react-dom':
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@radix-ui/[email protected]':
|
'@radix-ui/[email protected]':
|
||||||
resolution: {integrity: sha512-lZ0R4qR2Al6fZ4yCCZzu/ReTFrylHFxIqy7OezIpWF4bL0o9biKo0pFIvkaew3TyZ9Fy5gYVrR5zCGZBVbO1zg==}
|
resolution: {integrity: sha512-lZ0R4qR2Al6fZ4yCCZzu/ReTFrylHFxIqy7OezIpWF4bL0o9biKo0pFIvkaew3TyZ9Fy5gYVrR5zCGZBVbO1zg==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -1649,9 +1662,6 @@ packages:
|
|||||||
resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}
|
resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
|
|
||||||
[email protected]:
|
|
||||||
resolution: {integrity: sha512-jsr4vafJhwoLVEDW3n1KvPnCCXWaQfRng0/EEYk1vNcQGcG/htAdhJX0be8YyqMoSz7+hZvOZSTAepsabiuhiQ==}
|
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
||||||
engines: {node: '>= 4'}
|
engines: {node: '>= 4'}
|
||||||
@@ -2989,6 +2999,15 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 18.3.12
|
'@types/react': 18.3.12
|
||||||
|
|
||||||
|
'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':
|
||||||
|
dependencies:
|
||||||
|
'@radix-ui/react-primitive': 2.1.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||||
|
react: 18.3.1
|
||||||
|
react-dom: 18.3.1([email protected])
|
||||||
|
optionalDependencies:
|
||||||
|
'@types/react': 18.3.12
|
||||||
|
'@types/react-dom': 18.3.1
|
||||||
|
|
||||||
'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':
|
'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@radix-ui/primitive': 1.1.0
|
'@radix-ui/primitive': 1.1.0
|
||||||
@@ -4290,8 +4309,6 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
parse-passwd: 1.0.0
|
parse-passwd: 1.0.0
|
||||||
|
|
||||||
[email protected]: {}
|
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
onlyBuiltDependencies:
|
onlyBuiltDependencies:
|
||||||
- '@prisma/client'
|
- '@prisma/client'
|
||||||
- '@prisma/engines'
|
- '@prisma/engines'
|
||||||
|
- leveldown
|
||||||
- prisma
|
- prisma
|
||||||
Reference in new issue
Block a user