feat: add dummy api for hub

This commit is contained in:
Sosokker 2025-03-07 02:58:45 +07:00
parent 02d219a502
commit cc96dfae92
4 changed files with 265 additions and 231 deletions

148
frontend/api/hub.ts Normal file
View File

@ -0,0 +1,148 @@
import axiosInstance from "./config";
import type { Blog } from "@/types";
// Dummy blog data used as a fallback.
const dummyBlogs: Blog[] = [
{
id: 1,
title: "Sustainable Farming Practices for Modern Agriculture",
description:
"Learn about eco-friendly farming techniques that can increase yield while preserving the environment.",
date: "2023-05-15",
author: "Emma Johnson",
topic: "Sustainability",
image: "/placeholder.svg?height=400&width=600",
readTime: "5 min read",
featured: true,
content: `<p>Sustainable farming is not just a trend; it's a necessary evolution in agricultural practices. […]</p>`,
tableOfContents: [
{ id: "importance", title: "The Importance of Sustainable Agriculture", level: 1 },
{ id: "crop-rotation", title: "Crop Rotation and Diversification", level: 1 },
{ id: "ipm", title: "Integrated Pest Management (IPM)", level: 1 },
{ id: "water-conservation", title: "Water Conservation Techniques", level: 1 },
{ id: "soil-health", title: "Soil Health Management", level: 1 },
{ id: "renewable-energy", title: "Renewable Energy Integration", level: 1 },
{ id: "conclusion", title: "Conclusion", level: 1 },
],
relatedArticles: [
{
id: 2,
title: "Optimizing Fertilizer Usage for Maximum Crop Yield",
topic: "Fertilizers",
image: "/placeholder.svg?height=200&width=300",
description: "",
date: "",
author: "",
readTime: "",
featured: false,
},
{
id: 4,
title: "Water Conservation Techniques for Drought-Prone Areas",
topic: "Sustainability",
image: "/placeholder.svg?height=200&width=300",
description: "",
date: "",
author: "",
readTime: "",
featured: false,
},
{
id: 5,
title: "Organic Pest Control Methods That Actually Work",
topic: "Organic",
image: "/placeholder.svg?height=200&width=300",
description: "",
date: "",
author: "",
readTime: "",
featured: false,
},
],
},
{
id: 2,
title: "Optimizing Fertilizer Usage for Maximum Crop Yield",
description: "Discover the perfect balance of fertilizers to maximize your harvest without wasting resources.",
date: "2023-06-02",
author: "Michael Chen",
topic: "Fertilizers",
image: "/placeholder.svg?height=400&width=600",
readTime: "7 min read",
featured: false,
},
{
id: 3,
title: "Seasonal Planting Guide: What to Grow and When",
description:
"A comprehensive guide to help you plan your planting schedule throughout the year for optimal results.",
date: "2023-06-18",
author: "Sarah Williams",
topic: "Plantation",
image: "/placeholder.svg?height=400&width=600",
readTime: "8 min read",
featured: false,
},
{
id: 4,
title: "Water Conservation Techniques for Drought-Prone Areas",
description: "Essential strategies to maintain your crops during water shortages and drought conditions.",
date: "2023-07-05",
author: "David Rodriguez",
topic: "Sustainability",
image: "/placeholder.svg?height=400&width=600",
readTime: "6 min read",
featured: false,
},
{
id: 5,
title: "Organic Pest Control Methods That Actually Work",
description: "Natural and effective ways to keep pests at bay without resorting to harmful chemicals.",
date: "2023-07-22",
author: "Lisa Thompson",
topic: "Organic",
image: "/placeholder.svg?height=400&width=600",
readTime: "9 min read",
featured: false,
},
{
id: 6,
title: "The Future of Smart Farming: IoT and Agriculture",
description: "How Internet of Things technology is revolutionizing the way we monitor and manage farms.",
date: "2023-08-10",
author: "James Wilson",
topic: "Technology",
image: "/placeholder.svg?height=400&width=600",
readTime: "10 min read",
featured: true,
},
];
/**
* Fetches a list of blog posts.
* Simulates a network delay and returns dummy data when the API endpoint is unavailable.
*/
export async function fetchBlogs(): Promise<Blog[]> {
await new Promise((resolve) => setTimeout(resolve, 1000));
try {
const response = await axiosInstance.get<Blog[]>("/api/blogs");
return response.data;
} catch (error) {
return dummyBlogs;
}
}
/**
* Fetches a single blog post by its id.
* Returns the API result if available; otherwise falls back to dummy data.
*/
export async function fetchBlogById(id: string): Promise<Blog | null> {
await new Promise((resolve) => setTimeout(resolve, 500));
try {
const response = await axiosInstance.get<Blog>(`/api/blogs/${id}`);
return response.data;
} catch (error) {
const blog = dummyBlogs.find((blog) => blog.id === Number(id));
return blog || null;
}
}

View File

@ -4,110 +4,36 @@ import { useState, useEffect } from "react";
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
import { ArrowLeft, Calendar, Clock, Share2, Bookmark, ChevronUp } from "lucide-react"; import { ArrowLeft, Calendar, Clock, Share2, Bookmark, ChevronUp } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
// Sample blog data - in a real app, you would fetch this based on the ID import { fetchBlogById } from "@/api/hub";
const blog = { import type { Blog } from "@/types";
id: 1,
title: "Sustainable Farming Practices for Modern Agriculture",
description: "Learn about eco-friendly farming techniques that can increase yield while preserving the environment.",
date: "2023-05-15",
author: "Emma Johnson",
authorRole: "Agricultural Specialist",
authorImage: "/placeholder.svg?height=100&width=100",
topic: "Sustainability",
image: "/placeholder.svg?height=600&width=1200",
readTime: "5 min read",
content: `
<p>Sustainable farming is not just a trend; it's a necessary evolution in agricultural practices to ensure food security for future generations while minimizing environmental impact. This article explores practical, eco-friendly farming techniques that can increase yield while preserving our precious natural resources.</p>
<h2>The Importance of Sustainable Agriculture</h2>
<p>As the global population continues to grow, the demand for food increases, putting pressure on farmers to produce more. However, conventional farming methods often lead to soil degradation, water pollution, and biodiversity loss. Sustainable farming addresses these challenges by working with natural processes rather than against them.</p>
<p>Key benefits of sustainable farming include:</p>
<ul>
<li>Reduced environmental impact</li>
<li>Improved soil health and fertility</li>
<li>Conservation of water resources</li>
<li>Enhanced biodiversity</li>
<li>Long-term economic viability</li>
</ul>
<h2>Crop Rotation and Diversification</h2>
<p>One of the simplest yet most effective sustainable farming practices is crop rotation. By alternating different crops in the same area across growing seasons, farmers can break pest cycles, improve soil structure, and enhance nutrient availability.</p>
<p>Diversification goes hand in hand with rotation. Growing a variety of crops rather than practicing monoculture helps spread risk, improves ecological balance, and can provide multiple income streams for farmers.</p>
<h2>Integrated Pest Management (IPM)</h2>
<p>IPM is an ecosystem-based approach that focuses on long-term prevention of pests through a combination of techniques such as biological control, habitat manipulation, and resistant crop varieties. Chemical pesticides are used only when monitoring indicates they are needed according to established guidelines.</p>
<p>This approach reduces pesticide use, minimizes environmental impact, and helps prevent the development of pesticide-resistant pests.</p>
<h2>Water Conservation Techniques</h2>
<p>Water is a precious resource, and sustainable farming emphasizes its efficient use. Drip irrigation systems deliver water directly to plant roots, reducing evaporation and runoff. Rainwater harvesting systems capture and store rainfall for later use during dry periods.</p>
<p>Additionally, selecting drought-resistant crop varieties and implementing proper soil management practices can significantly reduce water requirements.</p>
<h2>Soil Health Management</h2>
<p>Healthy soil is the foundation of sustainable agriculture. Practices such as minimal tillage, cover cropping, and the application of organic matter help maintain soil structure, prevent erosion, and enhance fertility.</p>
<p>Composting farm waste and applying it back to the fields creates a closed-loop system that reduces the need for synthetic fertilizers while improving soil quality.</p>
<h2>Renewable Energy Integration</h2>
<p>Modern sustainable farms are increasingly incorporating renewable energy sources such as solar panels, wind turbines, and biogas digesters. These technologies reduce dependence on fossil fuels, lower operational costs, and decrease the carbon footprint of agricultural operations.</p>
<h2>Conclusion</h2>
<p>Transitioning to sustainable farming practices requires knowledge, planning, and sometimes initial investment. However, the long-term benefits for farmers, communities, and the environment make it a worthwhile endeavor.</p>
<p>By adopting these eco-friendly techniques, farmers can ensure the viability of their operations while contributing to a healthier planet for future generations.</p>
`,
tableOfContents: [
{ id: "importance", title: "The Importance of Sustainable Agriculture", level: 1 },
{ id: "crop-rotation", title: "Crop Rotation and Diversification", level: 1 },
{ id: "ipm", title: "Integrated Pest Management (IPM)", level: 1 },
{ id: "water-conservation", title: "Water Conservation Techniques", level: 1 },
{ id: "soil-health", title: "Soil Health Management", level: 1 },
{ id: "renewable-energy", title: "Renewable Energy Integration", level: 1 },
{ id: "conclusion", title: "Conclusion", level: 1 },
],
relatedArticles: [
{
id: 2,
title: "Optimizing Fertilizer Usage for Maximum Crop Yield",
topic: "Fertilizers",
image: "/placeholder.svg?height=200&width=300",
},
{
id: 4,
title: "Water Conservation Techniques for Drought-Prone Areas",
topic: "Sustainability",
image: "/placeholder.svg?height=200&width=300",
},
{
id: 5,
title: "Organic Pest Control Methods That Actually Work",
topic: "Organic",
image: "/placeholder.svg?height=200&width=300",
},
],
};
export default function BlogPage() { export default function BlogPage() {
// Get the dynamic route parameter.
const params = useParams();
const blogId = params.id as string;
// Fetch the blog based on its id.
const {
data: blog,
isLoading,
isError,
} = useQuery<Blog | null>({
queryKey: ["blog", blogId],
queryFn: () => fetchBlogById(blogId),
staleTime: 60 * 1000,
});
// Local state for the "scroll to top" button.
const [showScrollTop, setShowScrollTop] = useState(false); const [showScrollTop, setShowScrollTop] = useState(false);
// Handle scroll to show/hide scroll to top button
useEffect(() => { useEffect(() => {
const handleScroll = () => { const handleScroll = () => {
setShowScrollTop(window.scrollY > 300); setShowScrollTop(window.scrollY > 300);
@ -117,12 +43,10 @@ export default function BlogPage() {
return () => window.removeEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll);
}, []); }, []);
// Scroll to top function
const scrollToTop = () => { const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" }); window.scrollTo({ top: 0, behavior: "smooth" });
}; };
// Scroll to section function
const scrollToSection = (id: string) => { const scrollToSection = (id: string) => {
const element = document.getElementById(id); const element = document.getElementById(id);
if (element) { if (element) {
@ -130,6 +54,14 @@ export default function BlogPage() {
} }
}; };
if (isLoading) {
return <div className="flex min-h-screen bg-background items-center justify-center">Loading...</div>;
}
if (isError || !blog) {
return <div className="flex min-h-screen bg-background items-center justify-center">Error loading blog.</div>;
}
return ( return (
<div className="min-h-screen bg-background"> <div className="min-h-screen bg-background">
{/* Header */} {/* Header */}
@ -175,15 +107,10 @@ export default function BlogPage() {
<div className="grid lg:grid-cols-[1fr_300px] gap-10 max-w-6xl mx-auto"> <div className="grid lg:grid-cols-[1fr_300px] gap-10 max-w-6xl mx-auto">
{/* Article content */} {/* Article content */}
<div> <div>
{/* Topic badge */}
<div className="mb-4"> <div className="mb-4">
<Badge className="rounded-full">{blog.topic}</Badge> <Badge className="rounded-full">{blog.topic}</Badge>
</div> </div>
{/* Article title */}
<h1 className="text-3xl md:text-4xl lg:text-5xl font-bold tracking-tight mb-4">{blog.title}</h1> <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold tracking-tight mb-4">{blog.title}</h1>
{/* Article meta */}
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-6"> <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-6">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Calendar className="h-4 w-4" /> <Calendar className="h-4 w-4" />
@ -195,30 +122,11 @@ export default function BlogPage() {
</div> </div>
<span>By {blog.author}</span> <span>By {blog.author}</span>
</div> </div>
{/* Featured image */}
<div className="relative h-[300px] md:h-[400px] mb-8 rounded-lg overflow-hidden"> <div className="relative h-[300px] md:h-[400px] mb-8 rounded-lg overflow-hidden">
<Image src={blog.image || "/placeholder.svg"} alt={blog.title} fill className="object-cover" /> <Image src={blog.image || "/placeholder.svg"} alt={blog.title} fill className="object-cover" />
</div> </div>
{/* Article description */}
<p className="text-lg md:text-xl text-muted-foreground mb-8">{blog.description}</p> <p className="text-lg md:text-xl text-muted-foreground mb-8">{blog.description}</p>
<div className="prose prose-green max-w-none" dangerouslySetInnerHTML={{ __html: blog.content || "" }} />
{/* Article content */}
<div className="prose prose-green max-w-none" dangerouslySetInnerHTML={{ __html: blog.content }} />
{/* Author bio */}
<div className="mt-12 p-6 bg-muted rounded-lg">
<div className="flex items-center gap-4">
<div className="relative w-16 h-16 rounded-full overflow-hidden">
<Image src={blog.authorImage || "/placeholder.svg"} alt={blog.author} fill className="object-cover" />
</div>
<div>
<h3 className="font-semibold">{blog.author}</h3>
<p className="text-sm text-muted-foreground">{blog.authorRole}</p>
</div>
</div>
</div>
</div> </div>
{/* Sidebar */} {/* Sidebar */}
@ -231,12 +139,13 @@ export default function BlogPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<nav className="space-y-2"> <nav className="space-y-2">
{blog.tableOfContents.map((item) => ( {blog.tableOfContents?.map((item) => (
<button <button
key={item.id} key={item.id}
onClick={() => scrollToSection(item.id)} onClick={() => scrollToSection(item.id)}
className={`text-left w-full px-2 py-1 text-sm rounded-md hover:bg-muted transition-colors className={`text-left w-full px-2 py-1 text-sm rounded-md hover:bg-muted transition-colors ${
${item.level > 1 ? "ml-4" : ""}`}> item.level > 1 ? "ml-4" : ""
}`}>
{item.title} {item.title}
</button> </button>
))} ))}
@ -245,6 +154,7 @@ export default function BlogPage() {
</Card> </Card>
{/* Related articles */} {/* Related articles */}
{blog.relatedArticles && (
<Card className="mt-8"> <Card className="mt-8">
<CardHeader> <CardHeader>
<CardTitle>Related Articles</CardTitle> <CardTitle>Related Articles</CardTitle>
@ -276,6 +186,7 @@ export default function BlogPage() {
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
)}
</div> </div>
</div> </div>
</div> </div>

View File

@ -4,6 +4,7 @@ import { useState } from "react";
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
import { CalendarIcon, ChevronRight, Leaf, Search } from "lucide-react"; import { CalendarIcon, ChevronRight, Leaf, Search } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@ -11,86 +12,36 @@ import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
// Sample blog data import { fetchBlogs } from "@/api/hub";
const blogs = [ import type { Blog } from "@/types";
{
id: 1,
title: "Sustainable Farming Practices for Modern Agriculture",
description:
"Learn about eco-friendly farming techniques that can increase yield while preserving the environment.",
date: "2023-05-15",
author: "Emma Johnson",
topic: "Sustainability",
image: "/placeholder.svg?height=400&width=600",
readTime: "5 min read",
featured: true,
},
{
id: 2,
title: "Optimizing Fertilizer Usage for Maximum Crop Yield",
description: "Discover the perfect balance of fertilizers to maximize your harvest without wasting resources.",
date: "2023-06-02",
author: "Michael Chen",
topic: "Fertilizers",
image: "/placeholder.svg?height=400&width=600",
readTime: "7 min read",
featured: false,
},
{
id: 3,
title: "Seasonal Planting Guide: What to Grow and When",
description:
"A comprehensive guide to help you plan your planting schedule throughout the year for optimal results.",
date: "2023-06-18",
author: "Sarah Williams",
topic: "Plantation",
image: "/placeholder.svg?height=400&width=600",
readTime: "8 min read",
featured: false,
},
{
id: 4,
title: "Water Conservation Techniques for Drought-Prone Areas",
description: "Essential strategies to maintain your crops during water shortages and drought conditions.",
date: "2023-07-05",
author: "David Rodriguez",
topic: "Sustainability",
image: "/placeholder.svg?height=400&width=600",
readTime: "6 min read",
featured: false,
},
{
id: 5,
title: "Organic Pest Control Methods That Actually Work",
description: "Natural and effective ways to keep pests at bay without resorting to harmful chemicals.",
date: "2023-07-22",
author: "Lisa Thompson",
topic: "Organic",
image: "/placeholder.svg?height=400&width=600",
readTime: "9 min read",
featured: false,
},
{
id: 6,
title: "The Future of Smart Farming: IoT and Agriculture",
description: "How Internet of Things technology is revolutionizing the way we monitor and manage farms.",
date: "2023-08-10",
author: "James Wilson",
topic: "Technology",
image: "/placeholder.svg?height=400&width=600",
readTime: "10 min read",
featured: true,
},
];
// Extract unique topics from blogs
const topics = ["All", ...new Set(blogs.map((blog) => blog.topic))];
export default function KnowledgeHubPage() { export default function KnowledgeHubPage() {
const [selectedTopic, setSelectedTopic] = useState("All"); const [selectedTopic, setSelectedTopic] = useState("All");
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
// Filter blogs based on selected topic and search query // Fetch blogs using react-query.
const {
data: blogs,
isLoading,
isError,
} = useQuery<Blog[]>({
queryKey: ["blogs"],
queryFn: fetchBlogs,
staleTime: 60 * 1000,
});
if (isLoading) {
return <div className="flex min-h-screen bg-background items-center justify-center">Loading...</div>;
}
if (isError || !blogs) {
return <div className="flex min-h-screen bg-background items-center justify-center">Error loading blogs.</div>;
}
// Derive the list of topics from the fetched blogs.
const topics = ["All", ...new Set(blogs.map((blog) => blog.topic))];
// Filter blogs based on selected topic and search query.
const filteredBlogs = blogs.filter((blog) => { const filteredBlogs = blogs.filter((blog) => {
const matchesTopic = selectedTopic === "All" || blog.topic === selectedTopic; const matchesTopic = selectedTopic === "All" || blog.topic === selectedTopic;
const matchesSearch = const matchesSearch =
@ -104,7 +55,6 @@ export default function KnowledgeHubPage() {
return ( return (
<div className="flex min-h-screen bg-background"> <div className="flex min-h-screen bg-background">
{/* Main content */}
<div className="flex-1 flex flex-col"> <div className="flex-1 flex flex-col">
<main className="flex-1 p-6 md:p-10"> <main className="flex-1 p-6 md:p-10">
<div className="max-w-7xl mx-auto"> <div className="max-w-7xl mx-auto">
@ -156,7 +106,7 @@ export default function KnowledgeHubPage() {
</div> </div>
<CardFooter className="p-4 flex justify-between items-center"> <CardFooter className="p-4 flex justify-between items-center">
<div className="text-sm text-muted-foreground">By {blog.author}</div> <div className="text-sm text-muted-foreground">By {blog.author}</div>
<Link href={`/blog/${blog.id}`}> <Link href={`/hub/${blog.id}`}>
<Button variant="ghost" size="sm" className="gap-1"> <Button variant="ghost" size="sm" className="gap-1">
Read more <ChevronRight className="h-4 w-4" /> Read more <ChevronRight className="h-4 w-4" />
</Button> </Button>

View File

@ -71,3 +71,28 @@ export type InventoryItem = {
}; };
export type CreateInventoryItemInput = Omit<InventoryItem, "id" | "lastUpdated" | "status">; export type CreateInventoryItemInput = Omit<InventoryItem, "id" | "lastUpdated" | "status">;
export interface Blog {
id: number;
title: string;
description: string;
date: string;
author: string;
topic: string;
image: string;
readTime: string;
featured: boolean;
content?: string;
tableOfContents?: { id: string; title: string; level: number }[];
relatedArticles?: {
id: number;
title: string;
topic: string;
image: string;
description?: string;
date?: string;
author?: string;
readTime?: string;
featured?: boolean;
}[];
}