This commit is contained in:
Rao 2025-02-21 17:05:14 +08:00
commit e505b77dcb
45 changed files with 673 additions and 1037 deletions

View File

@ -21,7 +21,7 @@ export abstract class RowModelService {
// 添加更多需要引号的关键词
]);
protected logger = new Logger(this.tableName);
protected constructor(protected tableName: string) {}
protected constructor(protected tableName: string) { }
protected async getRowDto(row: any, staff?: UserProfile): Promise<any> {
return row;
}
@ -52,7 +52,7 @@ export abstract class RowModelService {
]);
SQL = await this.getRowsSqlWrapper(SQL, request, staff);
this.logger.debug('getrows', SQL);
// this.logger.debug('getrows', SQL);
const results: any[] = (await db?.$queryRawUnsafe(SQL)) || [];

View File

@ -6,6 +6,5 @@ import { db } from '@nice/common';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) { }
constructor(private readonly postService: PostService) {}
}

View File

@ -15,7 +15,7 @@ import {
import { MessageService } from '../message/message.service';
import { BaseService } from '../base/base.service';
import { DepartmentService } from '../department/department.service';
import { setPostRelation } from './utils';
import { setCourseInfo, setPostRelation } from './utils';
import EventBus, { CrudOperation } from '@server/utils/event-bus';
import { BaseTreeService } from '../base/base.tree.service';
import { z } from 'zod';
@ -180,6 +180,7 @@ export class PostService extends BaseTreeService<Prisma.PostDelegate> {
if (result) {
await setPostRelation({ data: result, staff });
await this.setPerms(result, staff);
await setCourseInfo({ data: result });
}
return result;

View File

@ -3,6 +3,7 @@ import {
EnrollmentStatus,
Post,
PostType,
SectionDto,
UserProfile,
VisitType,
} from '@nice/common';
@ -123,3 +124,43 @@ export async function updateCourseEnrollmentStats(courseId: string) {
},
});
}
export async function setCourseInfo({ data }: { data: Post }) {
// await db.term
if (data?.type === PostType.COURSE) {
const ancestries = await db.postAncestry.findMany({
where: {
ancestorId: data.id,
},
select: {
id: true,
descendant: true,
},
});
const descendants = ancestries.map((ancestry) => ancestry.descendant);
const sections: SectionDto[] = descendants
.filter((descendant) => {
return (
descendant.type === PostType.SECTION &&
descendant.parentId === data.id
);
})
.map((section) => ({
...section,
lectures: [],
}));
const lectures = descendants.filter((descendant) => {
return (
descendant.type === PostType.LECTURE &&
sections.map((section) => section.id).includes(descendant.parentId)
);
});
sections.forEach((section) => {
section.lectures = lectures.filter(
(lecture) => lecture.parentId === section.id,
);
});
Object.assign(data, { sections });
}
}

View File

@ -21,7 +21,6 @@ export class GenDevService {
deptStaffRecord: Record<string, Staff[]> = {};
terms: Record<TaxonomySlug, Term[]> = {
[TaxonomySlug.CATEGORY]: [],
[TaxonomySlug.UNIT]: [],
[TaxonomySlug.TAG]: [],
[TaxonomySlug.LEVEL]: [],
};
@ -36,7 +35,7 @@ export class GenDevService {
private readonly departmentService: DepartmentService,
private readonly staffService: StaffService,
private readonly termService: TermService,
) {}
) { }
async genDataEvent() {
EventBus.emit('genDataEvent', { type: 'start' });
try {
@ -62,7 +61,7 @@ export class GenDevService {
const domains = this.depts.filter((item) => item.isDomain);
for (const domain of domains) {
await this.createTerms(domain, TaxonomySlug.CATEGORY, depth, count);
await this.createTerms(domain, TaxonomySlug.UNIT, depth, count);
// await this.createTerms(domain, TaxonomySlug.UNIT, depth, count);
}
}
const termCount = await db.term.count();

View File

@ -1,2 +1,5 @@
VITE_APP_TUS_URL=http://localhost:8080
VITE_APP_API_URL=http://localhost:3000
VITE_APP_SERVER_IP=192.168.252.239
VITE_APP_SERVER_PORT=3000
VITE_APP_FILE_PORT=80
VITE_APP_VERSION=0.3.0
VITE_APP_APP_NAME=MOOC

View File

@ -14,7 +14,6 @@ import { Toaster } from 'react-hot-toast';
dayjs.locale("zh-cn");
function App() {
return (
<>
<AuthProvider>

View File

@ -1,11 +1,41 @@
/**
* -
* 功能: 捕获React Router路由层级错误并展示可视化错误信息
* :
* -
* -
* -
*/
import { useRouteError } from "react-router-dom";
/**
*
* @核心功能
* @设计模式 UI展示
* @使用示例 React Router的RouterProvider中配置errorElement={<ErrorPage/>}
*/
export default function ErrorPage() {
// 使用React Router提供的Hook获取路由错误对象
// 类型定义为any以兼容React Router不同版本的类型差异
const error: any = useRouteError();
return <div className=" flex justify-center items-center pt-64 ">
<div className=" flex flex-col gap-4">
<div className=" text-xl font-bold text-primary">?...</div>
<div className=" text-tertiary" >{error?.statusText || error?.message}</div>
return (
// 主容器: 基于Flex的垂直水平双居中布局
// pt-64: 顶部留白实现视觉层次结构
<div className="flex justify-center items-center pt-64">
{/* 内容区块: 采用纵向弹性布局控制内部元素间距 */}
<div className="flex flex-col gap-4">
{/* 主标题: 强调性文字样式配置 */}
<div className="text-xl font-bold text-primary">
?...
</div>
{/* 错误详情: 动态渲染错误信息,实现优雅降级策略 */}
{/* 使用可选链操作符防止未定义错误,信息优先级: statusText > message */}
<div className="text-tertiary">
{error?.statusText || error?.message}
</div>
</div>
</div>
)
}

View File

@ -2,7 +2,7 @@ import CourseDetail from "@web/src/components/models/course/detail/CourseDetail"
import { useParams } from "react-router-dom";
export function CourseDetailPage() {
const { id } = useParams();
const { id, lectureId } = useParams();
console.log("Course ID:", id);
return <CourseDetail id={id}></CourseDetail>;
return <CourseDetail id={id} lectureId={lectureId}></CourseDetail>;
}

View File

@ -1,17 +1,45 @@
import { useState, useMemo } from 'react';
import { mockCourses } from './mockData';
import FilterSection from './components/FilterSection';
import CourseList from './components/CourseList';
import { useState, useMemo } from "react";
import { mockCourses } from "./mockData";
import FilterSection from "./components/FilterSection";
import CourseList from "./components/CourseList";
import { api } from "@nice/client";
import { LectureType, PostType } from "@nice/common";
export default function CoursesPage() {
const [currentPage, setCurrentPage] = useState(1);
const [selectedCategory, setSelectedCategory] = useState('');
const [selectedLevel, setSelectedLevel] = useState('');
const [selectedCategory, setSelectedCategory] = useState("");
const [selectedLevel, setSelectedLevel] = useState("");
const pageSize = 12;
const { data, isLoading } = api.post.findManyWithPagination.useQuery({
where: {
type: PostType.COURSE,
terms: {
some: {
AND: [
...(selectedCategory
? [
{
name: selectedCategory,
},
]
: []),
...(selectedLevel
? [
{
name: selectedLevel,
},
]
: []),
],
},
},
},
});
const filteredCourses = useMemo(() => {
return mockCourses.filter(course => {
const matchCategory = !selectedCategory || course.category === selectedCategory;
return mockCourses.filter((course) => {
const matchCategory =
!selectedCategory || course.category === selectedCategory;
const matchLevel = !selectedLevel || course.level === selectedLevel;
return matchCategory && matchLevel;
});
@ -24,7 +52,7 @@ export default function CoursesPage() {
const handlePageChange = (page: number) => {
setCurrentPage(page);
window.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: "smooth" });
};
return (
@ -37,11 +65,11 @@ export default function CoursesPage() {
<FilterSection
selectedCategory={selectedCategory}
selectedLevel={selectedLevel}
onCategoryChange={category => {
onCategoryChange={(category) => {
setSelectedCategory(category);
setCurrentPage(1);
}}
onLevelChange={level => {
onLevelChange={(level) => {
setSelectedLevel(level);
setCurrentPage(1);
}}

View File

@ -2,6 +2,7 @@ import HeroSection from './components/HeroSection';
import CategorySection from './components/CategorySection';
import CoursesSection from './components/CoursesSection';
import FeaturedTeachersSection from './components/FeaturedTeachersSection';
import { TusUploader } from '@web/src/components/common/uploader/TusUploader';
const HomePage = () => {
const mockCourses = [
{
@ -105,6 +106,7 @@ const HomePage = () => {
return (
<div className="min-h-screen">
<HeroSection />
<TusUploader></TusUploader>
<CoursesSection
title="推荐课程"
description="最受欢迎的精品课程,助你快速成长"

View File

@ -1,15 +1,15 @@
import { useState } from 'react';
import { Input, Layout, Avatar, Button, Dropdown } from 'antd';
import { SearchOutlined, UserOutlined } from '@ant-design/icons';
import { useAuth } from '@web/src/providers/auth-provider';
import { useNavigate } from 'react-router-dom';
import { UserMenu } from './UserMenu';
import { NavigationMenu } from './NavigationMenu';
import { useState } from "react";
import { Input, Layout, Avatar, Button, Dropdown } from "antd";
import { EditFilled, SearchOutlined, UserOutlined } from "@ant-design/icons";
import { useAuth } from "@web/src/providers/auth-provider";
import { useNavigate } from "react-router-dom";
import { UserMenu } from "./UserMenu";
import { NavigationMenu } from "./NavigationMenu";
const { Header } = Layout;
export function MainHeader() {
const [searchValue, setSearchValue] = useState('');
const [searchValue, setSearchValue] = useState("");
const { isAuthenticated, user } = useAuth();
const navigate = useNavigate();
@ -18,9 +18,8 @@ export function MainHeader() {
<div className="w-full max-w-screen-2xl px-4 md:px-6 mx-auto 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"
>
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 />
@ -29,32 +28,43 @@ export function MainHeader() {
<div className="group relative">
<Input
size="large"
prefix={<SearchOutlined className="text-gray-400 group-hover:text-blue-500 transition-colors" />}
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 && (
<>
<Button
onClick={() => navigate("/course/editor")}
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 ? (
<Dropdown
overlay={<UserMenu />}
trigger={['click']}
placement="bottomRight"
>
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()}
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={() => navigate('/login')}
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 />}
>
icon={<UserOutlined />}>
</Button>
)}

View File

@ -1,6 +1,5 @@
import MindEditor from "@web/src/components/common/editor/MindEditor";
import MindElixir, { MindElixirInstance } from "mind-elixir";
import { useEffect, useRef } from "react";
export default function PathsPage() {
return <MindEditor></MindEditor>
return <MindEditor></MindEditor>;
}

View File

@ -1,6 +1,6 @@
import { MindElixirInstance } from "packages/mind-elixir-core/dist/types";
import { MindElixirInstance } from "mind-elixir";
import { useRef, useEffect } from "react";
import MindElixir from 'mind-elixir';
import MindElixir from "mind-elixir";
export default function MindEditor() {
const me = useRef<MindElixirInstance>();
@ -12,17 +12,15 @@ export default function MindEditor() {
contextMenu: true, // default true
toolBar: true, // default true
nodeMenu: true, // default true
keypress: true // default true
keypress: true, // default true
});
// instance.install(NodeMenu);
instance.init(MindElixir.new("新主题"));
me.current = instance;
}, []);
return <div >
return (
<div>
1
</div>
<div id="map" style={{ width: "100%" }} />
</div>
);
}

View File

@ -72,22 +72,7 @@ export function FormArrayField({
<Input
{...inputProps}
placeholder={placeholder}
style={{ width: "80%" }}
// suffix={
// inputProps.maxLength && (
// <Typography.Text type="secondary">
// {inputProps.maxLength -
// (
// Form.useWatch(
// [
// name,
// field.name,
// ]
// ) || ""
// ).length}
// </Typography.Text>
// )
// }
style={{ width: "100%" }}
onChange={(e) => {
// 更新 items 状态
const newItems = [...items];

View File

@ -0,0 +1,102 @@
import React, { useState } from "react";
import { Input, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
interface InputListProps {
initialValue?: string[];
onChange?: (value: string[]) => void;
placeholder?: string;
}
const InputList: React.FC<InputListProps> = ({
initialValue,
onChange,
placeholder = "请输入内容",
}) => {
// Internal state management with fallback to initial value or empty array
const [inputValues, setInputValues] = useState<string[]>(
initialValue && initialValue.length > 0 ? initialValue : [""]
);
// Handle individual input value change
const handleInputChange = (index: number, newValue: string) => {
const newValues = [...inputValues];
newValues[index] = newValue;
// Update internal state
setInputValues(newValues);
// Call external onChange if provided
onChange?.(newValues);
};
// Handle delete operation
const handleDelete = (index: number) => {
const newValues = inputValues.filter((_, i) => i !== index);
// Ensure at least one input remains
const finalValues = newValues.length === 0 ? [""] : newValues;
// Update internal state
setInputValues(finalValues);
// Call external onChange if provided
onChange?.(finalValues);
};
// Add new input field
const handleAdd = () => {
const newValues = [...inputValues, ""];
// Update internal state
setInputValues(newValues);
// Call external onChange if provided
onChange?.(newValues);
};
return (
<div className="space-y-2">
{inputValues.map((item, index) => (
<div key={index} className="flex items-center space-x-2 group">
<Input
value={item}
onChange={(e) =>
handleInputChange(index, e.target.value)
}
placeholder={placeholder}
className="flex-grow"
/>
{inputValues.length > 1 && (
<Button
type="text"
icon={<DeleteOutlined />}
danger
className="opacity-0 group-hover:opacity-100"
onClick={() => handleDelete(index)}
/>
)}
</div>
))}
<div className="flex items-center space-x-2 group">
<Button
type="dashed"
block
onClick={handleAdd}
className="w-full">
</Button>
{inputValues.length > 1 && (
<Button
type="text"
icon={<DeleteOutlined />}
danger
className="opacity-0"
/>
)}
</div>
</div>
);
};
export default InputList;

View File

@ -5,12 +5,8 @@ import {
DeleteOutlined,
} from "@ant-design/icons";
import { Upload, Progress, Button } from "antd";
import type { UploadFile } from "antd";
import { useTusUpload } from "@web/src/hooks/useTusUpload";
import toast from "react-hot-toast";
import { getCompressedImageUrl } from "@nice/utils";
import { api } from "@nice/client";
export interface TusUploaderProps {
value?: string[];
onChange?: (value: string[]) => void;
@ -30,16 +26,7 @@ export const TusUploader = ({
onChange,
multiple = true,
}: TusUploaderProps) => {
const { data: files } = api.resource.findMany.useQuery({
where: {
fileId: { in: value },
},
select: {
id: true,
fileId: true,
title: true,
},
});
const { handleFileUpload, uploadProgress } = useTusUpload();
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([]);
const [completedFiles, setCompletedFiles] = useState<UploadingFile[]>(
@ -74,6 +61,7 @@ export const TusUploader = ({
const handleBeforeUpload = useCallback(
(file: File) => {
const fileKey = `${file.name}-${Date.now()}`;
setUploadingFiles((prev) => [
@ -151,7 +139,7 @@ export const TusUploader = ({
name="files"
multiple={multiple}
showUploadList={false}
style={{ background: "transparent", borderStyle: "none" }}
beforeUpload={handleBeforeUpload}>
<p className="ant-upload-drag-icon">
<UploadOutlined />

View File

@ -1,7 +1,13 @@
import { CourseDetailProvider } from "./CourseDetailContext";
import CourseDetailLayout from "./CourseDetailLayout";
export default function CourseDetail({ id }: { id?: string }) {
export default function CourseDetail({
id,
lectureId,
}: {
id?: string;
lectureId?: string;
}) {
const iframeStyle = {
width: "50%",
height: "100vh",

View File

@ -1,11 +1,12 @@
import { api,} from "@nice/client";
import { courseDetailSelect, CourseDto } from "@nice/common";
import React, { createContext, ReactNode, useState } from "react";
import { api } from "@nice/client";
import { courseDetailSelect, CourseDto, Lecture } from "@nice/common";
import React, { createContext, ReactNode, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
interface CourseDetailContextType {
editId?: string; // 添加 editId
course?: CourseDto;
lecture?: Lecture;
selectedLectureId?: string | undefined;
setSelectedLectureId?: React.Dispatch<React.SetStateAction<string>>;
isLoading?: boolean;
@ -22,12 +23,13 @@ export function CourseDetailProvider({
children,
editId,
}: CourseFormProviderProps) {
const navigate = useNavigate();
const { data: course, isLoading }: { data: CourseDto; isLoading: boolean } =
api.course.findFirst.useQuery(
(api.post as any).findFirst.useQuery(
{
where: { id: editId },
include: {
sections: { include: { lectures: true } },
// sections: { include: { lectures: true } },
enrollments: true,
},
},
@ -36,12 +38,24 @@ export function CourseDetailProvider({
const [selectedLectureId, setSelectedLectureId] = useState<
string | undefined
>(undefined);
const { data: lecture, isLoading: lectureIsLoading } = (
api.post as any
).findFirst.useQuery(
{
where: { id: selectedLectureId },
},
{ enabled: Boolean(editId) }
);
useEffect(() => {
navigate(`/course/${editId}/detail/${selectedLectureId}`);
}, [selectedLectureId, editId]);
const [isHeaderVisible, setIsHeaderVisible] = useState(true); // 新增
return (
<CourseDetailContext.Provider
value={{
editId,
course,
lecture,
selectedLectureId,
setSelectedLectureId,
isLoading,

View File

@ -1,21 +1,23 @@
// components/CourseDetailDisplayArea.tsx
import { motion, useScroll, useTransform } from "framer-motion";
import React from "react";
import React, { useContext } from "react";
import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer";
import { CourseDetailDescription } from "./CourseDetailDescription/CourseDetailDescription";
import { Course } from "@nice/common";
import { Course, PostType } from "@nice/common";
import { CourseDetailContext } from "./CourseDetailContext";
interface CourseDetailDisplayAreaProps {
course: Course;
// course: Course;
videoSrc?: string;
videoPoster?: string;
isLoading?: boolean;
// isLoading?: boolean;
}
export const CourseDetailDisplayArea: React.FC<
CourseDetailDisplayAreaProps
> = ({ course, videoSrc, videoPoster, isLoading = false }) => {
> = ({ videoSrc, videoPoster }) => {
// 创建滚动动画效果
const { course, isLoading, lecture } = useContext(CourseDetailContext);
const { scrollY } = useScroll();
const videoScale = useTransform(scrollY, [0, 200], [1, 0.8]);
const videoOpacity = useTransform(scrollY, [0, 200], [1, 0.8]);
@ -25,16 +27,15 @@ export const CourseDetailDisplayArea: React.FC<
{/* 固定的视频区域 */}
{/* 移除 sticky 定位,让视频区域随页面滚动 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
style={{
opacity: videoOpacity,
}}
className="w-full bg-black">
{lecture.type === PostType.LECTURE && (
<div className=" w-full ">
<VideoPlayer src={videoSrc} poster={videoPoster} />
</div>
)}
</motion.div>
{/* 课程内容区域 */}

View File

@ -2,12 +2,13 @@
import { motion, useScroll, useTransform } from "framer-motion";
import { useContext, useEffect, useState } from "react";
import { CourseDetailContext } from "../CourseDetailContext";
import { Button } from "antd";
export const CourseDetailHeader = () => {
const { scrollY } = useScroll();
const [lastScrollY, setLastScrollY] = useState(0);
const { course, isHeaderVisible, setIsHeaderVisible } =
const { course, isHeaderVisible, setIsHeaderVisible, lecture } =
useContext(CourseDetailContext);
useEffect(() => {
const updateHeader = () => {
@ -43,6 +44,12 @@ export const CourseDetailHeader = () => {
<div className="flex items-center space-x-4">
<h1 className="text-white text-xl ">{course?.title}</h1>
</div>
<Button
onClick={() => {
console.log(lecture);
}}>
123
</Button>
<nav className="flex items-center space-x-4">
{/* 添加你的导航项目 */}
<button className="px-4 py-2 rounded-full bg-blue-500 text-white hover:bg-blue-600 transition-colors">

View File

@ -5,10 +5,16 @@ import { CourseDetailContext } from "./CourseDetailContext";
import CourseDetailDisplayArea from "./CourseDetailDisplayArea";
import { CourseSyllabus } from "./CourseSyllabus/CourseSyllabus";
import CourseDetailHeader from "./CourseDetailHeader/CourseDetailHeader";
import { Button } from "antd";
export default function CourseDetailLayout() {
const { course, selectedLectureId, isLoading, setSelectedLectureId } =
useContext(CourseDetailContext);
const {
course,
selectedLectureId,
lecture,
isLoading,
setSelectedLectureId,
} = useContext(CourseDetailContext);
const handleLectureClick = (lectureId: string) => {
setSelectedLectureId(lectureId);
@ -16,7 +22,9 @@ export default function CourseDetailLayout() {
const [isSyllabusOpen, setIsSyllabusOpen] = useState(false);
return (
<div className="relative">
<CourseDetailHeader /> {/* 添加 Header 组件 */}
<CourseDetailHeader />
{/* 添加 Header 组件 */}
{/* 主内容区域 */}
{/* 为了防止 Header 覆盖内容,添加上边距 */}
<div className="pt-16">
@ -29,8 +37,8 @@ export default function CourseDetailLayout() {
transition={{ type: "spring", stiffness: 300, damping: 30 }}
className="relative">
<CourseDetailDisplayArea
course={course}
isLoading={isLoading}
// course={course}
// isLoading={isLoading}
videoSrc="https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"
videoPoster="https://picsum.photos/800/450"
/>

View File

@ -7,11 +7,12 @@ import {
import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/24/outline";
import React, { useState, useRef, useContext } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { SectionDto } from "@nice/common";
import { SectionDto, TaxonomySlug } from "@nice/common";
import { SyllabusHeader } from "./SyllabusHeader";
import { SectionItem } from "./SectionItem";
import { CollapsedButton } from "./CollapsedButton";
import { CourseDetailContext } from "../CourseDetailContext";
import { api } from "@nice/client";
interface CourseSyllabusProps {
sections: SectionDto[];
@ -29,7 +30,11 @@ export const CourseSyllabus: React.FC<CourseSyllabusProps> = ({
const { isHeaderVisible } = useContext(CourseDetailContext);
const [expandedSections, setExpandedSections] = useState<string[]>([]);
const sectionRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// api.term.findMany.useQuery({
// where: {
// taxonomy: { slug: TaxonomySlug.CATEGORY },
// },
// });
const toggleSection = (sectionId: string) => {
setExpandedSections((prev) =>
prev.includes(sectionId)

View File

@ -1,9 +1,8 @@
// components/CourseSyllabus/LectureItem.tsx
import { Lecture } from "@nice/common";
import { Lecture, LectureType } from "@nice/common";
import React from "react";
import { motion } from "framer-motion";
import { ClockIcon, PlayCircleIcon } from "@heroicons/react/24/outline";
import { ClockCircleOutlined, FileTextOutlined, PlayCircleOutlined } from "@ant-design/icons"; // 使用 Ant Design 图标
interface LectureItemProps {
lecture: Lecture;
@ -14,23 +13,24 @@ export const LectureItem: React.FC<LectureItemProps> = ({
lecture,
onClick,
}) => (
<motion.button
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
className="w-full flex items-center gap-4 p-4 hover:bg-gray-50 text-left transition-colors"
<div
className="w-full flex items-center gap-4 p-4 hover:bg-gray-50 text-left transition-colors cursor-pointer"
onClick={() => onClick(lecture.id)}>
<PlayCircleIcon className="w-5 h-5 text-blue-500 flex-shrink-0" />
{lecture.type === LectureType.VIDEO && (
<PlayCircleOutlined className="w-5 h-5 text-blue-500 flex-shrink-0" />
)}
{lecture.type === LectureType.ARTICLE && (
<FileTextOutlined className="w-5 h-5 text-blue-500 flex-shrink-0" /> // 为文章类型添加图标
)}
<div className="flex-grow">
<h4 className="font-medium text-gray-800">{lecture.title}</h4>
{lecture.description && (
<p className="text-sm text-gray-500 mt-1">
{lecture.description}
</p>
{lecture.subTitle && (
<p className="text-sm text-gray-500 mt-1">{lecture.subTitle}</p>
)}
</div>
<div className="flex items-center gap-1 text-sm text-gray-500">
<ClockIcon className="w-4 h-4" />
<ClockCircleOutlined className="w-4 h-4" />
<span>{lecture.duration}</span>
</div>
</motion.button>
</div>
);

View File

@ -33,8 +33,8 @@ export const SectionItem = React.forwardRef<HTMLDivElement, SectionItemProps>(
{section.title}
</h3>
<p className="text-sm text-gray-500">
{section.totalLectures} ·{" "}
{Math.floor(section.totalDuration / 60)}
{section?.lectures?.length} ·{" "}
{/* {Math.floor(section?.totalDuration / 60)}分钟 */}
</p>
</div>
</div>

View File

@ -43,7 +43,12 @@ export function CourseFormProvider({
const [form] = Form.useForm<CourseFormData>();
const { create, update, createCourse } = usePost();
const { data: course }: { data: CourseDto } = api.post.findFirst.useQuery(
{ where: { id: editId } },
{
where: { id: editId },
include: {
terms: true,
},
},
{ enabled: Boolean(editId) }
);
const {
@ -51,7 +56,7 @@ export function CourseFormProvider({
}: {
data: Taxonomy[];
} = api.taxonomy.getAll.useQuery({
// type: ObjectType.COURSE,
type: ObjectType.COURSE,
});
const navigate = useNavigate();
@ -65,6 +70,9 @@ export function CourseFormProvider({
requirements: course?.meta?.requirements,
objectives: course?.meta?.objectives,
};
course.terms?.forEach((term) => {
formData[term.taxonomyId] = term.id; // 假设 taxonomyName 是您在 Form.Item 中使用的 name
});
form.setFieldsValue(formData);
}
}, [course, form]);
@ -72,13 +80,24 @@ export function CourseFormProvider({
const onSubmit = async (values: CourseFormData) => {
console.log(values);
const sections = values?.sections || [];
const termIds = taxonomies
.map((tax) => values[tax.id]) // 获取每个 taxonomy 对应的选中值
.filter((id) => id); // 过滤掉空值
const formattedValues = {
...values,
meta: {
requirements: values.requirements,
objectives: values.objectives,
},
terms: {
connect: termIds.map((id) => ({ id })), // 转换成 connect 格式
},
};
// 删除原始的 taxonomy 字段
taxonomies.forEach((tax) => {
delete formattedValues[tax.id];
});
delete formattedValues.requirements;
delete formattedValues.objectives;
delete formattedValues.sections;

View File

@ -3,6 +3,7 @@ import { CourseLevel, CourseLevelLabel } from "@nice/common";
import { convertToOptions } from "@nice/client";
import TermSelect from "../../../term/term-select";
import { useCourseEditor } from "../context/CourseEditorContext";
import AvatarUploader from "@web/src/components/common/uploader/AvatarUploader";
const { TextArea } = Input;
@ -14,6 +15,7 @@ export function CourseBasicForm() {
value: key as CourseLevel,
})
);
const { form, taxonomies } = useCourseEditor();
return (
<div className="max-w-2xl mx-auto space-y-6 p-6">
@ -26,14 +28,12 @@ export function CourseBasicForm() {
]}>
<Input placeholder="请输入课程标题" />
</Form.Item>
<Form.Item
name="subTitle"
label="课程副标题"
rules={[{ max: 10, message: "副标题最多10个字符" }]}>
<Input placeholder="请输入课程副标题" />
</Form.Item>
<Form.Item name="content" label="课程描述">
<TextArea
placeholder="请输入课程描述"
@ -50,14 +50,13 @@ export function CourseBasicForm() {
},
]}
label={tax.name}
name={tax.name}
name={tax.id}
key={index}>
<TermSelect taxonomyId={tax.id}></TermSelect>
<TermSelect
placeholder={`请选择${tax.name}`}
taxonomyId={tax.id}></TermSelect>
</Form.Item>
))}
{/* <Form.Item name="level" label="">
<Select placeholder="请选择难度等级" options={levelOptions} />
</Form.Item> */}
</div>
);
}

View File

@ -1,604 +0,0 @@
import {
PlusOutlined,
DragOutlined,
DeleteOutlined,
CaretRightOutlined,
SaveOutlined,
} from "@ant-design/icons";
import {
Form,
Alert,
Button,
Input,
Select,
Space,
Collapse,
message,
} from "antd";
import React, { useCallback, useEffect, useState } from "react";
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from "@dnd-kit/core";
import { api, emitDataChange } from "@nice/client";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "../../../../common/editor/quill/QuillEditor";
import { TusUploader } from "../../../../common/uploader/TusUploader";
import { Lecture, LectureType, PostType } from "@nice/common";
import { useCourseEditor } from "../context/CourseEditorContext";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";
interface SectionData {
id: string;
title: string;
content?: string;
courseId?: string;
}
interface LectureData {
id: string;
title: string;
meta?: {
type?: LectureType;
fieldIds?: [];
};
content?: string;
sectionId?: string;
}
const CourseContentFormHeader = () => (
<Alert
type="info"
message="创建您的课程大纲"
description={
<>
<p>,:</p>
<ul className="mt-2 list-disc list-inside">
<li></li>
<li> 3-7 </li>
<li></li>
</ul>
</>
}
className="mb-8"
/>
);
const CourseSectionEmpty = () => (
<div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed">
<div className="text-gray-500">
<PlusOutlined className="text-4xl mb-4" />
<h3 className="text-lg font-medium mb-2"></h3>
<p className="text-sm"></p>
</div>
</div>
);
interface SortableSectionProps {
courseId?: string;
field: SectionData;
remove: () => void;
children: React.ReactNode;
}
const SortableSection: React.FC<SortableSectionProps> = ({
field,
remove,
courseId,
children,
}) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: field?.id });
const [form] = Form.useForm();
const [editing, setEditing] = useState(field.id ? false : true);
const [loading, setLoading] = useState(false);
const { create, update } = usePost();
const handleSave = async () => {
if (!courseId) {
toast.error("课程未创建,请先填写课程基本信息完成创建");
return;
}
try {
setLoading(true);
const values = await form.validateFields();
let result;
try {
if (!field?.id) {
result = await create.mutateAsync({
data: {
title: values?.title,
type: PostType.SECTION,
parentId: courseId,
},
});
} else {
result = await update.mutateAsync({
data: {
title: values?.title,
},
});
}
} catch (err) {
console.log(err);
}
field.id = result.id;
setEditing(false);
message.success("保存成功");
} catch (error) {
console.log(error);
message.error("保存失败");
} finally {
setLoading(false);
}
};
const style = {
transform: CSS.Transform.toString(transform),
transition,
backgroundColor: isDragging ? "#f5f5f5" : undefined,
};
return (
<div ref={setNodeRef} style={style} className="mb-4">
<Collapse>
<Collapse.Panel
header={
editing ? (
<Form
form={form}
className="flex items-center gap-4">
<Form.Item
name="title"
className="mb-0 flex-1"
initialValue={field?.title}>
<Input placeholder="章节标题" />
</Form.Item>
<Space>
<Button
onClick={handleSave}
loading={loading}
icon={<SaveOutlined />}
type="primary">
</Button>
<Button
onClick={() => {
setEditing(false);
if (!field?.id) {
remove();
}
}}>
</Button>
</Space>
</Form>
) : (
<div className="flex items-center justify-between">
<Space>
<DragOutlined
{...attributes}
{...listeners}
className="cursor-move"
/>
<span>{field.title || "未命名章节"}</span>
</Space>
<Space>
<Button
type="link"
onClick={() => setEditing(true)}>
</Button>
<Button type="link" danger onClick={remove}>
</Button>
</Space>
</div>
)
}
key={field.id || "new"}>
{children}
</Collapse.Panel>
</Collapse>
</div>
);
};
interface SortableLectureProps {
field: LectureData;
remove: () => void;
sectionFieldKey: string;
}
const SortableLecture: React.FC<SortableLectureProps> = ({
field,
remove,
sectionFieldKey,
}) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: field?.id });
const { create, update } = usePost();
const [form] = Form.useForm();
const [editing, setEditing] = useState(field?.id ? false : true);
const [loading, setLoading] = useState(false);
const lectureType =
Form.useWatch(["meta", "type"], form) || LectureType.ARTICLE;
const handleSave = async () => {
try {
setLoading(true);
const values = await form.validateFields();
let result;
try {
if (!field.id) {
result = await create.mutateAsync({
data: {
parentId: sectionFieldKey,
type: PostType.LECTURE,
title: values?.title,
meta: {
type: values?.meta?.type,
fileIds: values?.meta?.fileIds,
},
resources: {
connect: (values?.meta?.fileIds || []).map(
(fileId) => ({
fileId,
})
),
},
content: values?.content,
},
});
} else {
result = await update.mutateAsync({
where: {
id: field?.id,
},
data: {
title: values?.title,
meta: {
type: values?.meta?.type,
fieldIds: values?.meta?.fileIds,
},
resources: {
connect: (values?.meta?.fileIds || []).map(
(fileId) => ({
fileId,
})
),
},
content: values?.content,
},
});
}
} catch (err) {
console.log(err);
}
field.id = result.id;
setEditing(false);
message.success("保存成功");
} catch (error) {
message.error("保存失败");
} finally {
setLoading(false);
}
};
const style = {
transform: CSS.Transform.toString(transform),
transition,
borderBottom: "1px solid #f0f0f0",
backgroundColor: isDragging ? "#f5f5f5" : undefined,
};
return (
<div ref={setNodeRef} style={style} className="p-4">
{editing ? (
<Form form={form} initialValues={field}>
<div className="flex gap-4">
<Form.Item
name="title"
initialValue={field?.title}
className="mb-0 flex-1"
rules={[{ required: true }]}>
<Input placeholder="课时标题" />
</Form.Item>
<Form.Item
name={["meta", "type"]}
className="mb-0 w-32"
rules={[{ required: true }]}>
<Select
placeholder="选择类型"
options={[
{ label: "视频", value: LectureType.VIDEO },
{
label: "文章",
value: LectureType.ARTICLE,
},
]}
/>
</Form.Item>
</div>
<div className="mt-4 flex flex-1 ">
{lectureType === LectureType.VIDEO ? (
<Form.Item
name={["meta", "fileIds"]}
className="mb-0 flex-1"
rules={[{ required: true }]}>
<TusUploader multiple={false} />
</Form.Item>
) : (
<Form.Item
name="content"
className="mb-0 flex-1"
rules={[{ required: true }]}>
<QuillEditor />
</Form.Item>
)}
</div>
<div className="mt-4 flex justify-end gap-2">
<Button
onClick={handleSave}
loading={loading}
type="primary"
icon={<SaveOutlined />}>
</Button>
<Button
onClick={() => {
setEditing(false);
if (!field?.id) {
remove();
}
}}>
</Button>
</div>
</Form>
) : (
<div className="flex items-center justify-between">
<Space>
<DragOutlined
{...attributes}
{...listeners}
className="cursor-move"
/>
<CaretRightOutlined />
<span>{field?.title || "未命名课时"}</span>
</Space>
<Space>
<Button type="link" onClick={() => setEditing(true)}>
</Button>
<Button type="link" danger onClick={remove}>
</Button>
</Space>
</div>
)}
</div>
);
};
interface LectureListProps {
field: SectionData;
sectionId: string;
}
const LectureList: React.FC<LectureListProps> = ({ field, sectionId }) => {
const { softDeleteByIds } = usePost();
const { data: lectures = [], isLoading } = (
api.post.findMany as any
).useQuery(
{
where: {
parentId: sectionId,
type: PostType.LECTURE,
deletedAt: null,
},
},
{
enabled: !!sectionId,
}
);
useEffect(() => {
if (lectures && !isLoading) {
setItems(lectures);
}
}, [lectures, isLoading]);
const [items, setItems] = useState<LectureData[]>(lectures);
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
setItems((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over.id);
return arrayMove(items, oldIndex, newIndex);
});
};
return (
<div className="pl-8">
<div
onClick={() => {
console.log(lectures);
}}>
123
</div>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}>
<SortableContext
items={items}
strategy={verticalListSortingStrategy}>
{items.map((lecture) => (
<SortableLecture
key={lecture.id}
field={lecture}
remove={async () => {
if (lecture?.id) {
await softDeleteByIds.mutateAsync({
ids: [lecture.id],
});
}
setItems(lectures);
}}
sectionFieldKey={sectionId}
/>
))}
</SortableContext>
</DndContext>
<Button
type="dashed"
block
icon={<PlusOutlined />}
className="mt-4"
onClick={() => {
setItems([
...items.filter((item) => !!item.id),
{
id: null,
title: "",
meta: {
type: LectureType.ARTICLE,
},
},
]);
}}>
</Button>
</div>
);
};
const CourseContentForm: React.FC = () => {
const { editId } = useCourseEditor();
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const { softDeleteByIds } = usePost();
const { data: sections = [], isLoading } = api.post.findMany.useQuery(
{
where: {
parentId: editId,
type: PostType.SECTION,
deletedAt: null,
},
},
{
enabled: !!editId,
}
);
const [items, setItems] = useState<any[]>(sections);
useEffect(() => {
if (sections && !isLoading) {
setItems(sections);
}
}, [sections]);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
setItems((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over.id);
return arrayMove(items, oldIndex, newIndex);
});
};
return (
<div className="max-w-4xl mx-auto p-6">
<CourseContentFormHeader />
{items.length === 0 ? (
<CourseSectionEmpty />
) : (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}>
<SortableContext
items={items}
strategy={verticalListSortingStrategy}>
{items?.map((section, index) => (
<SortableSection
courseId={editId}
key={section.id}
field={section}
remove={async () => {
if (section?.id) {
await softDeleteByIds.mutateAsync({
ids: [section.id],
});
}
setItems(sections);
}}>
<LectureList
field={section}
sectionId={section.id}
/>
</SortableSection>
))}
</SortableContext>
</DndContext>
)}
<Button
type="dashed"
block
icon={<PlusOutlined />}
className="mt-4"
onClick={() => {
setItems([
...items.filter((item) => !!item.id),
{ id: null, title: "" },
]);
}}>
</Button>
</div>
);
};
export default CourseContentForm;

View File

@ -15,7 +15,7 @@ import {
Collapse,
message,
} from "antd";
import React, { useCallback, useEffect, useState } from "react";
import React, { useEffect, useState } from "react";
import {
DndContext,
closestCenter,
@ -33,15 +33,9 @@ import {
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { TusUploader } from "@web/src/components/common/uploader/TusUploader";
import { Lecture, LectureType, PostType } from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";
import { CourseContentFormHeader } from "./CourseContentFormHeader";
import { CourseSectionEmpty } from "./CourseSectionEmpty";
import { LectureData, SectionData } from "./interface";
import { SortableLecture } from "./SortableLecture";
@ -69,12 +63,16 @@ export const LectureList: React.FC<LectureListProps> = ({
enabled: !!sectionId,
}
);
// 用 lectures 初始化 items 状态
const [items, setItems] = useState<LectureData[]>(lectures);
// 当 lectures 变化时更新 items
useEffect(() => {
if (lectures && !isLoading) {
if (!isLoading) {
setItems(lectures);
}
}, [lectures, isLoading]);
const [items, setItems] = useState<LectureData[]>(lectures);
const sensors = useSensors(
useSensor(PointerSensor),
@ -96,12 +94,12 @@ export const LectureList: React.FC<LectureListProps> = ({
return (
<div className="pl-8">
<div
{/* <Button
onClick={() => {
console.log(lectures);
}}>
123
</div>
</Button> */}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
@ -132,8 +130,8 @@ export const LectureList: React.FC<LectureListProps> = ({
icon={<PlusOutlined />}
className="mt-4"
onClick={() => {
setItems([
...items.filter((item) => !!item.id),
setItems((prevItems) => [
...prevItems.filter((item) => !!item.id),
{
id: null,
title: "",

View File

@ -16,32 +16,11 @@ import {
message,
} from "antd";
import React, { useCallback, useEffect, useState } from "react";
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from "@dnd-kit/core";
import { api, emitDataChange } from "@nice/client";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { TusUploader } from "@web/src/components/common/uploader/TusUploader";
import { Lecture, LectureType, PostType } from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";
import { CourseContentFormHeader } from "./CourseContentFormHeader";
import { CourseSectionEmpty } from "./CourseSectionEmpty";
import { LectureData, SectionData } from "./interface";
interface SortableSectionProps {
courseId?: string;
@ -120,6 +99,7 @@ export const SortableSection: React.FC<SortableSectionProps> = ({
<div ref={setNodeRef} style={style} className="mb-4">
<Collapse>
<Collapse.Panel
collapsible={!field.id ? "disabled" : undefined} // 添加此行以禁用未创建章节的展开
header={
editing ? (
<Form

View File

@ -1,22 +1,19 @@
import { FormArrayField } from "@web/src/components/common/form/FormArrayField";
import { useFormContext } from "react-hook-form";
import { CourseFormData } from "../context/CourseEditorContext";
import InputList from "@web/src/components/common/input/InputList";
import { useState } from "react";
import { Form } from "antd";
export function CourseGoalForm() {
// const { register, formState: { errors }, watch, handleSubmit } = useFormContext<CourseFormData>();
return (
<form className="max-w-2xl mx-auto space-y-6 p-6">
<FormArrayField
name="requirements"
label="前置要求"
placeholder="添加要求"></FormArrayField>
<FormArrayField
name="objectives"
label="学习目标"
placeholder="添加目标"></FormArrayField>
</form>
<div className="max-w-2xl mx-auto space-y-6 p-6">
<Form.Item name="requirements" label="前置要求">
<InputList placeholder="请输入前置要求"></InputList>
</Form.Item>
<Form.Item name="objectives" label="学习目标">
<InputList placeholder="请输入学习目标"></InputList>
</Form.Item>
</div>
);
}

View File

@ -1,4 +1,4 @@
import { createContext, useMemo, useState } from "react";
import React, { createContext, useMemo, useState } from "react";
import { useAuth } from "@web/src/providers/auth-provider";
import { RolePerms } from "@nice/common";
import TaxonomyModal from "./taxonomy-modal";

View File

@ -42,7 +42,7 @@ export default function Speed() {
}}
className={`px-2 py-1 text-lg whitespace-nowrap ${
playbackSpeed === speed
? "text-primaryHover font-bold"
? "text-primary-500 font-bold"
: "text-white hover:text-primaryHover"
}`}>
{speed}x

View File

@ -2,7 +2,7 @@ export const env: {
APP_NAME: string;
SERVER_IP: string;
VERSION: string;
UPLOAD_PORT: string;
FILE_PORT: string;
SERVER_PORT: string;
} = {
APP_NAME: import.meta.env.PROD
@ -11,9 +11,9 @@ export const env: {
SERVER_IP: import.meta.env.PROD
? (window as any).env.VITE_APP_SERVER_IP
: import.meta.env.VITE_APP_SERVER_IP,
UPLOAD_PORT: import.meta.env.PROD
? (window as any).env.VITE_APP_UPLOAD_PORT
: import.meta.env.VITE_APP_UPLOAD_PORT,
FILE_PORT: import.meta.env.PROD
? (window as any).env.VITE_APP_FILE_PORT
: import.meta.env.VITE_APP_FILE_PORT,
SERVER_PORT: import.meta.env.PROD
? (window as any).env.VITE_APP_SERVER_PORT
: import.meta.env.VITE_APP_SERVER_PORT,

View File

@ -2,11 +2,6 @@ import { useState } from "react";
import * as tus from "tus-js-client";
import { env } from "../env";
import { getCompressedImageUrl } from "@nice/utils";
// useTusUpload.ts
interface UploadProgress {
fileId: string;
progress: number;
}
interface UploadResult {
compressedUrl: string;
@ -35,9 +30,7 @@ export function useTusUpload() {
if (uploadIndex === -1 || uploadIndex + 4 >= parts.length) {
throw new Error("Invalid upload URL format");
}
console.log(env.UPLOAD_PORT);
const resUrl = `http://${env.SERVER_IP}:${env.UPLOAD_PORT}/uploads/${parts.slice(uploadIndex + 1, uploadIndex + 6).join("/")}`;
const resUrl = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${parts.slice(uploadIndex + 1, uploadIndex + 6).join("/")}`;
return resUrl;
};
const handleFileUpload = async (
@ -46,11 +39,13 @@ export function useTusUpload() {
onError: (error: Error) => void,
fileKey: string // 添加文件唯一标识
) => {
// console.log()
setIsUploading(true);
setUploadProgress((prev) => ({ ...prev, [fileKey]: 0 }));
setUploadError(null);
try {
console.log(`http://${env.SERVER_IP}:${env.SERVER_PORT}/upload`);
const upload = new tus.Upload(file, {
endpoint: `http://${env.SERVER_IP}:${env.SERVER_PORT}/upload`,
retryDelays: [0, 1000, 3000, 5000],
@ -97,6 +92,7 @@ export function useTusUpload() {
onError: (error) => {
setIsUploading(false);
setUploadError(error.message);
console.log(error);
onError(error);
},
});

View File

@ -129,3 +129,4 @@
height: 600px;
width: 100%;
}

View File

@ -3,13 +3,9 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.js";
import "./index.css";
import { ModuleRegistry } from "@ag-grid-community/core";
import { LicenseManager } from "@ag-grid-enterprise/core";
import { ClientSideRowModelModule } from "@ag-grid-community/client-side-row-model";
ModuleRegistry.registerModules([ClientSideRowModelModule]);
LicenseManager.setLicenseKey(

View File

@ -57,11 +57,10 @@ export const routes: CustomRouteObject[] = [
{
index: true,
element: <HomePage />,
},
{
path: "paths",
element: <PathsPage></PathsPage>
element: <PathsPage></PathsPage>,
},
{
path: "courses",
@ -132,7 +131,7 @@ export const routes: CustomRouteObject[] = [
],
},
{
path: ":id?/detail", // 使用 ? 表示 id 参数是可选的
path: ":id?/detail/:lectureId?", // 使用 ? 表示 id 参数是可选的
element: <CourseDetailPage />,
},
],

View File

@ -5,7 +5,8 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "pnpm run --parallel dev"
"dev": "pnpm run --parallel dev",
"db:clear": "pnpm --filter common run db:clear"
},
"keywords": [],
"author": "insiinc",

View File

@ -45,6 +45,7 @@ model Term {
depts Department[] @relation("department_term")
hasChildren Boolean? @default(false) @map("has_children")
posts Post[] @relation("post_term")
@@index([name]) // 对name字段建立索引以加快基于name的查找速度
@@index([parentId]) // 对parentId字段建立索引以加快基于parentId的查找速度
@@map("term")
@ -198,7 +199,8 @@ model Post {
terms Term[] @relation("post_term")
order Float? @default(0) @map("order")
duration Int?
rating Int? @default(0)
// 索引
// 日期时间类型字段
createdAt DateTime @default(now()) @map("created_at")
publishedAt DateTime? @map("published_at") // 发布时间
@ -221,6 +223,7 @@ model Post {
watchableStaffs Staff[] @relation("post_watch_staff") // 可观看的员工列表,关联 Staff 模型
watchableDepts Department[] @relation("post_watch_dept") // 可观看的部门列表,关联 Department 模型
meta Json? // 封面url 视频url objectives具体的学习目标 rating评分Int
// 索引
@@index([type, domainId])
@@index([authorId, type])
@ -242,7 +245,6 @@ model PostAncestry {
relDepth Int @map("rel_depth")
ancestor Post? @relation("AncestorPosts", fields: [ancestorId], references: [id])
descendant Post @relation("DescendantPosts", fields: [descendantId], references: [id])
// 复合索引优化
// 索引建议
@@index([ancestorId]) // 针对祖先的查询
@ -302,8 +304,6 @@ model Visit {
@@map("visit")
}
model Enrollment {
id String @id @default(cuid()) @map("id")
status String @map("status")
@ -404,3 +404,19 @@ model NodeEdge {
@@index([targetId])
@@map("node_edge")
}
model Animal {
id String @id @default(cuid())
name String
age Int
gender Boolean
personId String?
person Person? @relation(fields: [personId], references: [id])
}
model Person {
id String @id @default(cuid())
name String
age Int
gender Boolean
animals Animal[]
}

View File

@ -1,5 +1,5 @@
import { Prisma } from "@prisma/client";
import { AppConfigSlug, RolePerms, TaxonomySlug } from "./enum";
import { AppConfigSlug, ObjectType, RolePerms, TaxonomySlug } from "./enum";
export const InitRoles: {
name: string;
@ -50,7 +50,11 @@ export const InitRoles: {
permissions: Object.keys(RolePerms) as RolePerms[],
},
];
export const InitTaxonomies: { name: string; slug: string }[] = [
export const InitTaxonomies: {
name: string;
slug: string;
objectType?: string[];
}[] = [
{
name: "分类",
slug: TaxonomySlug.CATEGORY,
@ -58,6 +62,7 @@ export const InitTaxonomies: { name: string; slug: string }[] = [
{
name: "难度等级",
slug: TaxonomySlug.LEVEL,
objectType: [ObjectType.COURSE],
},
// {
// name: "研判单元",

View File

@ -6,8 +6,8 @@ export enum PostType {
POST_COMMENT = "post_comment",
COURSE_REVIEW = "course_review",
COURSE = "couse",
LECTURE = "lecture",
SECTION = "section",
LECTURE = "lecture",
}
export enum LectureType {
VIDEO = "video",
@ -15,7 +15,6 @@ export enum LectureType {
}
export enum TaxonomySlug {
CATEGORY = "category",
UNIT = "unit",
TAG = "tag",
LEVEL = "level",
}

View File

@ -1,5 +1,13 @@
import { Post, Department, Staff, Enrollment } from "@prisma/client";
import {
Post,
Department,
Staff,
Enrollment,
Taxonomy,
Term,
} from "@prisma/client";
import { StaffDto } from "./staff";
import { TermDto } from "./term";
export type PostComment = {
id: string;
@ -63,4 +71,5 @@ export type Course = Post & {
export type CourseDto = Course & {
enrollments?: Enrollment[];
sections?: SectionDto[];
terms: Term[];
};