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 { jsonCacheManager } from "@/lib/jsonCacheManager";
|
||||
|
||||
const USER_AGENT = "NutriScan/1.0 (https://nutriscan.com.br)";
|
||||
|
||||
@@ -7,6 +8,8 @@ export async function GET(
|
||||
{ params }: { params: { barcode: string } }
|
||||
) {
|
||||
const { barcode } = params;
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const cacheOnly = searchParams.get("cache_only") === "true";
|
||||
|
||||
// Validar código de barras
|
||||
const cleanBarcode = barcode.replace(/\D/g, "");
|
||||
@@ -18,6 +21,36 @@ export async function GET(
|
||||
}
|
||||
|
||||
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(
|
||||
`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) {
|
||||
console.error("Erro ao buscar produto:", error);
|
||||
console.error("[API] Erro ao buscar produto:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao buscar produto" },
|
||||
{
|
||||
error: "Erro interno do servidor",
|
||||
fromCache: false,
|
||||
fromAPI: false,
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
+132
-18
@@ -1,4 +1,7 @@
|
||||
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)";
|
||||
|
||||
@@ -8,6 +11,7 @@ export async function GET(request: NextRequest) {
|
||||
const country = searchParams.get("country");
|
||||
const page = searchParams.get("page") || "1";
|
||||
const pageSize = searchParams.get("page_size") || "20";
|
||||
const cacheOnly = searchParams.get("cache_only") === "true";
|
||||
|
||||
if (!query) {
|
||||
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(
|
||||
{ error: "Invalid page_size parameter (max 50)" },
|
||||
{ error: "Invalid page_size parameter (max 100)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -180,29 +184,139 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://world.openfoodfacts.org/cgi/search.pl?${params.toString()}`,
|
||||
{
|
||||
headers: {
|
||||
"User-Agent": USER_AGENT,
|
||||
Accept: "application/json",
|
||||
},
|
||||
}
|
||||
console.log(
|
||||
`[API] Iniciando busca: "${query}" (país: ${
|
||||
country || "todos"
|
||||
}, page_size: ${pageSizeNum})`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao buscar produtos" },
|
||||
{ status: response.status }
|
||||
// Primeiro, buscar no cache JSON
|
||||
console.log(`[API] Buscando "${query}" no cache JSON...`);
|
||||
const localResults = await jsonCacheManager.searchProducts(
|
||||
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();
|
||||
return NextResponse.json(data);
|
||||
let fromAPI = false;
|
||||
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) {
|
||||
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(
|
||||
{ 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 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
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 { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -17,6 +30,8 @@ import {
|
||||
} from "@/components/ui/accordion";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { SortDropdown } from "@/app/components/SortDropdown";
|
||||
import { FilterBadges } from "@/app/components/FilterBadge";
|
||||
import {
|
||||
ProductFilters,
|
||||
NUTRITION_GRADES,
|
||||
@@ -32,6 +47,14 @@ interface FilterSidebarProps {
|
||||
isLoading?: boolean;
|
||||
totalResults?: number;
|
||||
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({
|
||||
@@ -41,6 +64,14 @@ export function FilterSidebar({
|
||||
isLoading = false,
|
||||
totalResults = 0,
|
||||
className = "",
|
||||
sortBy = "relevance",
|
||||
onSortChange,
|
||||
viewMode = "grid",
|
||||
onViewModeChange,
|
||||
onRefresh,
|
||||
onClearCache,
|
||||
isCached = false,
|
||||
onRemoveFilter,
|
||||
}: FilterSidebarProps) {
|
||||
const [searchBrands, setSearchBrands] = useState("");
|
||||
const [searchCategories, setSearchCategories] = useState("");
|
||||
@@ -117,11 +148,116 @@ export function FilterSidebar({
|
||||
</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
|
||||
type="multiple"
|
||||
defaultValue={["nutrition", "categories"]}
|
||||
defaultValue={["sorting"]}
|
||||
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 */}
|
||||
<AccordionItem
|
||||
value="nutrition"
|
||||
@@ -219,7 +355,7 @@ export function FilterSidebar({
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<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>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
@@ -286,7 +422,7 @@ export function FilterSidebar({
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<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>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
@@ -360,7 +496,7 @@ export function FilterSidebar({
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<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>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
@@ -393,7 +529,7 @@ export function FilterSidebar({
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<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>
|
||||
</div>
|
||||
</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;
|
||||
onValueChange: (value: string) => void;
|
||||
className?: string;
|
||||
align?: "start" | "center" | "end";
|
||||
}
|
||||
|
||||
export function SortDropdown({
|
||||
value,
|
||||
onValueChange,
|
||||
className = "",
|
||||
align = "start",
|
||||
}: SortDropdownProps) {
|
||||
const selectedOption =
|
||||
SORT_OPTIONS.find((option) => option.value === value) || SORT_OPTIONS[0];
|
||||
@@ -73,43 +75,48 @@ export function SortDropdown({
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
className="w-72 border-gray-100 dark:border-gray-800"
|
||||
align={align}
|
||||
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) => {
|
||||
const IconComponent = SORT_ICONS[option.value];
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => onValueChange(option.value)}
|
||||
className={`flex items-start gap-3 p-3 ${
|
||||
value === option.value ? "bg-accent" : ""
|
||||
}`}
|
||||
>
|
||||
{/* Ícone */}
|
||||
<div className="mt-0.5">
|
||||
{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 className="max-h-80 overflow-y-auto">
|
||||
{SORT_OPTIONS.map((option) => {
|
||||
const IconComponent = SORT_ICONS[option.value];
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => onValueChange(option.value)}
|
||||
className={`flex items-start gap-3 p-3 ${
|
||||
value === option.value ? "bg-accent" : ""
|
||||
}`}
|
||||
>
|
||||
{/* Ícone */}
|
||||
<div className="mt-0.5">
|
||||
{IconComponent && (
|
||||
<IconComponent className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
{option.description && (
|
||||
<span className="text-xs text-muted-foreground mt-1 block">
|
||||
{option.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 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>
|
||||
{option.description && (
|
||||
<span className="text-xs text-muted-foreground mt-1 block">
|
||||
{option.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
|
||||
+150
-106
@@ -5,28 +5,26 @@ import {
|
||||
Search,
|
||||
ArrowLeft,
|
||||
Loader2,
|
||||
Grid,
|
||||
List,
|
||||
SlidersHorizontal,
|
||||
RefreshCw,
|
||||
Database,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { Product, sortProducts, fetchAllResults } from "@/lib/openFoodFactsApi";
|
||||
import { ProductCard } from "@/app/components/ProductCard";
|
||||
import { ProductCardSkeleton } from "@/app/components/ProductCardSkeleton";
|
||||
import { FilterSidebar } from "@/app/components/FilterSidebar";
|
||||
import { FilterBadges } from "@/app/components/FilterBadge";
|
||||
import { SortDropdown } from "@/app/components/SortDropdown";
|
||||
import { SearchBar } from "@/app/components/SearchBar";
|
||||
import { Pagination } from "@/app/components/Pagination";
|
||||
import { useProductFilters } from "@/hooks/useProductFilters";
|
||||
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 { FilterRecord } from "@/lib/cacheManager";
|
||||
import { ProductFilters } from "@/lib/types";
|
||||
import Link from "next/link";
|
||||
import { Product, sortProducts } from "@/lib/openFoodFactsApi";
|
||||
|
||||
// Função para converter ProductFilters para FilterRecord
|
||||
function convertFiltersToRecord(filters: ProductFilters): FilterRecord {
|
||||
@@ -65,7 +63,6 @@ function ResultadosContent() {
|
||||
getCachedSearch,
|
||||
saveSearch,
|
||||
clearCache,
|
||||
updateProgress,
|
||||
setError: setCacheError,
|
||||
setLoading: setCacheLoading,
|
||||
} = useSearchCache();
|
||||
@@ -80,6 +77,13 @@ function ResultadosContent() {
|
||||
setIsLoading,
|
||||
} = 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
|
||||
useEffect(() => {
|
||||
const detectCountry = async () => {
|
||||
@@ -124,15 +128,31 @@ function ResultadosContent() {
|
||||
|
||||
console.log("Fazendo busca completa na API");
|
||||
|
||||
// Fazer busca completa
|
||||
const result = await fetchAllResults(
|
||||
query,
|
||||
countryToUse,
|
||||
10, // Máximo 10 páginas (500 produtos)
|
||||
(currentPage, totalPages, loadedProducts) => {
|
||||
updateProgress(currentPage, totalPages, loadedProducts, 0);
|
||||
}
|
||||
);
|
||||
// Construir parâmetros da API
|
||||
const params = new URLSearchParams({
|
||||
q: query,
|
||||
country: countryToUse,
|
||||
page: "1",
|
||||
page_size: "50", // Buscar até 50 produtos por página
|
||||
});
|
||||
|
||||
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
|
||||
const searchId = saveSearch(
|
||||
@@ -163,9 +183,9 @@ function ResultadosContent() {
|
||||
detectedCountry,
|
||||
countryParam,
|
||||
filters,
|
||||
cacheOnly,
|
||||
getCachedSearch,
|
||||
saveSearch,
|
||||
updateProgress,
|
||||
setIsLoading,
|
||||
setTotalResults,
|
||||
setCacheLoading,
|
||||
@@ -180,6 +200,18 @@ function ResultadosContent() {
|
||||
}
|
||||
}, [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
|
||||
const filteredAndSortedProducts = useMemo(() => {
|
||||
let filtered = [...allProducts];
|
||||
@@ -221,6 +253,10 @@ function ResultadosContent() {
|
||||
setForceRefresh(true);
|
||||
}, [clearCache, query, detectedCountry, countryParam, filters]);
|
||||
|
||||
const handleRefreshStorageStats = useCallback(() => {
|
||||
refreshStorageStats();
|
||||
}, [refreshStorageStats]);
|
||||
|
||||
const handleSortChange = useCallback(
|
||||
(sortBy: string) => {
|
||||
updateFilters({
|
||||
@@ -288,67 +324,38 @@ function ResultadosContent() {
|
||||
{cacheState.isCached && (
|
||||
<span className="ml-2 inline-flex items-center gap-1 text-blue-600 dark:text-blue-400">
|
||||
<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>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Controles de visualização - Desktop */}
|
||||
<div className="hidden lg:flex items-center gap-3">
|
||||
<SortDropdown
|
||||
value={filters.sortBy || "relevance"}
|
||||
onValueChange={handleSortChange}
|
||||
{/* Switch Cache-Only em produção */}
|
||||
<CacheOnlySwitch />
|
||||
|
||||
{/* Barra de Pesquisa - Desktop */}
|
||||
<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>
|
||||
|
||||
{/* Filtros Mobile */}
|
||||
<div className="lg:hidden">
|
||||
{/* Mobile Controls */}
|
||||
<div className="lg:hidden flex items-center gap-2">
|
||||
<SearchBar
|
||||
initialQuery={query}
|
||||
className="flex-1"
|
||||
placeholder="Buscar..."
|
||||
/>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
@@ -366,6 +373,25 @@ function ResultadosContent() {
|
||||
onClearFilters={clearFilters}
|
||||
isLoading={loading}
|
||||
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>
|
||||
</Sheet>
|
||||
@@ -374,29 +400,6 @@ function ResultadosContent() {
|
||||
</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 */}
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
<div className="flex gap-8">
|
||||
@@ -409,6 +412,24 @@ function ResultadosContent() {
|
||||
onClearFilters={clearFilters}
|
||||
isLoading={loading}
|
||||
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>
|
||||
@@ -546,19 +567,42 @@ function ResultadosContent() {
|
||||
)}
|
||||
|
||||
{/* Informações adicionais */}
|
||||
{cacheState.isCached && (
|
||||
<div className="text-center mt-6">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Dados carregados do cache •
|
||||
<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>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="text-center mt-6">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{cacheState.isCached ? (
|
||||
<>
|
||||
Dados carregados do cache local •
|
||||
<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>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
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>
|
||||
|
||||
Reference in new issue
Block a user