This commit is contained in:
longdayi 2025-02-27 08:00:04 +08:00
commit 313f545e08
54 changed files with 1072 additions and 640 deletions

View File

@ -32,7 +32,7 @@ export class AuthService {
return { isValid: false, error: FileValidationErrorType.INVALID_URI }; return { isValid: false, error: FileValidationErrorType.INVALID_URI };
} }
const fileId = extractFileIdFromNginxUrl(params.originalUri); const fileId = extractFileIdFromNginxUrl(params.originalUri);
console.log(params.originalUri, fileId); // console.log(params.originalUri, fileId);
const resource = await db.resource.findFirst({ where: { fileId } }); const resource = await db.resource.findFirst({ where: { fileId } });
// 资源验证 // 资源验证

View File

@ -108,15 +108,12 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
return await db.$transaction(async (tx) => { return await db.$transaction(async (tx) => {
const courseParams = { ...params, tx }; const courseParams = { ...params, tx };
// Create the course first // Create the course first
console.log(courseParams?.staff?.id);
console.log('courseDetail', courseDetail);
const createdCourse = await this.create(courseDetail, courseParams); const createdCourse = await this.create(courseDetail, courseParams);
// If sections are provided, create them // If sections are provided, create them
return createdCourse; return createdCourse;
}); });
} }
// If transaction is provided, use it directly // If transaction is provided, use it directly
console.log('courseDetail', courseDetail);
const createdCourse = await this.create(courseDetail, params); const createdCourse = await this.create(courseDetail, params);
// If sections are provided, create them // If sections are provided, create them
return createdCourse; return createdCourse;
@ -160,25 +157,13 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
await this.setPerms(result, staff); await this.setPerms(result, staff);
await setCourseInfo({ data: result }); await setCourseInfo({ data: result });
} }
// console.log(result);
return result; return result;
}, },
); );
return transDto; return transDto;
} }
// async findMany(args: Prisma.PostFindManyArgs, staff?: UserProfile) {
// if (!args.where) args.where = {};
// args.where.OR = await this.preFilter(args.where.OR, staff);
// return this.wrapResult(super.findMany(args), async (result) => {
// await Promise.all(
// result.map(async (item) => {
// await setPostRelation({ data: item, staff });
// await this.setPerms(item, staff);
// }),
// );
// return { ...result };
// });
// }
async findManyWithCursor(args: Prisma.PostFindManyArgs, staff?: UserProfile) { async findManyWithCursor(args: Prisma.PostFindManyArgs, staff?: UserProfile) {
if (!args.where) args.where = {}; if (!args.where) args.where = {};
args.where.OR = await this.preFilter(args.where.OR, staff); args.where.OR = await this.preFilter(args.where.OR, staff);
@ -255,6 +240,7 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
// 批量执行更新 // 批量执行更新
return updates.length > 0 ? await db.$transaction(updates) : []; return updates.length > 0 ? await db.$transaction(updates) : [];
} }
protected async setPerms(data: Post, staff?: UserProfile) { protected async setPerms(data: Post, staff?: UserProfile) {
if (!staff) return; if (!staff) return;
const perms: ResPerm = { const perms: ResPerm = {
@ -306,37 +292,37 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
staff?.id && { staff?.id && {
authorId: staff.id, authorId: staff.id,
}, },
staff?.id && { // staff?.id && {
watchableStaffs: { // watchableStaffs: {
some: { // some: {
id: staff.id, // id: staff.id,
}, // },
}, // },
}, // },
deptId && { // deptId && {
watchableDepts: { // watchableDepts: {
some: { // some: {
id: { // id: {
in: parentDeptIds, // in: parentDeptIds,
}, // },
}, // },
}, // },
}, // },
{ // {
AND: [ // AND: [
{ // {
watchableStaffs: { // watchableStaffs: {
none: {}, // 匹配 watchableStaffs 为空 // none: {}, // 匹配 watchableStaffs 为空
}, // },
}, // },
{ // {
watchableDepts: { // watchableDepts: {
none: {}, // 匹配 watchableDepts 为空 // none: {}, // 匹配 watchableDepts 为空
}, // },
}, // },
], // ],
}, // },
].filter(Boolean); ].filter(Boolean);
if (orCondition?.length > 0) return orCondition; if (orCondition?.length > 0) return orCondition;

View File

@ -1,6 +1,7 @@
import { import {
db, db,
EnrollmentStatus, EnrollmentStatus,
Lecture,
Post, Post,
PostType, PostType,
SectionDto, SectionDto,
@ -127,7 +128,6 @@ export async function updateCourseEnrollmentStats(courseId: string) {
export async function setCourseInfo({ data }: { data: Post }) { export async function setCourseInfo({ data }: { data: Post }) {
// await db.term // await db.term
if (data?.type === PostType.COURSE) { if (data?.type === PostType.COURSE) {
const ancestries = await db.postAncestry.findMany({ const ancestries = await db.postAncestry.findMany({
where: { where: {
@ -144,29 +144,45 @@ export async function setCourseInfo({ data }: { data: Post }) {
}, },
}); });
const descendants = ancestries.map((ancestry) => ancestry.descendant); const descendants = ancestries.map((ancestry) => ancestry.descendant);
const sections: SectionDto[] = descendants const sections: SectionDto[] = (
.filter((descendant) => { descendants.filter((descendant) => {
return ( return (
descendant.type === PostType.SECTION && descendant.type === PostType.SECTION &&
descendant.parentId === data.id descendant.parentId === data.id
); );
}) }) as any
.map((section) => ({ ).map((section) => ({
...section, ...section,
lectures: [], lectures: [],
})); }));
const lectures = descendants.filter((descendant) => { const lectures = descendants.filter((descendant) => {
return ( return (
descendant.type === PostType.LECTURE && descendant.type === PostType.LECTURE &&
sections.map((section) => section.id).includes(descendant.parentId) sections.map((section) => section.id).includes(descendant.parentId)
); );
}); });
const lectureCount = lectures?.length || 0; const lectureCount = lectures?.length || 0;
sections.forEach((section) => { sections.forEach((section) => {
section.lectures = lectures.filter( section.lectures = lectures.filter(
(lecture) => lecture.parentId === section.id, (lecture) => lecture.parentId === section.id,
); ) as any as Lecture[];
}); });
Object.assign(data, { sections, lectureCount });
const students = await db.staff.findMany({
where: {
learningPosts: {
some: {
id: data.id,
},
},
},
select: {
id: true,
},
});
const studentIds = (students || []).map((student) => student?.id);
Object.assign(data, { sections, lectureCount, studentIds });
} }
} }

View File

@ -3,7 +3,6 @@ import {
BaseSetting, BaseSetting,
db, db,
PostType, PostType,
TaxonomySlug,
VisitType, VisitType,
} from '@nice/common'; } from '@nice/common';
export async function updateTotalCourseViewCount(type: VisitType) { export async function updateTotalCourseViewCount(type: VisitType) {
@ -24,7 +23,7 @@ export async function updateTotalCourseViewCount(type: VisitType) {
views: true, views: true,
}, },
where: { where: {
postId: { in: courseIds }, postId: { in: posts.map((post) => post.id) },
type: type, type: type,
}, },
}); });
@ -65,8 +64,50 @@ export async function updateTotalCourseViewCount(type: VisitType) {
export async function updatePostViewCount(id: string, type: VisitType) { export async function updatePostViewCount(id: string, type: VisitType) {
const post = await db.post.findFirst({ const post = await db.post.findFirst({
where: { id }, where: { id },
select: { id: true, meta: true }, select: { id: true, meta: true, type: true },
}); });
const metaFieldMap = {
[VisitType.READED]: 'views',
[VisitType.LIKE]: 'likes',
[VisitType.HATE]: 'hates',
};
if (post?.type === PostType.LECTURE) {
const course = await db.postAncestry.findFirst({
where: {
descendantId: post?.id,
ancestor: {
type: PostType.COURSE,
},
},
select: { id: true },
});
const lectures = await db.postAncestry.findMany({
where: { ancestorId: course.id, descendant: { type: PostType.LECTURE } },
select: {
id: true,
},
});
const courseViews = await db.visit.aggregate({
_sum: {
views: true,
},
where: {
postId: {
in: [course.id, ...lectures.map((lecture) => lecture.id)],
},
type: type,
},
});
await db.post.update({
where: { id: course.id },
data: {
meta: {
...((post?.meta as any) || {}),
[metaFieldMap[type]]: courseViews._sum.views || 0,
},
},
});
}
const totalViews = await db.visit.aggregate({ const totalViews = await db.visit.aggregate({
_sum: { _sum: {
views: true, views: true,
@ -76,42 +117,13 @@ export async function updatePostViewCount(id: string, type: VisitType) {
type: type, type: type,
}, },
}); });
if (type === VisitType.READED) { await db.post.update({
await db.post.update({ where: { id },
where: { data: {
id: id, meta: {
...((post?.meta as any) || {}),
[metaFieldMap[type]]: totalViews._sum.views || 0,
}, },
data: { },
meta: { });
...((post?.meta as any) || {}),
views: totalViews._sum.views || 0,
}, // Use 0 if no visits exist
},
});
console.log('readed');
} else if (type === VisitType.LIKE) {
await db.post.update({
where: {
id: id,
},
data: {
meta: {
...((post?.meta as any) || {}),
likes: totalViews._sum.views || 0, // Use 0 if no visits exist
},
},
});
} else if (type === VisitType.HATE) {
await db.post.update({
where: {
id: id,
},
data: {
meta: {
...((post?.meta as any) || {}),
hates: totalViews._sum.views || 0, // Use 0 if no visits exist
},
},
});
}
} }

View File

@ -10,7 +10,7 @@ const pipeline = new ResourceProcessingPipeline()
.addProcessor(new VideoProcessor()); .addProcessor(new VideoProcessor());
export default async function processJob(job: Job<any, any, QueueJobType>) { export default async function processJob(job: Job<any, any, QueueJobType>) {
if (job.name === QueueJobType.FILE_PROCESS) { if (job.name === QueueJobType.FILE_PROCESS) {
console.log('job', job); // console.log('job', job);
const { resource } = job.data; const { resource } = job.data;
if (!resource) { if (!resource) {
throw new Error('No resource provided in job data'); throw new Error('No resource provided in job data');

View File

@ -89,8 +89,8 @@ export class TusService implements OnModuleInit {
upload: Upload, upload: Upload,
) { ) {
try { try {
console.log('upload.id', upload.id); // console.log('upload.id', upload.id);
console.log('fileId', this.getFileId(upload.id)); // console.log('fileId', this.getFileId(upload.id));
const resource = await this.resourceService.update({ const resource = await this.resourceService.update({
where: { fileId: this.getFileId(upload.id) }, where: { fileId: this.getFileId(upload.id) },
data: { status: ResourceStatus.UPLOADED }, data: { status: ResourceStatus.UPLOADED },

View File

@ -1,7 +1,7 @@
import { Card, Rate, Tag, Typography, Button } from "antd"; import { Card, Tag, Typography, Button } from "antd";
import { import {
UserOutlined, BookOutlined,
ClockCircleOutlined, EyeOutlined,
PlayCircleOutlined, PlayCircleOutlined,
TeamOutlined, TeamOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
@ -10,22 +10,25 @@ import { useNavigate } from "react-router-dom";
interface CourseCardProps { interface CourseCardProps {
course: CourseDto; course: CourseDto;
edit?: boolean;
} }
const { Title, Text } = Typography; const { Title, Text } = Typography;
export default function CourseCard({ course }: CourseCardProps) { export default function CourseCard({ course, edit = false }: CourseCardProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const handleClick = (course: CourseDto) => { const handleClick = (course: CourseDto) => {
navigate(`/course/${course.id}/detail`); if (!edit) {
window.scrollTo({top: 0,behavior: "smooth",}) navigate(`/course/${course.id}/detail`);
} else {
navigate(`/course/${course.id}/editor`);
}
window.scrollTo({ top: 0, behavior: "smooth" });
}; };
return ( return (
<Card <Card
onClick={() => handleClick(course)} onClick={() => handleClick(course)}
key={course.id} key={course.id}
hoverable hoverable
className="group overflow-hidden rounded-2xl border border-gray-200 bg-white className="group overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2"
shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-2"
cover={ cover={
<div className="relative h-56 bg-gradient-to-br from-gray-900 to-gray-800 overflow-hidden"> <div className="relative h-56 bg-gradient-to-br from-gray-900 to-gray-800 overflow-hidden">
<div <div
@ -39,39 +42,42 @@ export default function CourseCard({ course }: CourseCardProps) {
<PlayCircleOutlined className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-6xl text-white/90 opacity-0 group-hover:opacity-100 transition-all duration-300" /> <PlayCircleOutlined className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-6xl text-white/90 opacity-0 group-hover:opacity-100 transition-all duration-300" />
</div> </div>
}> }>
<div className="px-4"> <div className="px-4 ">
<div className="flex gap-2 mb-4"> <div className="overflow-hidden hover:overflow-auto">
{course?.terms?.map((term) => { <div className="flex gap-2 h-7 mb-4 whiteSpace-nowrap">
return ( {course?.terms?.map((term) => {
<Tag return (
key={term.id} <>
// color={term.taxonomy.slug===TaxonomySlug.CATEGORY? "blue" : "green"} <Tag
color={ key={term.id}
term?.taxonomy?.slug === color={
TaxonomySlug.CATEGORY term?.taxonomy?.slug ===
? "blue" TaxonomySlug.CATEGORY
: term?.taxonomy?.slug === ? "blue"
TaxonomySlug.LEVEL : term?.taxonomy?.slug ===
? "green" TaxonomySlug.LEVEL
: "orange" ? "green"
} : "orange"
className="px-3 py-1 rounded-full bg-blue-100 text-blue-600 border-0"> }
{term.name} className="px-3 py-1 rounded-full bg-blue-100 text-blue-600 border-0 ">
</Tag> {term.name}
); </Tag>
})} </>
);
})}
</div>
</div> </div>
<Title <Title
level={4} level={4}
className="mb-4 line-clamp-2 font-bold leading-snug text-gray-800 hover:text-blue-600 transition-colors duration-300 group-hover:scale-[1.02] transform origin-left"> className="mb-4 mt-4 line-clamp-2 font-bold leading-snug text-gray-800 hover:text-blue-600 transition-colors duration-300 group-hover:scale-[1.02] transform origin-left">
<button> {course.title}</button> <button> {course.title}</button>
</Title> </Title>
<div className="flex items-center mb-4 p-2 rounded-lg transition-all duration-300 hover:bg-blue-50 group"> <div className="flex items-center mb-4 rounded-lg transition-all duration-300 hover:bg-blue-50 group">
<TeamOutlined className="text-blue-500 text-lg transform group-hover:scale-110 transition-transform duration-300" /> <TeamOutlined className="text-blue-500 text-lg transform group-hover:scale-110 transition-transform duration-300" />
<div className="ml-2 flex items-center flex-grow"> <div className="ml-2 flex items-center flex-grow">
<Text className="font-medium text-blue-500 hover:text-blue-600 transition-colors duration-300 truncate max-w-[120px]"> <Text className="font-medium text-blue-500 transition-colors duration-300 truncate max-w-[120px]">
{course?.depts?.length > 1 {course?.depts?.length > 1
? `${course.depts[0].name}` ? `${course.depts[0].name}`
: course?.depts?.[0]?.name} : course?.depts?.[0]?.name}
@ -79,10 +85,15 @@ export default function CourseCard({ course }: CourseCardProps) {
{/* {course?.depts?.map((dept)=>{return dept.name})} */} {/* {course?.depts?.map((dept)=>{return dept.name})} */}
</Text> </Text>
</div> </div>
<span className="text-xs font-medium text-gray-500"> </div>
{course?.meta?.views <div className="flex items-center gap-2">
? `观看次数 ${course?.meta?.views}` <span className="text-xs font-medium text-gray-500 flex items-center">
: null} <EyeOutlined />
{`观看次数 ${course?.meta?.views || 0}`}
</span>
<span className="text-xs font-medium text-gray-500 flex items-center">
<BookOutlined />
{`学习人数 ${course?.studentIds?.length || 0}`}
</span> </span>
</div> </div>
<div className="pt-4 border-t border-gray-100 text-center"> <div className="pt-4 border-t border-gray-100 text-center">
@ -91,7 +102,7 @@ export default function CourseCard({ course }: CourseCardProps) {
size="large" size="large"
className="w-full shadow-[0_8px_20px_-6px_rgba(59,130,246,0.5)] hover:shadow-[0_12px_24px_-6px_rgba(59,130,246,0.6)] className="w-full shadow-[0_8px_20px_-6px_rgba(59,130,246,0.5)] hover:shadow-[0_12px_24px_-6px_rgba(59,130,246,0.6)]
transform hover:translate-y-[-2px] transition-all duration-500 ease-out"> transform hover:translate-y-[-2px] transition-all duration-500 ease-out">
{edit ? "进行编辑" : "立即学习"}
</Button> </Button>
</div> </div>
</div> </div>

View File

@ -19,7 +19,7 @@ export default function FilterSection() {
}); });
}; };
return ( return (
<div className="bg-white p-6 rounded-lg shadow-sm space-y-6 h-full"> <div className="bg-white z-0 p-6 rounded-lg mt-4 shadow-sm w-1/6 space-y-6 h-[820px] fixed overscroll-contain overflow-x-hidden">
{taxonomies?.map((tax, index) => { {taxonomies?.map((tax, index) => {
const items = Object.entries(selectedTerms).find( const items = Object.entries(selectedTerms).find(
([key, items]) => key === tax.slug ([key, items]) => key === tax.slug
@ -32,7 +32,7 @@ export default function FilterSection() {
<TermParentSelector <TermParentSelector
value={items} value={items}
slug = {tax?.slug} slug = {tax?.slug}
className="w-70 max-h-[500px] overscroll-contain overflow-x-hidden" className="w-70 max-h-[400px] overscroll-contain overflow-x-hidden"
onChange={(selected) => onChange={(selected) =>
handleTermChange( handleTermChange(
tax?.slug, tax?.slug,

View File

@ -43,7 +43,7 @@ const CategorySection = () => {
return ( return (
<section className="py-8 relative overflow-hidden"> <section className="py-8 relative overflow-hidden">
<div className="max-w-screen-2xl mx-auto px-4 relative"> <div className="max-w-screen-2xl mx-auto px-4 relative">
<div className="text-center mb-24"> <div className="text-center mb-12">
<Title <Title
level={2} level={2}
className="font-bold text-5xl mb-6 bg-gradient-to-r from-gray-900 via-gray-700 to-gray-800 bg-clip-text text-transparent motion-safe:animate-gradient-x"> className="font-bold text-5xl mb-6 bg-gradient-to-r from-gray-900 via-gray-700 to-gray-800 bg-clip-text text-transparent motion-safe:animate-gradient-x">

View File

@ -3,8 +3,9 @@ import { Typography, Skeleton } from "antd";
import { TaxonomySlug, TermDto } from "@nice/common"; import { TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client"; import { api } from "@nice/client";
import { CoursesSectionTag } from "./CoursesSectionTag"; import { CoursesSectionTag } from "./CoursesSectionTag";
import PostList from "@web/src/components/models/course/list/PostList";
import LookForMore from "./LookForMore"; import LookForMore from "./LookForMore";
import PostList from "@web/src/components/models/course/list/PostList";
import CourseCard from "../../courses/components/CourseCard";
interface GetTaxonomyProps { interface GetTaxonomyProps {
categories: string[]; categories: string[];
isLoading: boolean; isLoading: boolean;
@ -16,8 +17,9 @@ function useGetTaxonomy({ type }): GetTaxonomyProps {
taxonomy: { taxonomy: {
slug: type, slug: type,
}, },
parentId: null
}, },
take: 10, // 只取前10个 take: 11, // 只取前10个
}); });
const categories = useMemo(() => { const categories = useMemo(() => {
const allCategories = isLoading const allCategories = isLoading
@ -43,16 +45,15 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
type: TaxonomySlug.CATEGORY, type: TaxonomySlug.CATEGORY,
}); });
return ( return (
<section className="relative py-20 overflow-hidden bg-gradient-to-b from-gray-50 to-white"> <section className="relative py-16 overflow-hidden ">
<div className="max-w-screen-2xl mx-auto px-6 relative"> <div className="max-w-screen-2xl mx-auto px-4 relative">
<div className="flex justify-between items-end mb-16"> <div className="flex justify-between items-end mb-12 ">
<div> <div>
<Title <Title
level={2} level={2}
className="font-bold text-5xl mb-6 bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent"> className="font-bold text-5xl mb-6 bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
{title} {title}
</Title> </Title>
<Text <Text
type="secondary" type="secondary"
className="text-xl font-light text-gray-600"> className="text-xl font-light text-gray-600">
@ -81,6 +82,7 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
)} )}
</div> </div>
<PostList <PostList
renderItem={(post) => <CourseCard course={post} edit={false}></CourseCard>}
params={{ params={{
page: 1, page: 1,
pageSize: initialVisibleCoursesCount, pageSize: initialVisibleCoursesCount,

View File

@ -1,4 +1,10 @@
import React, { useRef, useCallback, useEffect, useMemo, useState } from "react"; import React, {
useRef,
useCallback,
useEffect,
useMemo,
useState,
} from "react";
import { Carousel, Typography } from "antd"; import { Carousel, Typography } from "antd";
import { import {
TeamOutlined, TeamOutlined,
@ -30,13 +36,29 @@ interface PlatformStat {
const HeroSection = () => { const HeroSection = () => {
const carouselRef = useRef<CarouselRef>(null); const carouselRef = useRef<CarouselRef>(null);
const { statistics, slides } = useAppConfig(); const { statistics, slides } = useAppConfig();
const [countStatistics, setCountStatistics] = useState<number>(0) const [countStatistics, setCountStatistics] = useState<number>(4);
const platformStats: PlatformStat[] = useMemo(() => { const platformStats: PlatformStat[] = useMemo(() => {
return [ return [
{ icon: <TeamOutlined />, value: statistics.staffs, label: "注册学员" }, {
{ icon: <StarOutlined />, value: statistics.courses, label: "精品课程" }, icon: <TeamOutlined />,
{ icon: <BookOutlined />, value: statistics.lectures, label: '课程章节' }, value: statistics.staffs,
{ icon: <EyeOutlined />, value: statistics.reads, label: "观看次数" }, label: "注册学员",
},
{
icon: <StarOutlined />,
value: statistics.courses,
label: "精品课程",
},
{
icon: <BookOutlined />,
value: statistics.lectures,
label: "课程章节",
},
{
icon: <EyeOutlined />,
value: statistics.reads,
label: "观看次数",
},
]; ];
}, [statistics]); }, [statistics]);
const handlePrev = useCallback(() => { const handlePrev = useCallback(() => {
@ -48,7 +70,7 @@ const HeroSection = () => {
}, []); }, []);
const countNonZeroValues = (statistics: Record<string, number>): number => { const countNonZeroValues = (statistics: Record<string, number>): number => {
return Object.values(statistics).filter(value => value !== 0).length; return Object.values(statistics).filter((value) => value !== 0).length;
}; };
useEffect(() => { useEffect(() => {
@ -67,8 +89,8 @@ const HeroSection = () => {
dots={{ dots={{
className: "carousel-dots !bottom-32 !z-20", className: "carousel-dots !bottom-32 !z-20",
}}> }}>
{Array.isArray(slides) ? {Array.isArray(slides) ? (
(slides.map((item, index) => ( slides.map((item, index) => (
<div key={index} className="relative h-[600px]"> <div key={index} className="relative h-[600px]">
<div <div
className="absolute inset-0 bg-cover bg-center transform transition-[transform,filter] duration-[2000ms] group-hover:scale-105 group-hover:brightness-110 will-change-[transform,filter]" className="absolute inset-0 bg-cover bg-center transform transition-[transform,filter] duration-[2000ms] group-hover:scale-105 group-hover:brightness-110 will-change-[transform,filter]"
@ -87,9 +109,9 @@ const HeroSection = () => {
<div className="relative h-full max-w-7xl mx-auto px-6 lg:px-8"></div> <div className="relative h-full max-w-7xl mx-auto px-6 lg:px-8"></div>
</div> </div>
)) ))
) : ( ) : (
<div></div> <div></div>
)} )}
</Carousel> </Carousel>
{/* Navigation Buttons */} {/* Navigation Buttons */}
@ -108,31 +130,30 @@ const HeroSection = () => {
</div> </div>
{/* Stats Container */} {/* Stats Container */}
{ {countStatistics > 1 && (
countStatistics > 1 && ( <div className="absolute -bottom-20 left-1/2 -translate-x-1/2 w-3/5 max-w-6xl px-4">
<div className="absolute -bottom-20 left-1/2 -translate-x-1/2 w-3/5 max-w-6xl px-4"> <div
<div className={`rounded-2xl grid grid-cols-${countStatistics} md:grid-cols-${countStatistics} gap-4 md:gap-8 p-6 md:p-8 bg-white border shadow-xl hover:shadow-2xl transition-shadow duration-500 will-change-[transform,box-shadow]`}> className={`rounded-2xl grid grid-cols-${countStatistics} lg:grid-cols-${countStatistics} md:grid-cols-${countStatistics} gap-4 md:gap-8 p-6 md:p-8 bg-white border shadow-xl hover:shadow-2xl transition-shadow duration-500 will-change-[transform,box-shadow]`}>
{platformStats.map((stat, index) => { {platformStats.map((stat, index) => {
return stat.value return stat.value ? (
? (<div <div
key={index} key={index}
className="text-center transform hover:-translate-y-1 hover:scale-105 transition-transform duration-300 ease-out"> className="text-center transform hover:-translate-y-1 hover:scale-105 transition-transform duration-300 ease-out">
<div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-full bg-primary-50 text-primary-600 text-3xl transition-colors duration-300 group-hover:text-primary-700"> <div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-full bg-primary-50 text-primary-600 text-3xl transition-colors duration-300 group-hover:text-primary-700">
{stat.icon} {stat.icon}
</div>
<div className="text-2xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent mb-1.5">
{stat.value}
</div>
<div className="text-gray-600 font-medium">
{stat.label}
</div>
</div> </div>
) : null <div className="text-2xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent mb-1.5">
})} {stat.value}
</div> </div>
<div className="text-gray-600 font-medium">
{stat.label}
</div>
</div>
) : null;
})}
</div> </div>
) </div>
} )}
</section> </section>
); );
}; };

View File

@ -2,7 +2,7 @@ import { CloudOutlined, FileSearchOutlined, HomeOutlined, MailOutlined, PhoneOut
export function MainFooter() { export function MainFooter() {
return ( return (
<footer className="bg-gradient-to-b from-slate-800 to-slate-900 text-secondary-200 "> <footer className="bg-gradient-to-b from-slate-800 to-slate-900 z-20 text-secondary-200">
<div className="container mx-auto px-4 py-6"> <div className="container mx-auto px-4 py-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* 开发组织信息 */} {/* 开发组织信息 */}

View File

@ -1,4 +1,3 @@
import { useContext, useState } from "react";
import { Input, Layout, Avatar, Button, Dropdown } from "antd"; import { Input, Layout, Avatar, Button, Dropdown } from "antd";
import { EditFilled, PlusOutlined, SearchOutlined, UserOutlined } from "@ant-design/icons"; import { EditFilled, PlusOutlined, SearchOutlined, UserOutlined } from "@ant-design/icons";
import { useAuth } from "@web/src/providers/auth-provider"; import { useAuth } from "@web/src/providers/auth-provider";
@ -12,13 +11,70 @@ export function MainHeader() {
const { id } = useParams(); const { id } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { searchValue, setSearchValue } = useMainContext(); const { searchValue, setSearchValue } = useMainContext();
return ( return (
<div className="select-none flex items-center justify-between p-4 bg-white shadow-md border-b border-gray-100 fixed w-full z-30 "> <div className="select-none flex items-center justify-center bg-white shadow-md border-b border-gray-100 fixed w-full z-30">
<div className="flex items-center space-x-8"> <div className="w-full max-w-screen-3xl px-4 md:px-6 mx-auto flex items-center justify-between h-full">
<div <div className="flex items-center space-x-8">
onClick={() => navigate("/")} <div
className="text-2xl font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent hover:scale-105 transition-transform cursor-pointer"> onClick={() => navigate("/")}
className="text-2xl font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent hover:scale-105 transition-transform cursor-pointer">
</div>
<NavigationMenu />
</div>
<div className="flex items-center space-x-6">
<div className="group relative">
<Input
size="large"
prefix={
<SearchOutlined className="text-gray-400 group-hover:text-blue-500 transition-colors" />
}
placeholder="搜索课程"
className="w-72 rounded-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
onPressEnter={(e) => {
if (
!window.location.pathname.startsWith(
"/courses/"
)
) {
navigate(`/courses/`);
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
}}
/>
</div>
{isAuthenticated && (
<>
<Button
onClick={() => {
const url = id
? `/course/${id}/editor`
: "/course/editor";
navigate(url);
}}
className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all"
icon={<EditFilled />}>
{id ? "编辑课程" : "创建课程"}
</Button>
</>
)}
{isAuthenticated ? (
<UserMenu />
) : (
<Button
onClick={() => navigate("/login")}
className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all"
icon={<UserOutlined />}>
</Button>
)}
</div> </div>
<NavigationMenu /> <NavigationMenu />
</div> </div>

View File

@ -1,15 +1,30 @@
import { useAuth } from "@web/src/providers/auth-provider";
import { Menu } from "antd"; import { Menu } from "antd";
import { useMemo } from "react";
import { useNavigate, useLocation } from "react-router-dom"; import { useNavigate, useLocation } from "react-router-dom";
const menuItems = [
{ key: "home", path: "/", label: "首页" },
{ key: "courses", path: "/courses", label: "全部课程" },
{ key: "path", path: "/path", label: "学习路径" },
];
export const NavigationMenu = () => { export const NavigationMenu = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { isAuthenticated } = useAuth();
const { pathname } = useLocation(); const { pathname } = useLocation();
const menuItems = useMemo(() => {
const baseItems = [
{ key: "home", path: "/", label: "首页" },
{ key: "courses", path: "/courses", label: "全部课程" },
{ key: "path", path: "/path", label: "学习路径" },
];
if (!isAuthenticated) {
return baseItems;
} else {
return [
...baseItems,
{ key: "my-duty", path: "/my-duty", label: "我创建的" },
{ key: "my-learning", path: "/my-learning", label: "我学习的" },
];
}
}, [isAuthenticated]);
const selectedKey = const selectedKey =
menuItems.find((item) => item.path === pathname)?.key || ""; menuItems.find((item) => item.path === pathname)?.key || "";
return ( return (

View File

@ -86,6 +86,20 @@ export function UserMenu() {
setModalOpen(true); setModalOpen(true);
}, },
}, },
{
icon: <UserOutlined className="text-lg" />,
label: "我创建的课程",
action: () => {
navigate("/my/duty");
},
},
{
icon: <UserOutlined className="text-lg" />,
label: "我学习的课程",
action: () => {
navigate("/my/learning");
},
},
canManageAnyStaff && { canManageAnyStaff && {
icon: <SettingOutlined className="text-lg" />, icon: <SettingOutlined className="text-lg" />,
label: "设置", label: "设置",
@ -222,18 +236,20 @@ export function UserMenu() {
focus:ring-2 focus:ring-[#00538E]/20 focus:ring-2 focus:ring-[#00538E]/20
group relative overflow-hidden group relative overflow-hidden
active:scale-[0.99] active:scale-[0.99]
${item.label === "注销" ${
item.label === "注销"
? "text-[#B22234] hover:bg-red-50/80 hover:text-red-700" ? "text-[#B22234] hover:bg-red-50/80 hover:text-red-700"
: "text-[#00538E] hover:bg-[#E6EEF5] hover:text-[#003F6A]" : "text-[#00538E] hover:bg-[#E6EEF5] hover:text-[#003F6A]"
}`}> }`}>
<span <span
className={`w-5 h-5 flex items-center justify-center className={`w-5 h-5 flex items-center justify-center
transition-all duration-200 ease-in-out transition-all duration-200 ease-in-out
group-hover:scale-110 group-hover:rotate-6 group-hover:scale-110 group-hover:rotate-6
group-hover:translate-x-0.5 ${item.label === "注销" group-hover:translate-x-0.5 ${
? "group-hover:text-red-600" item.label === "注销"
: "group-hover:text-[#003F6A]" ? "group-hover:text-red-600"
}`}> : "group-hover:text-[#003F6A]"
}`}>
{item.icon} {item.icon}
</span> </span>
<span>{item.label}</span> <span>{item.label}</span>

View File

@ -0,0 +1,21 @@
import CourseList from "@web/src/components/models/course/list/CourseList";
import { useAuth } from "@web/src/providers/auth-provider";
export default function MyDutyPage() {
const { user } = useAuth();
return (
<>
<div className="p-4">
<CourseList
edit
params={{
pageSize: 12,
where: {
authorId: user.id,
},
}}
cols={4}></CourseList>
</div>
</>
);
}

View File

@ -0,0 +1,24 @@
import CourseList from "@web/src/components/models/course/list/CourseList";
import { useAuth } from "@web/src/providers/auth-provider";
export default function MyLearningPage() {
const { user } = useAuth();
return (
<>
<div className="p-4">
<CourseList
params={{
pageSize: 12,
where: {
students: {
some: {
id: user?.id,
},
},
},
}}
cols={4}></CourseList>
</div>
</>
);
}

View File

@ -6,39 +6,13 @@ interface CollapsibleContentProps {
maxHeight?: number; maxHeight?: number;
} }
const CollapsibleContent: React.FC<CollapsibleContentProps> = ({ const CollapsibleContent: React.FC<CollapsibleContentProps> = ({ content }) => {
content,
maxHeight = 150,
}) => {
const contentWrapperRef = useRef(null); const contentWrapperRef = useRef(null);
const [isExpanded, setIsExpanded] = useState(false);
const [shouldCollapse, setShouldCollapse] = useState(false);
useEffect(() => {
if (contentWrapperRef.current) {
const shouldCollapse =
contentWrapperRef.current.scrollHeight > maxHeight;
setShouldCollapse(shouldCollapse);
}
}, [content]);
return ( return (
<div className=" text-base "> <div className=" text-base ">
<div className=" flex flex-col gap-4 border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out rounded-xl p-6 "> <div className=" flex flex-col gap-4 border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out rounded-xl p-6 ">
{/* 包装整个内容区域的容器 */} {/* 包装整个内容区域的容器 */}
<div <div ref={contentWrapperRef}>
ref={contentWrapperRef}
style={{
maxHeight:
shouldCollapse && !isExpanded
? maxHeight
: undefined,
}}
className={`duration-300 ${
shouldCollapse && !isExpanded
? ` overflow-hidden relative`
: ""
}`}>
{/* 内容区域 */} {/* 内容区域 */}
<div <div
className="ql-editor p-0 space-y-1 leading-relaxed" className="ql-editor p-0 space-y-1 leading-relaxed"
@ -46,23 +20,7 @@ const CollapsibleContent: React.FC<CollapsibleContentProps> = ({
__html: content || "", __html: content || "",
}} }}
/> />
{/* 渐变遮罩 */}
{shouldCollapse && !isExpanded && (
<div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-white to-transparent" />
)}
</div> </div>
{/* 展开/收起按钮 */}
{shouldCollapse && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="mt-2 text-blue-500 hover:text-blue-700">
{isExpanded ? "收起" : "展开"}
</button>
)}
{/* PostResources 组件 */}
{/* <PostResources post={post} /> */}
</div> </div>
</div> </div>
); );

View File

@ -1,11 +1,11 @@
export const defaultModules = { export const defaultModules = {
toolbar: [ toolbar: [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ header: [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'], ["bold", "italic", "underline", "strike"],
[{ 'list': 'ordered' }, { 'list': 'bullet' }], [{ list: "ordered" }, { list: "bullet" }],
[{ 'color': [] }, { 'background': [] }], [{ color: [] }, { background: [] }],
[{ 'align': [] }], [{ align: [] }],
['link', 'image'], ["link"],
['clean'] ["clean"],
] ],
}; };

View File

@ -1,5 +1,4 @@
import { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
// import UncoverAvatarUploader from "../uploader/UncoverAvatarUploader ";
import { Upload, Progress, Button, Image, Form } from "antd"; import { Upload, Progress, Button, Image, Form } from "antd";
import { DeleteOutlined } from "@ant-design/icons"; import { DeleteOutlined } from "@ant-design/icons";
import AvatarUploader from "./AvatarUploader"; import AvatarUploader from "./AvatarUploader";
@ -8,11 +7,17 @@ import { isEqual } from "lodash";
interface MultiAvatarUploaderProps { interface MultiAvatarUploaderProps {
value?: string[]; value?: string[];
onChange?: (value: string[]) => void; onChange?: (value: string[]) => void;
className?: string;
placeholder?: string;
style?: React.CSSProperties;
} }
export function MultiAvatarUploader({ export function MultiAvatarUploader({
value, value,
onChange, onChange,
className,
style,
placeholder = "点击上传",
}: MultiAvatarUploaderProps) { }: MultiAvatarUploaderProps) {
const [imageList, setImageList] = useState<string[]>(value || []); const [imageList, setImageList] = useState<string[]>(value || []);
const [previewImage, setPreviewImage] = useState<string>(""); const [previewImage, setPreviewImage] = useState<string>("");
@ -30,12 +35,21 @@ export function MultiAvatarUploader({
{(imageList || [])?.map((image, index) => { {(imageList || [])?.map((image, index) => {
return ( return (
<div <div
className="mr-2px relative" className={`mr-2px relative ${className}`}
key={index} key={index}
style={{ width: "200px", height: "100px" }}> style={{
width: "100px",
height: "100px",
...style,
}}>
<Image <Image
alt="" alt=""
style={{ width: "200px", height: "100px" }} className={className}
style={{
width: "100px",
height: "100px",
...style,
}}
src={image} src={image}
preview={{ preview={{
visible: previewImage === image, visible: previewImage === image,
@ -70,7 +84,10 @@ export function MultiAvatarUploader({
</div> </div>
<div className="flex"> <div className="flex">
<AvatarUploader <AvatarUploader
style={style}
className={className}
showCover={false} showCover={false}
placeholder={placeholder}
successText={"轮播图上传成功"} successText={"轮播图上传成功"}
onChange={(value) => { onChange={(value) => {
console.log(value); console.log(value);

View File

@ -0,0 +1,135 @@
import React, { useMemo } from "react";
import { Image, Button, Row, Col, Tooltip } from "antd";
import { ResourceDto } from "@nice/common";
import { env } from "@web/src/env";
import { getFileIcon } from "./utils";
import { formatFileSize, getCompressedImageUrl } from "@nice/utils";
export default function ResourcesShower({
resources = [],
}: {
resources: ResourceDto[];
}) {
const { resources: dealedResources } = useMemo(() => {
if (!resources) return { resources: [] };
const isImage = (url: string) =>
/\.(png|jpg|jpeg|gif|webp)$/i.test(url);
const sortedResources = resources
.map((resource) => {
const original = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${resource.url}`;
const isImg = isImage(resource.url);
return {
...resource,
url: isImg ? getCompressedImageUrl(original) : original,
originalUrl: original,
isImage: isImg,
};
})
.sort((a, b) => (a.isImage === b.isImage ? 0 : a.isImage ? -1 : 1));
return { resources: sortedResources };
}, [resources]);
const imageResources = dealedResources.filter((res) => res.isImage);
const fileResources = dealedResources.filter((res) => !res.isImage);
return (
<div className="space-y-6">
{imageResources.length > 0 && (
<Row gutter={[16, 16]} className="mb-6">
<Image.PreviewGroup>
{imageResources.map((resource) => (
<Col
key={resource.url}
xs={12}
sm={8}
md={6}
lg={6}
xl={4}
className="relative">
<div className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
<div className="w-full h-full">
<Image
src={resource.url}
alt={resource.title}
preview={{
src: resource.originalUrl,
mask: (
<div className="flex items-center justify-center text-white">
</div>
),
}}
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
}}
rootClassName="w-full h-full"
/>
</div>
{resource.title && (
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/60 to-transparent text-white text-sm truncate">
{resource.title}
</div>
)}
</div>
</Col>
))}
</Image.PreviewGroup>
</Row>
)}
{fileResources.length > 0 && (
<div className="rounded-xl p-1 border border-gray-100 bg-white">
<div className="flex flex-nowrap overflow-x-auto scrollbar-hide gap-1.5">
{fileResources.map((resource) => {
return (
<a
key={resource.url}
className="flex-shrink-0 relative active:scale-95 transition-transform select-none "
href={resource.originalUrl}
target="_blank"
download={true}
title="点击下载文件">
{/* 超紧凑卡片容器 */}
<div className="w-[120px] h-[80px] p-2 flex flex-col items-center justify-between rounded-xl hover:bg-primary-50/40 cursor-pointer">
{/* 微型文件图标 */}
<div className="text-primary-600 text-base">
{getFileIcon(resource.url)}
</div>
{/* 压缩信息展示 */}
<div className="w-full text-center space-y-0.5">
<p className="text-xs font-medium text-gray-800 truncate">
{resource.title?.slice(0, 12) ||
"未命名"}
</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span className="bg-gray-100 px-0.5 rounded-sm">
{resource.url
.split(".")
.pop()
?.slice(0, 4)
.toUpperCase()}
</span>
<span>
{resource.meta.size &&
formatFileSize(
resource.meta.size
)}
</span>
</div>
</div>
</div>
</a>
);
})}
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,48 @@
import {
FilePdfOutlined,
FileWordOutlined,
FileExcelOutlined,
FilePptOutlined,
FileTextOutlined,
FileZipOutlined,
FileImageOutlined,
FileUnknownOutlined,
} from "@ant-design/icons";
export const isContentEmpty = (html: string) => {
// 创建一个临时 div 来解析 HTML 内容
const temp = document.createElement("div");
temp.innerHTML = html;
// 获取纯文本内容并检查是否为空
return !temp.textContent?.trim();
};
export const getFileIcon = (filename: string) => {
const extension = filename.split(".").pop()?.toLowerCase();
switch (extension) {
case "pdf":
return <FilePdfOutlined className="text-red-500" />;
case "doc":
case "docx":
return <FileWordOutlined className="text-blue-500" />;
case "xls":
case "xlsx":
return <FileExcelOutlined className="text-green-600" />;
case "ppt":
case "pptx":
return <FilePptOutlined className="text-orange-500" />;
case "txt":
return <FileTextOutlined className="text-gray-600" />;
case "zip":
case "rar":
case "7z":
return <FileZipOutlined className="text-purple-500" />;
case "png":
case "jpg":
case "jpeg":
case "gif":
case "webp":
return <FileImageOutlined className="text-pink-400" />;
default:
return <FileUnknownOutlined className="text-gray-500" />;
}
};

View File

@ -1,38 +1,42 @@
import React from 'react'; import React from "react";
import { useLocation, Link, useMatches } from 'react-router-dom'; import { useLocation, Link, useMatches } from "react-router-dom";
import { theme } from 'antd'; import { theme } from "antd";
import { RightOutlined } from '@ant-design/icons'; import { RightOutlined } from "@ant-design/icons";
export default function Breadcrumb() { export default function Breadcrumb() {
let matches = useMatches(); const matches = useMatches();
const { token } = theme.useToken() const { token } = theme.useToken();
let crumbs = matches const crumbs = matches
// first get rid of any matches that don't have handle and crumb // first get rid of any matches that don't have handle and crumb
.filter((match) => Boolean((match.handle as any)?.crumb)) .filter((match) => Boolean((match.handle as any)?.crumb))
// now map them into an array of elements, passing the loader // now map them into an array of elements, passing the loader
// data to each one // data to each one
.map((match) => (match.handle as any).crumb(match.data)); .map((match) => (match.handle as any).crumb(match.data));
return ( return (
<ol className='flex items-center space-x-2 text-gray-600'> <ol className="flex items-center space-x-2 text-gray-600">
{crumbs.map((crumb, index) => ( {crumbs.map((crumb, index) => (
<React.Fragment key={index}> <React.Fragment key={index}>
<li className={`inline-flex items-center `} <li
style={{ className={`inline-flex items-center `}
color: (index === crumbs.length - 1) ? token.colorPrimaryText : token.colorTextSecondary, style={{
fontWeight: (index === crumbs.length - 1) ? "bold" : "normal", color:
}} index === crumbs.length - 1
> ? token.colorPrimaryText
{crumb} : token.colorTextSecondary,
</li> fontWeight:
{index < crumbs.length - 1 && ( index === crumbs.length - 1 ? "bold" : "normal",
<li className='mx-2'> }}>
<RightOutlined></RightOutlined> {crumb}
</li> </li>
)} {index < crumbs.length - 1 && (
</React.Fragment> <li className="mx-2">
))} <RightOutlined></RightOutlined>
</ol> </li>
); )}
</React.Fragment>
))}
</ol>
);
} }

View File

@ -3,10 +3,18 @@ import {
courseDetailSelect, courseDetailSelect,
CourseDto, CourseDto,
Lecture, Lecture,
lectureDetailSelect,
RolePerms,
VisitType, VisitType,
} from "@nice/common"; } from "@nice/common";
import { useAuth } from "@web/src/providers/auth-provider"; import { useAuth } from "@web/src/providers/auth-provider";
import React, { createContext, ReactNode, useEffect, useState } from "react"; import React, {
createContext,
ReactNode,
useEffect,
useMemo,
useState,
} from "react";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
interface CourseDetailContextType { interface CourseDetailContextType {
@ -19,11 +27,15 @@ interface CourseDetailContextType {
lectureIsLoading?: boolean; lectureIsLoading?: boolean;
isHeaderVisible: boolean; // 新增 isHeaderVisible: boolean; // 新增
setIsHeaderVisible: (visible: boolean) => void; // 新增 setIsHeaderVisible: (visible: boolean) => void; // 新增
canEdit?: boolean;
userIsLearning?: boolean;
} }
interface CourseFormProviderProps { interface CourseFormProviderProps {
children: ReactNode; children: ReactNode;
editId?: string; // 添加 editId 参数 editId?: string; // 添加 editId 参数
} }
export const CourseDetailContext = export const CourseDetailContext =
createContext<CourseDetailContextType | null>(null); createContext<CourseDetailContextType | null>(null);
export function CourseDetailProvider({ export function CourseDetailProvider({
@ -32,20 +44,26 @@ export function CourseDetailProvider({
}: CourseFormProviderProps) { }: CourseFormProviderProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { read } = useVisitor(); const { read } = useVisitor();
const { user } = useAuth(); const { user, hasSomePermissions, isAuthenticated } = useAuth();
const { lectureId } = useParams(); const { lectureId } = useParams();
const { data: course, isLoading }: { data: CourseDto; isLoading: boolean } = const { data: course, isLoading }: { data: CourseDto; isLoading: boolean } =
(api.post as any).findFirst.useQuery( (api.post as any).findFirst.useQuery(
{ {
where: { id: editId }, where: { id: editId },
include: { select: courseDetailSelect,
// sections: { include: { lectures: true } },
enrollments: true,
},
}, },
{ enabled: Boolean(editId) } { enabled: Boolean(editId) }
); );
const userIsLearning = useMemo(() => {
return (course?.studentIds || []).includes(user?.id);
}, [user, course, isLoading]);
const canEdit = useMemo(() => {
const isAuthor = isAuthenticated && user?.id === course?.authorId;
const isRoot = hasSomePermissions(RolePerms?.MANAGE_ANY_POST);
return isAuthor || isRoot;
}, [user, course]);
const [selectedLectureId, setSelectedLectureId] = useState< const [selectedLectureId, setSelectedLectureId] = useState<
string | undefined string | undefined
>(lectureId || undefined); >(lectureId || undefined);
@ -54,16 +72,17 @@ export function CourseDetailProvider({
).findFirst.useQuery( ).findFirst.useQuery(
{ {
where: { id: selectedLectureId }, where: { id: selectedLectureId },
select: lectureDetailSelect,
}, },
{ enabled: Boolean(editId) } { enabled: Boolean(editId) }
); );
useEffect(() => { useEffect(() => {
if (course) { if (lecture?.id) {
console.log("read");
read.mutateAsync({ read.mutateAsync({
data: { data: {
visitorId: user?.id || null, visitorId: user?.id || null,
postId: course.id, postId: lecture?.id,
type: VisitType.READED, type: VisitType.READED,
}, },
}); });
@ -85,6 +104,8 @@ export function CourseDetailProvider({
lectureIsLoading, lectureIsLoading,
isHeaderVisible, isHeaderVisible,
setIsHeaderVisible, setIsHeaderVisible,
canEdit,
userIsLearning,
}}> }}>
{children} {children}
</CourseDetailContext.Provider> </CourseDetailContext.Provider>

View File

@ -1,14 +1,18 @@
import { Course } from "@nice/common"; import { Course, TaxonomySlug } from "@nice/common";
import React, { useContext, useMemo } from "react"; import React, { useContext, useMemo } from "react";
import { Image, Typography, Skeleton } from "antd"; // 引入 antd 组件 import { Image, Typography, Skeleton, Tag } from "antd"; // 引入 antd 组件
import { CourseDetailContext } from "./CourseDetailContext"; import { CourseDetailContext } from "./CourseDetailContext";
import { import {
BookOutlined,
CalendarOutlined, CalendarOutlined,
EditTwoTone,
EyeOutlined, EyeOutlined,
PlayCircleOutlined, PlayCircleOutlined,
ReloadOutlined,
TeamOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useNavigate } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
export const CourseDetailDescription: React.FC = () => { export const CourseDetailDescription: React.FC = () => {
const { course, isLoading, selectedLectureId, setSelectedLectureId } = const { course, isLoading, selectedLectureId, setSelectedLectureId } =
@ -18,15 +22,18 @@ export const CourseDetailDescription: React.FC = () => {
return course?.sections?.[0]?.lectures?.[0]?.id; return course?.sections?.[0]?.lectures?.[0]?.id;
}, [course]); }, [course]);
const navigate = useNavigate(); const navigate = useNavigate();
const { canEdit } = useContext(CourseDetailContext);
const { id } = useParams();
return ( return (
<div className="w-full bg-white shadow-md rounded-lg border border-gray-200 p-6"> // <div className="w-full bg-white shadow-md rounded-lg border border-gray-200 p-5 my-4">
<div className="w-full px-5 my-2">
{isLoading || !course ? ( {isLoading || !course ? (
<Skeleton active paragraph={{ rows: 4 }} /> <Skeleton active paragraph={{ rows: 4 }} />
) : ( ) : (
<div className="space-y-4"> <div className="space-y-2">
{!selectedLectureId && ( {!selectedLectureId && course?.meta?.thumbnail && (
<> <>
<div className="relative my-4 overflow-hidden flex justify-center items-center"> <div className="relative mb-4 overflow-hidden flex justify-center items-center">
<Image <Image
src={course?.meta?.thumbnail} src={course?.meta?.thumbnail}
preview={false} preview={false}
@ -36,22 +43,37 @@ export const CourseDetailDescription: React.FC = () => {
onClick={() => { onClick={() => {
setSelectedLectureId(firstLectureId); setSelectedLectureId(firstLectureId);
}} }}
className="w-full h-full absolute top-0 z-10 bg-black opacity-30 transition-opacity duration-300 ease-in-out hover:opacity-70 cursor-pointer"> className="w-full h-full absolute top-0 z-10 bg-[rgba(0,0,0,0.3)] transition-all duration-300 ease-in-out hover:bg-[rgba(0,0,0,0.7)] cursor-pointer">
<PlayCircleOutlined className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white text-4xl z-10" /> <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white text-4xl z-10">
</div>
</div> </div>
</div> </div>
</> </>
)} )}
<div className="text-lg font-bold">{"课程简介:"}</div> <div className="text-lg font-bold">{"课程简介:"}</div>
<div className="text-gray-600 flex justify-start gap-4"> <div className="flex flex-col gap-2">
<div>{course?.subTitle}</div> <div className="flex gap-2 flex-wrap items-center float-start">
<div className="flex gap-1"> {course?.subTitle && <div>{course?.subTitle}</div>}
<EyeOutlined></EyeOutlined> {course.terms.map((term) => {
<div>{course?.meta?.views || 0}</div> return (
</div> <Tag
<div className="flex gap-1"> key={term.id}
<CalendarOutlined></CalendarOutlined> // color={term.taxonomy.slug===TaxonomySlug.CATEGORY? "blue" : "green"}
{dayjs(course?.createdAt).format("YYYY年M月D日")} color={
term?.taxonomy?.slug ===
TaxonomySlug.CATEGORY
? "blue"
: term?.taxonomy?.slug ===
TaxonomySlug.LEVEL
? "green"
: "orange"
}
className="px-3 py-1 rounded-full bg-blue-100 text-blue-600 border-0">
{term.name}
</Tag>
);
})}
</div> </div>
</div> </div>
<Paragraph <Paragraph

View File

@ -1,67 +0,0 @@
// import { useContext } from "react";
// import { CourseDetailContext } from "../../CourseDetailContext";
// import { CheckCircleIcon } from "@heroicons/react/24/solid";
// export function Overview() {
// const { course } = useContext(CourseDetailContext);
// return (
// <>
// <div className="space-y-8">
// {/* 课程描述 */}
// <div className="prose max-w-none">
// <p>{course?.description}</p>
// </div>
// {/* 学习目标 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">学习目标</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.objectives.map((objective, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-green-500 flex-shrink-0 mt-1" />
// <span>{objective}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 适合人群 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">适合人群</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.audiences.map((audience, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-blue-500 flex-shrink-0 mt-1" />
// <span>{audience}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 课程要求 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">课程要求</h2>
// <ul className="list-disc list-inside space-y-2 text-gray-700">
// {course?.requirements.map((requirement, index) => (
// <li key={index}>{requirement}</li>
// ))}
// </ul>
// </div>
// {/* 可获得技能 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">可获得技能</h2>
// <div className="flex flex-wrap gap-2">
// {course?.skills.map((skill, index) => (
// <span
// key={index}
// className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
// {skill}
// </span>
// ))}
// </div>
// </div>
// </div>
// </>
// );
// }

View File

@ -8,6 +8,17 @@ import { CourseDetailContext } from "./CourseDetailContext";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent"; import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { Skeleton } from "antd"; import { Skeleton } from "antd";
import { CoursePreview } from "./CoursePreview/CoursePreview"; import { CoursePreview } from "./CoursePreview/CoursePreview";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
import {
BookOutlined,
CalendarOutlined,
EditTwoTone,
EyeOutlined,
ReloadOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import CourseDetailTitle from "./CourseDetailTitle";
// interface CourseDetailDisplayAreaProps { // interface CourseDetailDisplayAreaProps {
// // course: Course; // // course: Course;
@ -18,8 +29,15 @@ import { CoursePreview } from "./CoursePreview/CoursePreview";
export const CourseDetailDisplayArea: React.FC = () => { export const CourseDetailDisplayArea: React.FC = () => {
// 创建滚动动画效果 // 创建滚动动画效果
const { course, isLoading, lecture, lectureIsLoading, selectedLectureId } = const {
useContext(CourseDetailContext); course,
isLoading,
canEdit,
lecture,
lectureIsLoading,
selectedLectureId,
} = useContext(CourseDetailContext);
const navigate = useNavigate();
const { scrollY } = useScroll(); const { scrollY } = useScroll();
const videoOpacity = useTransform(scrollY, [0, 200], [1, 0.8]); const videoOpacity = useTransform(scrollY, [0, 200], [1, 0.8]);
return ( return (
@ -28,7 +46,7 @@ export const CourseDetailDisplayArea: React.FC = () => {
{lectureIsLoading && ( {lectureIsLoading && (
<Skeleton active paragraph={{ rows: 4 }} title={false} /> <Skeleton active paragraph={{ rows: 4 }} title={false} />
)} )}
<CourseDetailTitle></CourseDetailTitle>
{selectedLectureId && {selectedLectureId &&
!lectureIsLoading && !lectureIsLoading &&
lecture?.meta?.type === LectureType.VIDEO && ( lecture?.meta?.type === LectureType.VIDEO && (
@ -53,10 +71,16 @@ export const CourseDetailDisplayArea: React.FC = () => {
content={lecture?.content || ""} content={lecture?.content || ""}
maxHeight={500} // Optional, defaults to 150 maxHeight={500} // Optional, defaults to 150
/> />
<div className="px-6">
<ResourcesShower
resources={
lecture?.resources
}></ResourcesShower>
</div>
</div> </div>
</div> </div>
)} )}
<div className="flex justify-center flex-col items-center gap-2 w-full my-2 px-4"> <div className="flex justify-center flex-col items-center gap-2 w-full my-2 ">
<CourseDetailDescription /> <CourseDetailDescription />
</div> </div>
{/* 课程内容区域 */} {/* 课程内容区域 */}

View File

@ -10,62 +10,75 @@ import { useAuth } from "@web/src/providers/auth-provider";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { UserMenu } from "@web/src/app/main/layout/UserMenu/UserMenu"; import { UserMenu } from "@web/src/app/main/layout/UserMenu/UserMenu";
import { CourseDetailContext } from "../CourseDetailContext"; import { CourseDetailContext } from "../CourseDetailContext";
import { Department, RolePerms } from "@nice/common"; import { usePost, useStaff } from "@nice/client";
import toast from "react-hot-toast";
import { NavigationMenu } from "@web/src/app/main/layout/NavigationMenu";
const { Header } = Layout; const { Header } = Layout;
export function CourseDetailHeader() { export function CourseDetailHeader() {
const [searchValue, setSearchValue] = useState("");
const { id } = useParams(); const { id } = useParams();
const { isAuthenticated, user, hasSomePermissions, hasEveryPermissions } = const { isAuthenticated, user, hasSomePermissions, hasEveryPermissions } =
useAuth(); useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const { course } = useContext(CourseDetailContext); const { course, canEdit, userIsLearning } = useContext(CourseDetailContext);
hasSomePermissions(RolePerms.MANAGE_ANY_POST, RolePerms.MANAGE_DOM_POST); const { update } = useStaff();
hasEveryPermissions(RolePerms.MANAGE_ANY_POST, RolePerms.MANAGE_DOM_POST);
return (
<Header className="select-none flex items-center justify-center bg-white shadow-md border-b border-gray-100 fixed w-full z-30">
<div className="w-full flex items-center justify-between h-full">
<div className="flex items-center space-x-2">
<HomeOutlined
onClick={() => {
navigate("/");
}}
className="text-2xl text-primary-500 hover:scale-105 cursor-pointer"
/>
<div className="text-2xl font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent transition-transform "> return (
{course?.title} <Header className="select-none flex items-center justify-center bg-white shadow-md border-b border-gray-100 fixed w-full z-30">
<div className="w-full max-w-screen-3xl px-4 md:px-6 flex items-center justify-between h-full">
<div className="flex items-center space-x-8">
<div
onClick={() => navigate("/")}
className="text-2xl font-bold bg-gradient-to-r from-primary-600 via-primary-500 to-primary-400 bg-clip-text text-transparent hover:scale-105 transition-transform cursor-pointer">
</div> </div>
{/* <NavigationMenu /> */} <NavigationMenu />
</div> </div>
<div className="flex items-center space-x-6"> <div className="flex items-center space-x-6">
<div className="group relative">
<Input
size="large"
prefix={
<SearchOutlined className="text-gray-400 group-hover:text-blue-500 transition-colors" />
}
placeholder="搜索课程"
className="w-72 rounded-full"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
</div>
{isAuthenticated && ( {isAuthenticated && (
<> <Button
<Button onClick={async () => {
onClick={() => { if (!userIsLearning) {
const url = id await update.mutateAsync({
? `/course/${id}/editor` where: { id: user?.id },
: "/course/editor"; data: {
navigate(url); learningPosts: {
}} connect: { id: course.id },
className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all" },
icon={<EditFilled />}> },
{"编辑课程"} });
</Button> } else {
</> await update.mutateAsync({
where: { id: user?.id },
data: {
learningPosts: {
disconnect: {
id: course.id,
},
},
},
});
}
}}
className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all"
icon={<EditFilled />}>
{userIsLearning ? "退出学习" : "加入学习"}
</Button>
)}
{canEdit && (
<Button
onClick={() => {
const url = id
? `/course/${id}/editor`
: "/course/editor";
navigate(url);
}}
className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all"
icon={<EditFilled />}>
{"编辑课程"}
</Button>
)} )}
{isAuthenticated ? ( {isAuthenticated ? (
<UserMenu /> <UserMenu />

View File

@ -1,77 +0,0 @@
// // components/Header.tsx
// import { motion, useScroll, useTransform } from "framer-motion";
// import { useContext, useEffect, useState } from "react";
// import { CourseDetailContext } from "../CourseDetailContext";
// import { Avatar, Button, Dropdown } from "antd";
// import { UserOutlined } from "@ant-design/icons";
// import { UserMenu } from "@web/src/app/main/layout/UserMenu";
// import { useAuth } from "@web/src/providers/auth-provider";
// export const CourseDetailHeader = () => {
// const { scrollY } = useScroll();
// const { user, isAuthenticated } = useAuth();
// const [lastScrollY, setLastScrollY] = useState(0);
// const { course, isHeaderVisible, setIsHeaderVisible, lecture } =
// useContext(CourseDetailContext);
// useEffect(() => {
// const updateHeader = () => {
// const current = scrollY.get();
// const direction = current > lastScrollY ? "down" : "up";
// if (direction === "down" && current > 100) {
// setIsHeaderVisible(false);
// } else if (direction === "up") {
// setIsHeaderVisible(true);
// }
// setLastScrollY(current);
// };
// // 使用 requestAnimationFrame 来优化性能
// const unsubscribe = scrollY.on("change", () => {
// requestAnimationFrame(updateHeader);
// });
// return () => {
// unsubscribe();
// };
// }, [lastScrollY, scrollY, setIsHeaderVisible]);
// return (
// <motion.header
// initial={{ y: 0 }}
// animate={{ y: isHeaderVisible ? 0 : -100 }}
// transition={{ type: "spring", stiffness: 300, damping: 30 }}
// className="fixed top-0 left-0 w-full h-16 bg-slate-900 backdrop-blur-sm z-50 shadow-sm">
// <div className="w-full mx-auto px-4 h-full flex items-center justify-between">
// <div className="flex items-center space-x-4">
// <h1 className="text-white text-xl ">{course?.title}</h1>
// </div>
// {isAuthenticated ? (
// <Dropdown
// overlay={<UserMenu />}
// trigger={["click"]}
// placement="bottomRight">
// <Avatar
// size="large"
// className="cursor-pointer hover:scale-105 transition-all bg-gradient-to-r from-blue-500 to-blue-600 text-white font-semibold">
// {(user?.showname ||
// user?.username ||
// "")[0]?.toUpperCase()}
// </Avatar>
// </Dropdown>
// ) : (
// <Button
// onClick={() => navigator("/login")}
// className="flex items-center space-x-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 border-none shadow-md hover:shadow-lg transition-all"
// icon={<UserOutlined />}>
// 登录
// </Button>
// )}
// </div>
// </motion.header>
// );
// };
// export default CourseDetailHeader;

View File

@ -9,9 +9,7 @@ import { CourseDetailHeader } from "./CourseDetailHeader/CourseDetailHeader";
export default function CourseDetailLayout() { export default function CourseDetailLayout() {
const { const {
course, course,
selectedLectureId,
lecture,
isLoading,
setSelectedLectureId, setSelectedLectureId,
} = useContext(CourseDetailContext); } = useContext(CourseDetailContext);
@ -26,7 +24,7 @@ export default function CourseDetailLayout() {
{/* 添加 Header 组件 */} {/* 添加 Header 组件 */}
{/* 主内容区域 */} {/* 主内容区域 */}
{/* 为了防止 Header 覆盖内容,添加上边距 */} {/* 为了防止 Header 覆盖内容,添加上边距 */}
<div className="pt-16"> <div className="pt-16 px-32">
{" "} {" "}
{/* 添加这个包装 div */} {/* 添加这个包装 div */}
<motion.div <motion.div
@ -38,10 +36,7 @@ export default function CourseDetailLayout() {
}} }}
transition={{ type: "spring", stiffness: 300, damping: 30 }} transition={{ type: "spring", stiffness: 300, damping: 30 }}
className="relative"> className="relative">
<CourseDetailDisplayArea <CourseDetailDisplayArea />
// course={course}
// isLoading={isLoading}
/>
</motion.div> </motion.div>
{/* 课程大纲侧边栏 */} {/* 课程大纲侧边栏 */}
<CourseSyllabus <CourseSyllabus

View File

@ -0,0 +1,57 @@
import { useContext } from "react";
import { CourseDetailContext } from "./CourseDetailContext";
import { useNavigate } from "react-router-dom";
import { BookOutlined, CalendarOutlined, EditTwoTone, EyeOutlined, ReloadOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
export default function CourseDetailTitle() {
const {
course,
isLoading,
canEdit,
lecture,
lectureIsLoading,
selectedLectureId,
} = useContext(CourseDetailContext);
const navigate = useNavigate();
return (
<div className="flex justify-center flex-col items-center gap-2 w-full my-2 px-6">
<div className="flex justify-start w-full text-2xl font-bold">
{course?.title}
</div>
<div className="text-gray-600 flex w-full justify-start gap-5">
<div className="flex gap-1">
<CalendarOutlined></CalendarOutlined>
{"创建于:"}
{dayjs(course?.createdAt).format("YYYY年M月D日")}
</div>
<div className="flex gap-1">
<ReloadOutlined></ReloadOutlined>
{"更新于:"}
{dayjs(course?.updatedAt).format("YYYY年M月D日")}
</div>
<div className="flex gap-1">
<EyeOutlined></EyeOutlined>
<div>{`观看次数${course?.meta?.views || 0}`}</div>
</div>
<div className="flex gap-1">
<BookOutlined />
<div>{`学习人数${course?.studentIds?.length || 0}`}</div>
</div>
{canEdit && (
<div
className="flex gap-1 text-primary hover:cursor-pointer"
onClick={() => {
const url = course?.id
? `/course/${course?.id}/editor`
: "/course/editor";
navigate(url);
}}>
<EditTwoTone></EditTwoTone>
{"点击编辑课程"}
</div>
)}
</div>
</div>
);
}

View File

@ -45,7 +45,6 @@ export const CourseSyllabus: React.FC<CourseSyllabusProps> = ({
block: "start", block: "start",
}); });
}; };
return ( return (
<> <>
{/* 收起按钮直接显示 */} {/* 收起按钮直接显示 */}

View File

@ -4,6 +4,7 @@ import { Lecture, LectureType, LessonTypeLabel } from "@nice/common";
import React, { useMemo } from "react"; import React, { useMemo } from "react";
import { import {
ClockCircleOutlined, ClockCircleOutlined,
EyeOutlined,
FileTextOutlined, FileTextOutlined,
PlayCircleOutlined, PlayCircleOutlined,
} from "@ant-design/icons"; // 使用 Ant Design 图标 } from "@ant-design/icons"; // 使用 Ant Design 图标
@ -43,13 +44,17 @@ export const LectureItem: React.FC<LectureItemProps> = ({
<span>{LessonTypeLabel[lecture?.meta?.type]}</span> <span>{LessonTypeLabel[lecture?.meta?.type]}</span>
</div> </div>
)} )}
<div className="flex-grow"> <div className="flex-grow flex justify-between items-center w-2/3 realative">
<h4 className="font-medium text-gray-800">{lecture.title}</h4> <h4 className="font-medium text-gray-800 w-4/5">{lecture.title}</h4>
{lecture.subTitle && ( {lecture.subTitle && (
<p className="text-sm text-gray-500 mt-1"> <span className="text-sm text-gray-500 mt-1 w-4/5">
{lecture.subTitle} {lecture.subTitle}
</p> </span>
)} )}
<div className="text-gray-500 whitespace-normal">
<EyeOutlined></EyeOutlined>
<span className="ml-2">{lecture?.meta?.views ? lecture?.meta?.views : 0}</span>
</div>
</div> </div>
</div> </div>
); );

View File

@ -91,6 +91,7 @@ export function CourseFormProvider({
const formattedValues = { const formattedValues = {
...values, ...values,
type: PostType.COURSE,
meta: { meta: {
...((course?.meta as CourseMeta) || {}), ...((course?.meta as CourseMeta) || {}),
...(values?.meta?.thumbnail !== undefined && { ...(values?.meta?.thumbnail !== undefined && {
@ -98,10 +99,10 @@ export function CourseFormProvider({
}), }),
}, },
terms: { terms: {
connect: termIds.map((id) => ({ id })), // 转换成 connect 格式 set: termIds.map((id) => ({ id })), // 转换成 connect 格式
}, },
depts: { depts: {
connect: deptIds.map((id) => ({ id })), set: deptIds.map((id) => ({ id })),
}, },
}; };
// 删除原始的 taxonomy 字段 // 删除原始的 taxonomy 字段
@ -111,8 +112,6 @@ export function CourseFormProvider({
delete formattedValues.sections; delete formattedValues.sections;
delete formattedValues.deptIds; delete formattedValues.deptIds;
console.log(course.meta);
console.log(formattedValues?.meta);
try { try {
if (editId) { if (editId) {
const result = await update.mutateAsync({ const result = await update.mutateAsync({
@ -125,7 +124,7 @@ export function CourseFormProvider({
const result = await createCourse.mutateAsync({ const result = await createCourse.mutateAsync({
courseDetail: { courseDetail: {
data: { data: {
title: formattedValues.title || "12345", title: formattedValues.title,
// state: CourseStatus.DRAFT, // state: CourseStatus.DRAFT,
type: PostType.COURSE, type: PostType.COURSE,

View File

@ -32,7 +32,7 @@ export function CourseBasicForm() {
<Form.Item <Form.Item
name="subTitle" name="subTitle"
label="课程副标题" label="课程副标题"
rules={[{ max: 10, message: "副标题最多10个字符" }]}> rules={[{ max: 20, message: "副标题最多20个字符" }]}>
<Input placeholder="请输入课程副标题" /> <Input placeholder="请输入课程副标题" />
</Form.Item> </Form.Item>
<Form.Item name={["meta", "thumbnail"]} label="课程封面"> <Form.Item name={["meta", "thumbnail"]} label="课程封面">

View File

@ -33,7 +33,12 @@ import {
useSortable, useSortable,
verticalListSortingStrategy, verticalListSortingStrategy,
} from "@dnd-kit/sortable"; } from "@dnd-kit/sortable";
import { Lecture, LectureType, PostType } from "@nice/common"; import {
Lecture,
lectureDetailSelect,
LectureType,
PostType,
} from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext"; import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client"; import { usePost } from "@nice/client";
import { LectureData, SectionData } from "./interface"; import { LectureData, SectionData } from "./interface";
@ -62,6 +67,7 @@ export const LectureList: React.FC<LectureListProps> = ({
orderBy: { orderBy: {
order: "asc", order: "asc",
}, },
select: lectureDetailSelect,
}, },
{ {
enabled: !!sectionId, enabled: !!sectionId,

View File

@ -15,6 +15,7 @@ import {
LectureType, LectureType,
LessonTypeLabel, LessonTypeLabel,
PostType, PostType,
ResourceStatus,
videoMimeTypes, videoMimeTypes,
} from "@nice/common"; } from "@nice/common";
import { usePost } from "@nice/client"; import { usePost } from "@nice/client";
@ -23,6 +24,8 @@ import toast from "react-hot-toast";
import { env } from "@web/src/env"; import { env } from "@web/src/env";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent"; import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer"; import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer";
import MultiAvatarUploader from "@web/src/components/common/uploader/MultiAvatarUploader";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
interface SortableLectureProps { interface SortableLectureProps {
field: Lecture; field: Lecture;
@ -58,6 +61,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
setLoading(true); setLoading(true);
const values = await form.validateFields(); const values = await form.validateFields();
let result; let result;
const fileIds = values?.meta?.fileIds || [];
const videoUrlId = Array.isArray(values?.meta?.videoIds) const videoUrlId = Array.isArray(values?.meta?.videoIds)
? values?.meta?.videoIds[0] ? values?.meta?.videoIds[0]
: typeof values?.meta?.videoIds === "string" : typeof values?.meta?.videoIds === "string"
@ -72,13 +76,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title, title: values?.title,
meta: { meta: {
type: values?.meta?.type, type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [], videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8` ? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined, : undefined,
}, },
resources: { resources: {
connect: [videoUrlId] connect: [videoUrlId, ...fileIds]
.filter(Boolean) .filter(Boolean)
.map((fileId) => ({ .map((fileId) => ({
fileId, fileId,
@ -97,13 +102,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title, title: values?.title,
meta: { meta: {
type: values?.meta?.type, type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [], videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8` ? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined, : undefined,
}, },
resources: { resources: {
connect: [videoUrlId] connect: [videoUrlId, ...fileIds]
.filter(Boolean) .filter(Boolean)
.map((fileId) => ({ .map((fileId) => ({
fileId, fileId,
@ -113,6 +119,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
}, },
}); });
} }
setIsContentVisible(false);
toast.success("课时已更新"); toast.success("课时已更新");
field.id = result.id; field.id = result.id;
setEditing(false); setEditing(false);
@ -178,14 +185,30 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
/> />
</Form.Item> </Form.Item>
) : ( ) : (
<Form.Item <div>
name="content" <Form.Item
className="mb-0 flex-1" name="content"
rules={[ className="mb-0 flex-1"
{ required: true, message: "请输入内容" }, rules={[
]}> {
<QuillEditor /> required: true,
</Form.Item> message: "请输入内容",
},
]}>
<QuillEditor />
</Form.Item>
<Form.Item
name={["meta", "fileIds"]}
className="mb-0 flex-1"
rules={[
{
required: true,
message: "请传入文件",
},
]}>
<TusUploader multiple={true} />
</Form.Item>
</div>
)} )}
</div> </div>
@ -237,10 +260,16 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
{isContentVisible && {isContentVisible &&
!editing && // Conditionally render content based on type !editing && // Conditionally render content based on type
(field?.meta?.type === LectureType.ARTICLE ? ( (field?.meta?.type === LectureType.ARTICLE ? (
<CollapsibleContent <div>
maxHeight={200} <CollapsibleContent
content={field?.content} maxHeight={200}
/> content={field?.content}
/>
<div className="px-6 ">
<ResourcesShower
resources={field?.resources}></ResourcesShower>
</div>
</div>
) : ( ) : (
<VideoPlayer src={field?.meta?.videoUrl} /> <VideoPlayer src={field?.meta?.videoUrl} />
))} ))}

View File

@ -13,6 +13,7 @@ interface PostListProps {
cols?: number; cols?: number;
showPagination?: boolean; showPagination?: boolean;
renderItem: (post: any) => React.ReactNode renderItem: (post: any) => React.ReactNode
} }
interface PostPagnationProps { interface PostPagnationProps {
data: { data: {
@ -57,7 +58,11 @@ export default function PostList({
window.scrollTo({ top: 0, behavior: "smooth" }); window.scrollTo({ top: 0, behavior: "smooth" });
} }
if (isLoading) { if (isLoading) {
return <Skeleton paragraph={{ rows: 10 }}></Skeleton>; return (
<div className="space-y-6">
<Skeleton paragraph={{ rows: 10 }}></Skeleton>
</div>
);
} }
return ( return (
<div className="space-y-6"> <div className="space-y-6">

View File

@ -2,7 +2,6 @@ import { api } from "@nice/client/";
import { Checkbox, Form } from "antd"; import { Checkbox, Form } from "antd";
import { TermDto } from "@nice/common"; import { TermDto } from "@nice/common";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
export default function TermParentSelector({ export default function TermParentSelector({
value, value,
onChange, onChange,
@ -13,11 +12,7 @@ export default function TermParentSelector({
domainId, domainId,
style, style,
}: any) { }: any) {
const utils = api.useUtils();
const [selectedValues, setSelectedValues] = useState<string[]>([]); // 用于存储选中的值 const [selectedValues, setSelectedValues] = useState<string[]>([]); // 用于存储选中的值
const [termsData, setTermsData] = useState<any[]>([]);
const { const {
data, data,
isLoading, isLoading,
@ -42,7 +37,7 @@ export default function TermParentSelector({
<Checkbox.Group onChange={handleCheckboxChange}> <Checkbox.Group onChange={handleCheckboxChange}>
{data?.map((category) => ( {data?.map((category) => (
<div className="w-full h-9 p-2 my-1"> <div className="w-full h-9 p-2 my-1">
<Checkbox className="text-base text-slate-700" key={category.id} value={category.id}> <Checkbox className="text-base text-slate-700" key={category.id} value={category.id}>
{category.name} {category.name}
</Checkbox> </Checkbox>
</div> </div>

View File

@ -48,7 +48,7 @@ export default function TermSelect({
const [listTreeData, setListTreeData] = useState< const [listTreeData, setListTreeData] = useState<
Omit<DefaultOptionType, "label">[] Omit<DefaultOptionType, "label">[]
>([]); >([]);
const fetchParentTerms = useCallback( const fetchParentTerms = useCallback(
async (termIds: string | string[], taxonomyId?: string) => { async (termIds: string | string[], taxonomyId?: string) => {
const idsArray = Array.isArray(termIds) const idsArray = Array.isArray(termIds)

View File

@ -96,7 +96,6 @@ export const Controls = () => {
<div className="flex items-center space-x-4"> <div className="flex items-center space-x-4">
{/* 播放/暂停按钮 */} {/* 播放/暂停按钮 */}
<Play></Play> <Play></Play>
{/* 时间显示 */} {/* 时间显示 */}
{duration && ( {duration && (
<span className="text-white text-xl"> <span className="text-white text-xl">
@ -114,7 +113,7 @@ export const Controls = () => {
{/* 倍速控制 */} {/* 倍速控制 */}
<Speed></Speed> <Speed></Speed>
{/* 设置按钮 */} {/* 设置按钮 */}
<Setting></Setting> {/* <Setting></Setting> */}
{/* 全屏按钮 */} {/* 全屏按钮 */}
<FullScreen></FullScreen> <FullScreen></FullScreen>

View File

@ -14,7 +14,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
onError, onError,
videoRef, videoRef,
setIsReady, setIsReady,
isPlaying,
setIsPlaying, setIsPlaying,
setError, setError,
setBufferingState, setBufferingState,
@ -26,8 +25,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
isDragging, isDragging,
setIsDragging, setIsDragging,
progressRef, progressRef,
resolution,
setResolutions,
} = useContext(VideoPlayerContext); } = useContext(VideoPlayerContext);
// 处理进度条拖拽 // 处理进度条拖拽
@ -40,7 +37,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
); );
videoRef.current.currentTime = percent * videoRef.current.duration; videoRef.current.currentTime = percent * videoRef.current.duration;
}; };
// 添加拖拽事件监听 // 添加拖拽事件监听
useEffect(() => { useEffect(() => {
const handleMouseUp = () => setIsDragging(false); const handleMouseUp = () => setIsDragging(false);
@ -66,15 +62,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
setError(null); setError(null);
setLoadingProgress(0); setLoadingProgress(0);
setBufferingState(false); setBufferingState(false);
// Check for native HLS support (Safari) // Check for native HLS support (Safari)
if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) { if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) {
videoRef.current.src = src; videoRef.current.src = src;
setIsReady(true); setIsReady(true);
// 设置视频时长 // 设置视频时长
setDuration(videoRef.current.duration); setDuration(videoRef.current.duration);
if (autoPlay) { if (autoPlay) {
try { try {
await videoRef.current.play(); await videoRef.current.play();
@ -85,14 +78,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
} }
return; return;
} }
if (!Hls.isSupported()) { if (!Hls.isSupported()) {
const errorMessage = "您的浏览器不支持 HLS 视频播放"; const errorMessage = "您的浏览器不支持 HLS 视频播放";
setError(errorMessage); setError(errorMessage);
onError?.(errorMessage); onError?.(errorMessage);
return; return;
} }
hls = new Hls({ hls = new Hls({
maxBufferLength: 30, maxBufferLength: 30,
maxMaxBufferLength: 600, maxMaxBufferLength: 600,
@ -102,13 +93,10 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
hls.loadSource(src); hls.loadSource(src);
hls.attachMedia(videoRef.current); hls.attachMedia(videoRef.current);
hls.on(Hls.Events.MANIFEST_PARSED, async () => { hls.on(Hls.Events.MANIFEST_PARSED, async () => {
setIsReady(true); setIsReady(true);
// 设置视频时长 // 设置视频时长
setDuration(videoRef.current?.duration || 0); setDuration(videoRef.current?.duration || 0);
if (autoPlay && videoRef.current) { if (autoPlay && videoRef.current) {
try { try {
await videoRef.current.play(); await videoRef.current.play();
@ -118,7 +106,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
} }
} }
}); });
hls.on(Hls.Events.BUFFER_APPENDING, () => { hls.on(Hls.Events.BUFFER_APPENDING, () => {
setBufferingState(true); setBufferingState(true);
}); });
@ -205,7 +192,7 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
}, [src, onError, autoPlay]); }, [src, onError, autoPlay]);
return ( return (
<div className="relative w-full h-full"> <div className="relative w-full aspect-video">
<video <video
ref={videoRef} ref={videoRef}
className="w-full h-full" className="w-full h-full"

View File

@ -55,7 +55,6 @@ export function VideoPlayer({
src, src,
poster, poster,
onError, onError,
}: { }: {
src: string; src: string;
poster?: string; poster?: string;

View File

@ -18,7 +18,7 @@ export default function VideoPlayerLayout() {
<> <>
<div <div
className={`relative w-full bg-black rounded-lg overflow-hidden`} className={`relative w-full bg-black rounded-lg overflow-hidden`}
style={{ aspectRatio: "21/9" }} style={{ aspectRatio: "16/9" }}
onMouseEnter={() => { onMouseEnter={() => {
setIsHovering(true); setIsHovering(true);
setShowControls(true); setShowControls(true);

View File

@ -19,6 +19,9 @@ import PathPage from "../app/main/path/page";
import { adminRoute } from "./admin-route"; import { adminRoute } from "./admin-route";
import PathEditorPage from "../app/main/path/editor/page"; import PathEditorPage from "../app/main/path/editor/page";
import { CoursePreview } from "../app/main/course/preview/page";
import MyLearningPage from "../app/main/my-learning/page";
import MyDutyPage from "../app/main/my-duty/page";
interface CustomIndexRouteObject extends IndexRouteObject { interface CustomIndexRouteObject extends IndexRouteObject {
name?: string; name?: string;
breadcrumb?: string; breadcrumb?: string;
@ -73,18 +76,25 @@ export const routes: CustomRouteObject[] = [
path: "courses", path: "courses",
element: <CoursesPage></CoursesPage>, element: <CoursesPage></CoursesPage>,
}, },
{ {
path: "profiles", path: "my-duty",
element: (
<WithAuth>
<MyDutyPage></MyDutyPage>
</WithAuth>
),
},
{
path: "my-learning",
element: (
<WithAuth>
<MyLearningPage></MyLearningPage>
</WithAuth>
),
}, },
// // 课程预览页面
// {
// path: "coursePreview/:id?",
// element: <CoursePreview></CoursePreview>,
// },
], ],
}, },
{ {
path: "course", path: "course",
children: [ children: [
@ -113,7 +123,6 @@ export const routes: CustomRouteObject[] = [
</WithAuth> </WithAuth>
), ),
}, },
], ],
}, },
{ {

View File

@ -5,39 +5,48 @@ import { ObjectType, Staff } from "@nice/common";
import { findQueryData } from "../utils"; import { findQueryData } from "../utils";
import { CrudOperation, emitDataChange } from "../../event"; import { CrudOperation, emitDataChange } from "../../event";
export function useStaff() { export function useStaff() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const queryKey = getQueryKey(api.staff); const queryKey = getQueryKey(api.staff);
const create = api.staff.create.useMutation({ const create = api.staff.create.useMutation({
onSuccess: (result) => { onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey }); queryClient.invalidateQueries({ queryKey });
emitDataChange(ObjectType.STAFF, result as any, CrudOperation.CREATED) emitDataChange(
}, ObjectType.STAFF,
}); result as any,
const updateUserDomain = api.staff.updateUserDomain.useMutation({ CrudOperation.CREATED
onSuccess: async (result) => { );
queryClient.invalidateQueries({ queryKey }); },
}, });
}); const updateUserDomain = api.staff.updateUserDomain.useMutation({
const update = api.staff.update.useMutation({ onSuccess: async (result) => {
onSuccess: (result) => { queryClient.invalidateQueries({ queryKey });
queryClient.invalidateQueries({ queryKey }); },
emitDataChange(ObjectType.STAFF, result as any, CrudOperation.UPDATED) });
}, const update = api.staff.update.useMutation({
}); onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey });
queryClient.invalidateQueries({ queryKey: getQueryKey(api.post) });
emitDataChange(
ObjectType.STAFF,
result as any,
CrudOperation.UPDATED
);
},
});
const softDeleteByIds = api.staff.softDeleteByIds.useMutation({ const softDeleteByIds = api.staff.softDeleteByIds.useMutation({
onSuccess: (result, variables) => { onSuccess: (result, variables) => {
queryClient.invalidateQueries({ queryKey }); queryClient.invalidateQueries({ queryKey });
}, },
}); });
const getStaff = (key: string) => { const getStaff = (key: string) => {
return findQueryData<Staff>(queryClient, api.staff, key); return findQueryData<Staff>(queryClient, api.staff, key);
}; };
return { return {
create, create,
update, update,
softDeleteByIds, softDeleteByIds,
getStaff, getStaff,
updateUserDomain updateUserDomain,
}; };
} }

View File

@ -88,9 +88,12 @@ model Staff {
deletedAt DateTime? @map("deleted_at") deletedAt DateTime? @map("deleted_at")
officerId String? @map("officer_id") officerId String? @map("officer_id")
watchedPost Post[] @relation("post_watch_staff") // watchedPost Post[] @relation("post_watch_staff")
visits Visit[] visits Visit[]
posts Post[] posts Post[]
learningPosts Post[] @relation("post_student")
sentMsgs Message[] @relation("message_sender") sentMsgs Message[] @relation("message_sender")
receivedMsgs Message[] @relation("message_receiver") receivedMsgs Message[] @relation("message_receiver")
registerToken String? registerToken String?
@ -124,7 +127,7 @@ model Department {
deptStaffs Staff[] @relation("DeptStaff") deptStaffs Staff[] @relation("DeptStaff")
terms Term[] @relation("department_term") terms Term[] @relation("department_term")
watchedPost Post[] @relation("post_watch_dept") // watchedPost Post[] @relation("post_watch_dept")
hasChildren Boolean? @default(false) @map("has_children") hasChildren Boolean? @default(false) @map("has_children")
@@index([parentId]) @@index([parentId])
@ -201,6 +204,7 @@ model Post {
order Float? @default(0) @map("order") order Float? @default(0) @map("order")
duration Int? duration Int?
rating Int? @default(0) rating Int? @default(0)
students Staff[] @relation("post_student")
depts Department[] @relation("post_dept") depts Department[] @relation("post_dept")
// 索引 // 索引
// 日期时间类型字段 // 日期时间类型字段
@ -222,8 +226,8 @@ model Post {
ancestors PostAncestry[] @relation("DescendantPosts") ancestors PostAncestry[] @relation("DescendantPosts")
descendants PostAncestry[] @relation("AncestorPosts") descendants PostAncestry[] @relation("AncestorPosts")
resources Resource[] // 附件列表 resources Resource[] // 附件列表
watchableStaffs Staff[] @relation("post_watch_staff") // 可观看的员工列表,关联 Staff 模型 // watchableStaffs Staff[] @relation("post_watch_staff")
watchableDepts Department[] @relation("post_watch_dept") // 可观看的部门列表,关联 Department 模型 // watchableDepts Department[] @relation("post_watch_dept") // 可观看的部门列表,关联 Department 模型
meta Json? // 封面url 视频url objectives具体的学习目标 rating评分Int meta Json? // 封面url 视频url objectives具体的学习目标 rating评分Int
// 索引 // 索引
@ -287,14 +291,6 @@ model Visit {
message Message? @relation(fields: [messageId], references: [id]) message Message? @relation(fields: [messageId], references: [id])
messageId String? @map("message_id") messageId String? @map("message_id")
lectureId String? @map("lecture_id") // 课时ID lectureId String? @map("lecture_id") // 课时ID
// 学习数据
// progress Float? @default(0) @map("progress") // 完成进度(0-100%)
// isCompleted Boolean? @default(false) @map("is_completed") // 是否完成
// lastPosition Int? @default(0) @map("last_position") // 视频播放位置(秒)
// totalWatchTime Int? @default(0) @map("total_watch_time") // 总观看时长(秒)
// // 时间记录
// lastWatchedAt DateTime? @map("last_watched_at") // 最后观看时间
createdAt DateTime @default(now()) @map("created_at") // 创建时间 createdAt DateTime @default(now()) @map("created_at") // 创建时间
updatedAt DateTime @updatedAt @map("updated_at") // 更新时间 updatedAt DateTime @updatedAt @map("updated_at") // 更新时间
deletedAt DateTime? @map("deleted_at") // 删除时间,可为空 deletedAt DateTime? @map("deleted_at") // 删除时间,可为空

View File

@ -5,7 +5,7 @@ export enum PostType {
POST = "post", POST = "post",
POST_COMMENT = "post_comment", POST_COMMENT = "post_comment",
COURSE_REVIEW = "course_review", COURSE_REVIEW = "course_review",
COURSE = "couse", COURSE = "course",
SECTION = "section", SECTION = "section",
LECTURE = "lecture", LECTURE = "lecture",
PATH = "path", PATH = "path",
@ -101,7 +101,6 @@ export enum RolePerms {
} }
export enum AppConfigSlug { export enum AppConfigSlug {
BASE_SETTING = "base_setting", BASE_SETTING = "base_setting",
} }
// 资源类型的枚举,定义了不同类型的资源,以字符串值表示 // 资源类型的枚举,定义了不同类型的资源,以字符串值表示
export enum ResourceType { export enum ResourceType {

View File

@ -1,7 +1,8 @@
export * from "./department" export * from "./department";
export * from "./message" export * from "./message";
export * from "./staff" export * from "./staff";
export * from "./term" export * from "./term";
export * from "./post" export * from "./post";
export * from "./rbac" export * from "./rbac";
export * from "./select" export * from "./select";
export * from "./resource";

View File

@ -8,6 +8,7 @@ import {
} from "@prisma/client"; } from "@prisma/client";
import { StaffDto } from "./staff"; import { StaffDto } from "./staff";
import { TermDto } from "./term"; import { TermDto } from "./term";
import { ResourceDto } from "./resource";
import { DepartmentDto } from "./department"; import { DepartmentDto } from "./department";
export type PostComment = { export type PostComment = {
@ -47,6 +48,7 @@ export type PostDto = Post & {
export type LectureMeta = { export type LectureMeta = {
type?: string; type?: string;
views?: number;
videoUrl?: string; videoUrl?: string;
videoThumbnail?: string; videoThumbnail?: string;
videoIds?: string[]; videoIds?: string[];
@ -54,6 +56,7 @@ export type LectureMeta = {
}; };
export type Lecture = Post & { export type Lecture = Post & {
resources?: ResourceDto[];
meta?: LectureMeta; meta?: LectureMeta;
}; };
@ -82,5 +85,6 @@ export type CourseDto = Course & {
sections?: SectionDto[]; sections?: SectionDto[];
terms: TermDto[]; terms: TermDto[];
lectureCount?: number; lectureCount?: number;
depts:Department[] depts: Department[];
studentIds: string[];
}; };

View File

@ -0,0 +1,52 @@
import { Resource } from "@prisma/client";
export interface BaseMetadata {
size: number;
filetype: string;
filename: string;
extension: string;
modifiedAt: Date;
}
/**
*
*/
export interface ImageMetadata {
width: number; // 图片宽度(px)
height: number; // 图片高度(px)
compressedUrl?: string;
orientation?: number; // EXIF方向信息
space?: string; // 色彩空间 (如: RGB, CMYK)
hasAlpha?: boolean; // 是否包含透明通道
}
/**
*
*/
export interface VideoMetadata {
width?: number;
height?: number;
duration?: number;
videoCodec?: string;
audioCodec?: string;
coverUrl?: string;
}
/**
*
*/
export interface AudioMetadata {
duration: number; // 音频时长(秒)
bitrate?: number; // 比特率(bps)
sampleRate?: number; // 采样率(Hz)
channels?: number; // 声道数
codec?: string; // 音频编码格式
}
export type FileMetadata = ImageMetadata &
VideoMetadata &
AudioMetadata &
BaseMetadata;
export type ResourceDto = Resource & {
meta: FileMetadata;
};

View File

@ -1,5 +0,0 @@
import { Lecture, Section } from "@prisma/client";
export type SectionDto = Section & {
lectures: Lecture[];
};

View File

@ -6,8 +6,8 @@ export const postDetailSelect: Prisma.PostSelect = {
title: true, title: true,
content: true, content: true,
resources: true, resources: true,
watchableDepts: true, // watchableDepts: true,
watchableStaffs: true, // watchableStaffs: true,
updatedAt: true, updatedAt: true,
terms: { terms: {
select: { select: {
@ -84,6 +84,7 @@ export const courseDetailSelect: Prisma.PostSelect = {
id: true, id: true,
title: true, title: true,
subTitle: true, subTitle: true,
type: true,
content: true, content: true,
depts: true, depts: true,
// isFeatured: true, // isFeatured: true,
@ -94,6 +95,7 @@ export const courseDetailSelect: Prisma.PostSelect = {
select: { select: {
id: true, id: true,
name: true, name: true,
taxonomyId: true,
taxonomy: { taxonomy: {
select: { select: {
id: true, id: true,
@ -110,3 +112,15 @@ export const courseDetailSelect: Prisma.PostSelect = {
meta: true, meta: true,
rating: true, rating: true,
}; };
export const lectureDetailSelect: Prisma.PostSelect = {
id: true,
title: true,
subTitle: true,
content: true,
resources: true,
createdAt: true,
updatedAt: true,
// 关联表选择
meta: true,
};