feat: add get sentiment data endpoint
This commit is contained in:
parent
0c03517965
commit
d65a0067ed
|
|
@ -0,0 +1,42 @@
|
||||||
|
import prisma from "@/lib/prisma";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
// const body = await request.json();
|
||||||
|
|
||||||
|
// const { name, brand } = body;
|
||||||
|
// if (!name || !brand) {
|
||||||
|
// return NextResponse.json(
|
||||||
|
// { error: "Missing required fields" },
|
||||||
|
// { status: 400 },
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
|
||||||
|
const products = [
|
||||||
|
{ name: "ZenBook 14", brand: "ASUS" },
|
||||||
|
{ name: "Swift 3", brand: "Acer" },
|
||||||
|
{ name: "Surface Laptop 5", brand: "Microsoft" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await prisma.product.createMany({
|
||||||
|
data: products,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
message: "Booking successful",
|
||||||
|
data: result,
|
||||||
|
},
|
||||||
|
{ status: 201 },
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Create product Error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Internal Server Error" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
import prisma from "@/lib/prisma";
|
||||||
|
import { Sentiment } from "@prisma/client";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
// const body = await request.json();
|
||||||
|
|
||||||
|
// const { name, brand } = body;
|
||||||
|
// if (!name || !brand) {
|
||||||
|
// return NextResponse.json(
|
||||||
|
// { error: "Missing required fields" },
|
||||||
|
// { status: 400 },
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
|
||||||
|
const reviews = [
|
||||||
|
{
|
||||||
|
productId: 2,
|
||||||
|
content:
|
||||||
|
"Laptop ini sangat ringan dan performanya cepat untuk kerja harian.",
|
||||||
|
keywords: ["ringan", "cepat", "kerja"],
|
||||||
|
sentiment: Sentiment.positive,
|
||||||
|
confidenceScore: 0.92,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
productId: 3,
|
||||||
|
content: "Baterainya awet, tapi harganya cukup mahal.",
|
||||||
|
keywords: ["baterai", "awet", "mahal"],
|
||||||
|
sentiment: Sentiment.neutral,
|
||||||
|
confidenceScore: 0.75,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
productId: 4,
|
||||||
|
content: "Performa kurang stabil dan sering panas.",
|
||||||
|
keywords: ["performa", "panas", "stabil"],
|
||||||
|
sentiment: Sentiment.negative,
|
||||||
|
confidenceScore: 0.88,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await prisma.review.createMany({
|
||||||
|
data: reviews,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
message: "Booking successful",
|
||||||
|
data: result,
|
||||||
|
},
|
||||||
|
{ status: 201 },
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Create product Error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Internal Server Error" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
// app/api/reviews/sentiment-stats/route.ts
|
||||||
|
import prisma from "@/lib/prisma";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const grouped = await prisma.review.groupBy({
|
||||||
|
by: ["sentiment"],
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
positive: 0,
|
||||||
|
negative: 0,
|
||||||
|
neutral: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
grouped.forEach((item) => {
|
||||||
|
if (item.sentiment === "positive") result.positive = item._count._all;
|
||||||
|
if (item.sentiment === "negative") result.negative = item._count._all;
|
||||||
|
if (item.sentiment === "neutral") result.neutral = item._count._all;
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -20,7 +20,7 @@ import { SentimentAnalyzer } from "./SentimentAnalyzer";
|
||||||
import { BrandFilter } from "./BrandFilter";
|
import { BrandFilter } from "./BrandFilter";
|
||||||
import { ReviewTable } from "./ReviewTable";
|
import { ReviewTable } from "./ReviewTable";
|
||||||
import { SentimentChart, TrendChart, WordCloud } from "@/src/utils/dImports";
|
import { SentimentChart, TrendChart, WordCloud } from "@/src/utils/dImports";
|
||||||
import { useDashboard } from "@/src/hooks/useDashboard";
|
import { useDashboards } from "@/src/hooks/useDashboard";
|
||||||
|
|
||||||
export default function DashboardClient() {
|
export default function DashboardClient() {
|
||||||
const {
|
const {
|
||||||
|
|
@ -30,10 +30,11 @@ export default function DashboardClient() {
|
||||||
neutralCount,
|
neutralCount,
|
||||||
filteredReviews,
|
filteredReviews,
|
||||||
selectedBrand,
|
selectedBrand,
|
||||||
setSelectedBrand,
|
|
||||||
loading,
|
loading,
|
||||||
modelData,
|
modelData,
|
||||||
} = useDashboard();
|
setSelectedBrand,
|
||||||
|
percentage,
|
||||||
|
} = useDashboards();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-background">
|
<div className="min-h-screen bg-background">
|
||||||
|
|
@ -71,26 +72,29 @@ export default function DashboardClient() {
|
||||||
trend={{ value: 12.5, isPositive: true }}
|
trend={{ value: 12.5, isPositive: true }}
|
||||||
delay={0}
|
delay={0}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Sentimen Positif"
|
title="Sentimen Positif"
|
||||||
value={positiveCount}
|
value={positiveCount}
|
||||||
suffix={`(${((positiveCount / totalReviews) * 100).toFixed(1)}%)`}
|
suffix={`(${percentage(positiveCount, totalReviews)}%)`}
|
||||||
icon={ThumbsUp}
|
icon={ThumbsUp}
|
||||||
variant="positive"
|
variant="positive"
|
||||||
delay={100}
|
delay={100}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Sentimen Negatif"
|
title="Sentimen Negatif"
|
||||||
value={negativeCount}
|
value={negativeCount}
|
||||||
suffix={`(${((negativeCount / totalReviews) * 100).toFixed(1)}%)`}
|
suffix={`(${percentage(negativeCount, totalReviews)}%)`}
|
||||||
icon={ThumbsDown}
|
icon={ThumbsDown}
|
||||||
variant="negative"
|
variant="negative"
|
||||||
delay={200}
|
delay={200}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Sentimen Netral"
|
title="Sentimen Netral"
|
||||||
value={neutralCount}
|
value={neutralCount}
|
||||||
suffix={`(${((neutralCount / totalReviews) * 100).toFixed(1)}%)`}
|
suffix={`(${percentage(neutralCount, totalReviews)}%)`}
|
||||||
icon={Minus}
|
icon={Minus}
|
||||||
variant="neutral"
|
variant="neutral"
|
||||||
delay={300}
|
delay={300}
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,9 @@ import Link from "next/link";
|
||||||
import { useHeader } from "@/src/hooks/useHeader";
|
import { useHeader } from "@/src/hooks/useHeader";
|
||||||
|
|
||||||
export function Header() {
|
export function Header() {
|
||||||
const { open, setOpen, session } = useHeader();
|
const { open, setOpen, session, mounted } = useHeader();
|
||||||
|
|
||||||
|
if (!mounted) return null;
|
||||||
return (
|
return (
|
||||||
<header className="border-b bg-card/50 backdrop-blur-sm sticky top-0 z-50">
|
<header className="border-b bg-card/50 backdrop-blur-sm sticky top-0 z-50">
|
||||||
<div className="container mx-auto px-4 py-4">
|
<div className="container mx-auto px-4 py-4">
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ export function ModelInfo({ data }: { data: ModelDB[] }) {
|
||||||
<SelectValue placeholder="Pilih Model" />
|
<SelectValue placeholder="Pilih Model" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|
||||||
<SelectContent className="bg-card border-border shadow-lg">
|
<SelectContent className="bg-card border-border shadow-lg" position="popper">
|
||||||
{data.map((model, index) => (
|
{data.map((model, index) => (
|
||||||
<SelectItem
|
<SelectItem
|
||||||
key={model.modelName + index}
|
key={model.modelName + index}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ export function StatCard({
|
||||||
variant = "default",
|
variant = "default",
|
||||||
delay = 0,
|
delay = 0,
|
||||||
}: StatCardProps) {
|
}: StatCardProps) {
|
||||||
const { isVisible, displayValue } = useStatCard({ title, value, icon: Icon });
|
const { isVisible, displayValue } = useStatCard({ value, delay });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|
@ -25,6 +25,7 @@ export function StatCard({
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
||||||
|
|
||||||
<div className="flex items-baseline gap-1">
|
<div className="flex items-baseline gap-1">
|
||||||
<span className="text-3xl font-bold tracking-tight">
|
<span className="text-3xl font-bold tracking-tight">
|
||||||
{displayValue.toLocaleString()}
|
{displayValue.toLocaleString()}
|
||||||
|
|
@ -35,6 +36,7 @@ export function StatCard({
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{trend && (
|
{trend && (
|
||||||
<div className="flex items-center gap-1 text-sm">
|
<div className="flex items-center gap-1 text-sm">
|
||||||
<span
|
<span
|
||||||
|
|
@ -52,6 +54,7 @@ export function StatCard({
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={cn("rounded-xl p-3", iconStyles[variant])}>
|
<div className={cn("rounded-xl p-3", iconStyles[variant])}>
|
||||||
<Icon className="h-6 w-6" />
|
<Icon className="h-6 w-6" />
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,32 +1,44 @@
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { ModelDB } from "../types";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { reviewData, sentimentDistribution } from "../app/dashboard/lib/data";
|
import { ModelDB, Review, StatCounts } from "@/src/types";
|
||||||
import { getClassificationReport } from "../app/dashboard/lib/actions";
|
import { getClassificationReport } from "../app/dashboard/lib/actions";
|
||||||
|
|
||||||
export const useDashboard = () => {
|
export const useDashboards = () => {
|
||||||
const [selectedBrand, setSelectedBrand] = useState<string | null>(null);
|
const [selectedBrand, setSelectedBrand] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [modelData, setModelData] = useState<ModelDB[]>([]);
|
const [modelData, setModelData] = useState<ModelDB[]>([]);
|
||||||
|
const [reviews, setReviews] = useState<Review[]>([]);
|
||||||
const totalReviews = sentimentDistribution.reduce(
|
const [stats, setStats] = useState<StatCounts>({
|
||||||
(sum, s) => sum + s.value,
|
totalReviews: 0,
|
||||||
0,
|
positive: 0,
|
||||||
);
|
negative: 0,
|
||||||
|
neutral: 0,
|
||||||
const positiveCount =
|
});
|
||||||
sentimentDistribution.find((s) => s.name === "Positif")?.value || 0;
|
|
||||||
const negativeCount =
|
|
||||||
sentimentDistribution.find((s) => s.name === "Negatif")?.value || 0;
|
|
||||||
const neutralCount =
|
|
||||||
sentimentDistribution.find((s) => s.name === "Netral")?.value || 0;
|
|
||||||
|
|
||||||
const filteredReviews = selectedBrand
|
|
||||||
? reviewData.filter((r) => r.brand === selectedBrand)
|
|
||||||
: reviewData;
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchData() {
|
async function fetchStats() {
|
||||||
|
setLoading(true);
|
||||||
|
const res = await fetch("/api/review/sentiment-stats");
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
const total = data.positive + data.negative + data.neutral;
|
||||||
|
|
||||||
|
setStats({
|
||||||
|
totalReviews: total ?? 0,
|
||||||
|
positive: data.positive ?? 0,
|
||||||
|
negative: data.negative ?? 0,
|
||||||
|
neutral: data.neutral ?? 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchStats();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function fetchModelData() {
|
||||||
try {
|
try {
|
||||||
const data = await getClassificationReport();
|
const data = await getClassificationReport();
|
||||||
setModelData(data);
|
setModelData(data);
|
||||||
|
|
@ -36,18 +48,29 @@ export const useDashboard = () => {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fetchData();
|
|
||||||
|
fetchModelData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const filteredReviews = useMemo(() => {
|
||||||
|
return selectedBrand
|
||||||
|
? reviews.filter((r) => r.brand === selectedBrand)
|
||||||
|
: reviews;
|
||||||
|
}, [reviews, selectedBrand]);
|
||||||
|
|
||||||
|
const percentage = (value: number, total: number) =>
|
||||||
|
total > 0 ? ((value / total) * 100).toFixed(1) : "0.0";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
totalReviews,
|
totalReviews: stats.totalReviews,
|
||||||
positiveCount,
|
positiveCount: stats.positive,
|
||||||
negativeCount,
|
negativeCount: stats.negative,
|
||||||
neutralCount,
|
neutralCount: stats.neutral,
|
||||||
filteredReviews,
|
filteredReviews,
|
||||||
selectedBrand,
|
selectedBrand,
|
||||||
loading,
|
loading,
|
||||||
modelData,
|
modelData,
|
||||||
setSelectedBrand,
|
setSelectedBrand,
|
||||||
|
percentage,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,20 @@
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
export const useHeader = () => {
|
export const useHeader = () => {
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const session = useSession();
|
const session = useSession();
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
const handleRefresh = () => {
|
const handleRefresh = () => {
|
||||||
setIsRefreshing(true);
|
setIsRefreshing(true);
|
||||||
setTimeout(() => setIsRefreshing(false), 1500);
|
setTimeout(() => setIsRefreshing(false), 1500);
|
||||||
};
|
};
|
||||||
|
|
||||||
return { open, setOpen, session };
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { open, setOpen, session, isRefreshing, handleRefresh, mounted };
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,50 +1,32 @@
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { StatCardProps } from "../types";
|
import { UseStatCardProps } from "../types";
|
||||||
|
|
||||||
export const useStatCard = ({
|
export function useStatCard({ value, delay = 0 }: UseStatCardProps) {
|
||||||
title,
|
|
||||||
value,
|
|
||||||
suffix = "",
|
|
||||||
icon: Icon,
|
|
||||||
trend,
|
|
||||||
variant = "default",
|
|
||||||
delay = 0,
|
|
||||||
}: StatCardProps) => {
|
|
||||||
const [displayValue, setDisplayValue] = useState(0);
|
|
||||||
const [isVisible, setIsVisible] = useState(false);
|
const [isVisible, setIsVisible] = useState(false);
|
||||||
|
const [displayValue, setDisplayValue] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
setIsVisible(true);
|
setIsVisible(true);
|
||||||
}, delay);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [delay]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
let start = 0;
|
||||||
if (!isVisible) return;
|
const duration = 800;
|
||||||
|
const stepTime = 16;
|
||||||
|
const increment = value / (duration / stepTime);
|
||||||
|
|
||||||
const duration = 1200;
|
const counter = setInterval(() => {
|
||||||
const steps = 40;
|
start += increment;
|
||||||
const stepValue = value / steps;
|
if (start >= value) {
|
||||||
let current = 0;
|
|
||||||
let step = 0;
|
|
||||||
|
|
||||||
const timer = setInterval(() => {
|
|
||||||
step++;
|
|
||||||
const progress = step / steps;
|
|
||||||
const eased = 1 - Math.pow(1 - progress, 3);
|
|
||||||
current = value * eased;
|
|
||||||
|
|
||||||
if (step >= steps) {
|
|
||||||
setDisplayValue(value);
|
setDisplayValue(value);
|
||||||
clearInterval(timer);
|
clearInterval(counter);
|
||||||
} else {
|
} else {
|
||||||
setDisplayValue(Math.floor(current));
|
setDisplayValue(Math.floor(start));
|
||||||
}
|
}
|
||||||
}, duration / steps);
|
}, stepTime);
|
||||||
|
}, delay);
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
return () => clearTimeout(timeout);
|
||||||
}, [value, isVisible]);
|
}, [value, delay]);
|
||||||
|
|
||||||
return { isVisible, displayValue };
|
return { isVisible, displayValue };
|
||||||
};
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { UserGender } from "@prisma/client";
|
import { Sentiment, UserGender } from "@prisma/client";
|
||||||
import { LucideIcon } from "lucide-react";
|
import { LucideIcon } from "lucide-react";
|
||||||
|
|
||||||
export interface ModelDB {
|
export interface ModelDB {
|
||||||
|
|
@ -28,12 +28,12 @@ export interface BrandFilterProps {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Review {
|
export interface Review {
|
||||||
id: string;
|
id: number;
|
||||||
product: string;
|
product: string;
|
||||||
brand: string;
|
brand: string;
|
||||||
review: string;
|
review: string;
|
||||||
rating: number;
|
rating?: number | null;
|
||||||
sentiment: "positif" | "negatif" | "netral";
|
sentiment: Sentiment;
|
||||||
date: string;
|
date: string;
|
||||||
confidence: number;
|
confidence: number;
|
||||||
}
|
}
|
||||||
|
|
@ -110,3 +110,15 @@ export interface WordCloudItemProps {
|
||||||
maxValue: number;
|
maxValue: number;
|
||||||
minValue: number;
|
minValue: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface StatCounts {
|
||||||
|
totalReviews: number;
|
||||||
|
positive: number;
|
||||||
|
negative: number;
|
||||||
|
neutral: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseStatCardProps {
|
||||||
|
value: number;
|
||||||
|
delay?: number;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue