fix: restore wiki to dictionary, create dynamic blog pages and backend wiki CRUD

This commit is contained in:
parsa committed 2026-06-12 23:14:21 +03:30
1 parent 945c007a79
commit dcfc4acae4
13 files changed
+328 -119

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const WIKI_TERMS = [
{
id: "green-mussel",
name: "صدف لب‌سبز (Perna Canaliculus)",
description: "این صدف بومی سواحل بکر نیوزیلند است و تنها منبع طبیعی حاوی گلیکوزآمین‌گلیکان‌ها (GAG) در غلظت بسیار بالا محسوب می‌شود.",
benefits: [
"بازسازی بافت غضروفی تخریب شده",
"خواص ضدالتهابی طبیعی برای رباط‌ها",
"تامین اسیدهای چرب امگا ۳ خاص",
]
},
{
id: "silver",
name: "نقره میکروسیلور (Microsilver)",
description: "ذرات نقره خالص با ساختار اسفنجی که به دلیل اندازه ذرات درشت، جذب خون نمی‌شوند اما اثر آنتی‌باکتریال پایداری بر سطح غشاها دارند.",
benefits: [
"مبارزه با باکتری‌های مقاوم در دهان و پوست",
"عدم آسیب به فلور طبیعی بدن",
"جایگزین ایمن برای آنتی‌بیوتیک‌های موضعی",
]
},
{
id: "colostrum",
name: "آغوز (Colostrum)",
description: "اولین شیر مادر که حاوی دوز بالایی از ایمونوگلوبولین‌ها، ویتامین‌ها و مواد معدنی برای فعال‌سازی فوری سیستم ایمنی است.",
benefits: [
"تقویت سد دفاعی روده",
"انتقال مستقیم آنتی‌بادی به نوزادان",
"تسریع نقاهت بعد از جرافی",
]
},
{
id: "peat-extract",
name: "عصاره پیت (Peat Extract)",
description: "ماده‌ای کاملا طبیعی حاصل از تجزیه گیاهان در طول هزاران سال که غنی از اسیدهای هومیک و مواد معدنی است.",
benefits: [
"جذب سموم در دستگاه گوارش",
"تنظیم فلور روده",
"بهبود اشتها و هضم"
]
}
];
async function main() {
console.log('Seeding Scientific Terms (Wiki)...');
for (const term of WIKI_TERMS) {
await prisma.scientificTerm.upsert({
where: { key: term.id },
update: {
term: term.name,
definition: term.description,
keywords: JSON.stringify(term.benefits),
wikiId: term.id,
},
create: {
key: term.id,
term: term.name,
definition: term.description,
keywords: JSON.stringify(term.benefits),
wikiId: term.id,
},
});
}
console.log('Wiki seeded successfully');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+2
View File
@@ -13,6 +13,7 @@ import { MetricsController } from './common/metrics.controller';
import { AdminModule } from './admin/admin.module';
import { HomeModule } from './home/home.module';
import { BlogsModule } from './blogs/blogs.module';
import { WikiModule } from './wiki/wiki.module';
@Module({
imports: [
@@ -31,6 +32,7 @@ import { BlogsModule } from './blogs/blogs.module';
AdminModule,
HomeModule,
BlogsModule,
WikiModule,
],
controllers: [MetricsController],
providers: [
+1
View File
@@ -0,0 +1 @@
export class CreateWikiDto {}
+4
View File
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateWikiDto } from './create-wiki.dto';
export class UpdateWikiDto extends PartialType(CreateWikiDto) {}
+1
View File
@@ -0,0 +1 @@
export class Wiki {}
+17
View File
@@ -0,0 +1,17 @@
import { Controller, Get, Param } from '@nestjs/common';
import { WikiService } from './wiki.service';
@Controller('wiki')
export class WikiController {
constructor(private readonly wikiService: WikiService) {}
@Get()
findAll() {
return this.wikiService.findAll();
}
@Get(':key')
findOne(@Param('key') key: string) {
return this.wikiService.findOneByKey(key);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { WikiService } from './wiki.service';
import { WikiController } from './wiki.controller';
@Module({
controllers: [WikiController],
providers: [WikiService],
})
export class WikiModule {}
+21
View File
@@ -0,0 +1,21 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class WikiService {
constructor(private prisma: PrismaService) {}
async findAll() {
return this.prisma.scientificTerm.findMany({
orderBy: { term: 'asc' }
});
}
async findOneByKey(key: string) {
const term = await this.prisma.scientificTerm.findUnique({
where: { key }
});
if (!term) throw new NotFoundException('Wiki term not found');
return term;
}
}
@@ -0,0 +1,123 @@
import React from "react";
import { ChevronRight, Calendar, User, Sparkles } from "lucide-react";
import Link from 'next/link';
import type { Metadata } from 'next';
async function getBlog(slug: string) {
try {
const res = await fetch(`http://localhost:4000/api/blogs/${slug}`, { next: { revalidate: 60 } });
if (!res.ok) throw new Error('Failed to fetch blog');
const b = await res.json();
return {
id: b.id,
slug: b.slug,
title: b.title,
excerpt: b.metaDescription || b.content.substring(0, 150).replace(/<[^>]+>/g, '') + '...',
image: b.imageUrl,
date: new Date(b.createdAt).toLocaleDateString('fa-IR'),
author: b.author ? `${b.author.firstName} ${b.author.lastName}` : 'نویسنده کانینا',
content: b.content
};
} catch (error) {
console.error(error);
return null;
}
}
export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
const blog = await getBlog(params.slug);
if (!blog) return { title: 'مقاله یافت نشد' };
return {
title: blog.title,
description: blog.excerpt,
};
}
export default async function BlogPostPage({ params }: { params: { slug: string } }) {
const selectedPost = await getBlog(params.slug);
if (!selectedPost) {
return (
<div className="min-h-[50vh] flex flex-col items-center justify-center font-vazir text-center" dir="rtl">
<h1 className="text-3xl font-black text-medical-gray-900 mb-4">مقاله‌ای یافت نشد</h1>
<Link href="/blog" className="text-canina-blue font-bold flex items-center gap-2">
<ChevronRight className="w-4 h-4" />
بازگشت به مجله سلامت
</Link>
</div>
);
}
return (
<div className="min-h-screen bg-medical-gray-50 pt-8 pb-20 px-4 font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">
{/* Breadcrumbs */}
<div className="flex items-center gap-2 text-[10px] font-black text-medical-gray-400 uppercase tracking-widest mb-10">
<Link href="/" className="hover:text-canina-blue transition-colors">خانه</Link>
<ChevronRight className="w-2.5 h-2.5" />
<Link href="/blog" className="hover:text-canina-blue transition-colors">مجله سلامت</Link>
<ChevronRight className="w-2.5 h-2.5" />
<span className="text-canina-blue">{selectedPost.title}</span>
</div>
<div className="grid lg:grid-cols-12 gap-12">
<div className="lg:col-span-8">
<div className="bg-white rounded-[3.5rem] border border-medical-gray-200 shadow-2xl overflow-hidden">
<div className="aspect-video w-full overflow-hidden">
<img src={selectedPost.image} alt={selectedPost.title} className="w-full h-full object-cover" />
</div>
<div className="p-12">
<div className="flex items-center gap-4 text-xs font-bold text-canina-blue mb-8">
<div className="bg-canina-blue/10 px-4 py-1.5 rounded-full uppercase tracking-widest">تحقیق بالینی</div>
<div className="flex items-center gap-1">
<Calendar className="w-4 h-4" />
{selectedPost.date}
</div>
</div>
<h1 className="text-4xl lg:text-5xl font-black text-medical-gray-900 mb-10 leading-tight">
{selectedPost.title}
</h1>
<div className="prose prose-lg max-w-none text-medical-gray-600 leading-[2] text-justify space-y-6">
<p className="font-bold text-medical-gray-900 italic text-xl border-r-4 border-canina-blue pr-6 py-2">
{selectedPost.excerpt}
</p>
<div className="whitespace-pre-line" dangerouslySetInnerHTML={{ __html: selectedPost.content }} />
</div>
<div className="mt-16 pt-10 border-t border-medical-gray-100 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-14 h-14 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-400 border-2 border-white shadow-lg">
<User className="w-8 h-8" />
</div>
<div>
<div className="font-black text-medical-gray-900 text-lg">{selectedPost.author}</div>
<div className="font-bold text-medical-gray-400">نویسنده کانینا</div>
</div>
</div>
<div className="flex gap-4">
<button className="p-4 bg-medical-gray-100 rounded-2xl hover:bg-canina-blue hover:text-white transition-all text-medical-gray-400">
<Sparkles className="w-6 h-6" />
</button>
</div>
</div>
</div>
</div>
</div>
<div className="lg:col-span-4 space-y-10">
<div className="bg-canina-blue rounded-[3rem] p-10 text-white shadow-2xl relative overflow-hidden">
<div className="absolute top-0 left-0 p-8 opacity-10">
<Sparkles className="w-20 h-20" />
</div>
<h4 className="text-2xl font-black mb-6 italic relative z-10">ارتباط با کارشناسان</h4>
<div className="space-y-6 relative z-10 text-white/90">
برای دریافت مشاوره تخصصی و انتخاب بهترین مکمل برای حیوان خانگی خود، با ما در تماس باشید.
</div>
</div>
</div>
</div>
</div>
</div>
);
}
+24 -2
View File
@@ -6,6 +6,28 @@ export const metadata: Metadata = {
description: 'آخرین مقالات، آموزش‌ها و اخبار علمی در زمینه نگهداری، تغذیه و سلامت سگ و گربه.',
};
export default function Blog() {
return <BlogPage />;
async function getBlogs() {
try {
const res = await fetch('http://localhost:4000/api/blogs', { next: { revalidate: 60 } });
if (!res.ok) throw new Error('Failed to fetch blogs');
const data = await res.json();
return data.map((b: any) => ({
id: b.id,
slug: b.slug,
title: b.title,
excerpt: b.metaDescription || b.content.substring(0, 150).replace(/<[^>]+>/g, '') + '...',
image: b.imageUrl,
date: new Date(b.createdAt).toLocaleDateString('fa-IR'),
author: b.author ? `${b.author.firstName} ${b.author.lastName}` : 'نویسنده کانینا',
content: b.content
}));
} catch (error) {
console.error(error);
return [];
}
}
export default async function Blog() {
const blogs = await getBlogs();
return <BlogPage blogs={blogs} />;
}
+5 -54
View File
@@ -1,60 +1,11 @@
import Link from 'next/link';
import IngredientWiki from "../../components/IngredientWiki";
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'دانشنامه و مقالات علمی',
description: 'مقالات تخصصی و آموزشی درباره تغذیه و سلامت حیوانات خانگی',
title: 'دانشنامه ترکیبات دارویی',
description: 'اطلاعات کامل در مورد مواد موثره، ویتامین‌ها و ترکیبات گیاهی به کار رفته در محصولات تخصصی کانینا ایران.',
};
async function getBlogs() {
try {
const res = await fetch('http://localhost:4000/api/blogs', { next: { revalidate: 60 } });
if (!res.ok) throw new Error('Failed to fetch blogs');
return res.json();
} catch (error) {
console.error(error);
return [];
}
}
export default async function WikiPage() {
const blogs = await getBlogs();
return (
<div className="bg-white py-20 px-4 font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">
<h1 className="text-4xl font-black text-medical-gray-900 mb-12 text-center">دانشنامه و مقالات علمی</h1>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
{blogs.map((blog: any) => (
<Link key={blog.id} href={`/wiki/${blog.slug}`} className="group block">
<div className="bg-medical-gray-50 rounded-[2rem] overflow-hidden border border-medical-gray-100 hover:shadow-2xl transition-all duration-300 h-full flex flex-col">
{blog.imageUrl && (
<div className="aspect-video overflow-hidden">
<img src={blog.imageUrl} alt={blog.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
</div>
)}
<div className="p-6 flex-1 flex flex-col">
<h3 className="text-xl font-black text-medical-gray-900 mb-4 group-hover:text-canina-blue transition-colors">
{blog.title}
</h3>
<div className="text-sm text-medical-gray-500 line-clamp-3 mb-6" dangerouslySetInnerHTML={{ __html: blog.content.substring(0, 150) + '...' }} />
<div className="mt-auto flex items-center justify-between text-xs font-bold text-medical-gray-400">
<span>{new Date(blog.createdAt).toLocaleDateString('fa-IR')}</span>
<span className="text-canina-blue">مطالعه مقاله &larr;</span>
</div>
</div>
</div>
</Link>
))}
{blogs.length === 0 && (
<div className="col-span-full py-20 text-center text-medical-gray-400 font-bold">
مقاله‌ای یافت نشد.
</div>
)}
</div>
</div>
</div>
);
export default function WikiPage() {
return <IngredientWiki />;
}
+26 -50
View File
@@ -5,48 +5,22 @@ import { ChevronRight, Calendar, User, ArrowLeft, Sparkles, BookOpen } from "luc
import { Product } from "../lib/data/products";
import { productService } from "../lib/services/productService";
const BLOG_POSTS = [
{
id: "p1",
title: "مزایای شگفت‌انگیز صدف لب‌سبز نیوزیلند برای مفاصل پت",
excerpt: "صدف لب‌سبز (Perna Canaliculus) تنها منبع طبیعی حاوی گلیکوزآمین‌گلیکان‌ها (GAG) در غلظت بسیار بالا محسوب می‌شود.",
image: "https://images.unsplash.com/photo-1599443015574-be5fe8a05783?auto=format&fit=crop&q=80&w=800",
date: "۲۵ اردیبهشت ۱۴۰۳",
author: "دکتر کلاوس هنینگ",
content: `
صدف لب‌سبز نیوزیلندی قلب تپنده محصولات ارتوپدی کانینا است. این صدف که منحصراً در آب‌های فوق‌العاده تمیز نیوزیلند تکثیر می‌شود، حاوی ترکیبات ضدالتهابی طبیعی است که در هیچ منبع دیگری به این غلظت یافت نمی‌شود.
چرا برای سگ‌های نژاد بزرگ حیاتی است؟
در سگ‌های نژاد بزرگ، سرعت رشد اسکلتی بسیار بالاست. اگر مفاصل و تاندون‌ها با این سرعت هماهنگ نشوند، بدشکلی‌های ماندگار ایجاد می‌شود. GAG موجود در صدف، مانند چسب بیولوژیک عمل کرده و بافت غضروفی را ترمیم می‌کند.
مکمل Canhydrox GAG با دارا بودن ۱۵٪ پودر صدف لب‌سبز خالص، استاندارد طلایی در دامپزشکی آلمان است.
`
},
{
id: "p2",
title: "چگونه سیستم ایمنی پت خود را در برابر بیماری‌های فصلی تقویت کنیم؟",
excerpt: "آغوز (Colostrum) اولین سد دفاعی طبیعت است. با ایمیون‌بوستر کانی‌نا، پت شما در برابر ویروس‌ها بیمه می‌شود.",
image: "https://images.unsplash.com/photo-1576091160550-217359f42f8c?auto=format&fit=crop&q=80&w=800",
date: "۲۰ اردیبهشت ۱۴۰۳",
author: "دکتر النا اشمیت",
content: "ایمنی بدن یک مکانیزم پیچیده است. استفاده از Immun-Booster به ویژه در دوران واکسیناسیون یا جابجایی، به بدن پت کمک می‌کند تا آنتی‌بادی‌های لازم را با سرعت بیشتری تولید کند."
},
{
id: "p3",
title: "اهمیت اسیدهای چرب امگا ۳ در درخشش پوشش مویی",
excerpt: "ریزش موی شدید در سگ و گربه معمولاً نشانه کمبود اسیدهای چرب ضروری EPA و DHA است. روغن سالمون پرس سرد راه حل نهایی است.",
image: "https://images.unsplash.com/photo-1516734212186-a967f81ad0d7?auto=format&fit=crop&q=80&w=800",
date: "۱۵ اردیبهشت ۱۴۰۳",
author: "دکتر ماری کونیگ",
content: "روغن سالمون کانی‌نا به روش پرس سرد تهیه شده تا تمامی ویتامین‌های حساس به حرارت حفظ شوند. این روغن نه تنها پوست را مرطوب نگه می‌دارد، بلکه التهابات مفصلی را نیز کاهش می‌دهد."
}
];
export interface BlogPost {
id: string;
slug: string;
title: string;
excerpt: string;
image: string;
date: string;
author: string;
content: string;
}
import { useRouter } from 'next/navigation';
export default function BlogPage() {
export default function BlogPage({ blogs = [] }: { blogs: BlogPost[] }) {
const router = useRouter();
const [selectedPost, setSelectedPost] = React.useState<typeof BLOG_POSTS[0] | null>(null);
const [selectedPost, setSelectedPost] = React.useState<BlogPost | null>(null);
const [products, setProducts] = React.useState<Product[]>([]);
React.useEffect(() => {
@@ -144,10 +118,10 @@ export default function BlogPage() {
<div className="bg-white rounded-[3rem] border border-medical-gray-200 p-10 shadow-xl">
<h4 className="text-xl font-black italic mb-6">محبوب‌ترین مقالات</h4>
<div className="space-y-6">
{BLOG_POSTS.map(p => (
{blogs.map(p => (
<div
key={p.id}
onClick={() => setSelectedPost(p)}
onClick={() => router.push(`/blog/${p.slug}`)}
className="flex items-center gap-4 cursor-pointer group"
>
<div className="w-16 h-16 rounded-2xl overflow-hidden shrink-0">
@@ -194,17 +168,18 @@ export default function BlogPage() {
</div>
{/* Featured Post */}
{blogs.length > 0 && (
<div className="mb-20">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group"
onClick={() => setSelectedPost(BLOG_POSTS[0])}
onClick={() => router.push(`/blog/${blogs[0].slug}`)}
>
<div className="lg:w-1/2 aspect-video lg:aspect-auto">
<img
src={BLOG_POSTS[0].image}
alt={BLOG_POSTS[0].title}
src={blogs[0].image}
alt={blogs[0].title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
/>
</div>
@@ -213,14 +188,14 @@ export default function BlogPage() {
<div className="bg-canina-blue/10 px-3 py-1 rounded-full uppercase tracking-widest">تخصصی</div>
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
{BLOG_POSTS[0].date}
{blogs[0].date}
</div>
</div>
<h2 className="text-3xl lg:text-4xl font-black text-medical-gray-900 mb-6 leading-tight group-hover:text-canina-blue transition-colors">
{BLOG_POSTS[0].title}
{blogs[0].title}
</h2>
<p className="text-lg text-medical-gray-500 mb-8 leading-relaxed italic">
{BLOG_POSTS[0].excerpt}
{blogs[0].excerpt}
</p>
<div className="flex items-center justify-between pt-8 border-t border-medical-gray-100">
<div className="flex items-center gap-3">
@@ -228,8 +203,8 @@ export default function BlogPage() {
<User className="w-6 h-6" />
</div>
<div className="text-sm">
<div className="font-black text-medical-gray-900">{BLOG_POSTS[0].author}</div>
<div className="font-bold text-medical-gray-400">محقق ارشد کانی‌نا</div>
<div className="font-black text-medical-gray-900">{blogs[0].author}</div>
<div className="font-bold text-medical-gray-400">نویسنده کانینا</div>
</div>
</div>
<div className="flex items-center gap-2 text-canina-blue font-black">
@@ -240,10 +215,11 @@ export default function BlogPage() {
</div>
</motion.div>
</div>
)}
{/* Post Grid */}
<div className="grid md:grid-cols-2 gap-8">
{BLOG_POSTS.slice(1).map((post, idx) => (
{blogs.slice(1).map((post, idx) => (
<motion.div
key={post.id}
initial={{ opacity: 0, y: 20 }}
@@ -251,7 +227,7 @@ export default function BlogPage() {
viewport={{ once: true }}
transition={{ delay: idx * 0.1 }}
className="bg-white rounded-[3rem] overflow-hidden border border-medical-gray-200 shadow-xl group hover:shadow-2xl transition-all cursor-pointer"
onClick={() => setSelectedPost(post)}
onClick={() => router.push(`/blog/${post.slug}`)}
>
<div className="aspect-[16/9] overflow-hidden">
<img
@@ -1,6 +1,6 @@
"use client";
import { useMemo, useState, useEffect } from "react";
import { INGREDIENTS_WIKI, Product } from "../lib/data/products";
import { Product, IngredientInfo } from "../lib/data/products";
import { motion } from "motion/react";
import { FlaskConical, CheckCircle2, ChevronRight, ChevronLeft, Beaker } from "lucide-react";
import { useSettingsStore } from "../lib/store/settingsStore";
@@ -11,24 +11,26 @@ import { useRouter } from 'next/navigation';
export default function IngredientWiki() {
const router = useRouter();
const texts = useSettingsStore(state => state.texts);
const [ingredientsWiki, setIngredientsWiki] = useState<IngredientInfo[]>([]);
const [products, setProducts] = useState<Product[]>([]);
useEffect(() => {
productService.getProducts().then(data => setProducts(data));
fetch('http://localhost:4000/api/wiki')
.then(res => res.json())
.then(data => {
const mapped = data.map((item: any) => ({
id: item.key,
name: item.term,
description: item.definition,
benefits: item.keywords ? JSON.parse(item.keywords) : []
}));
setIngredientsWiki(mapped);
})
.catch(err => console.error("Failed to fetch wiki:", err));
}, []);
const ingredientsWiki = useMemo(() => {
const jsonStr = texts['ingredients_wiki'];
if (jsonStr) {
try {
return JSON.parse(jsonStr) as typeof INGREDIENTS_WIKI;
} catch (e) {
console.error("Failed to parse ingredients_wiki from DB setting:", e);
}
}
return INGREDIENTS_WIKI;
}, [texts]);
return (
<div className="bg-white py-12 px-4 overflow-hidden font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto">