update teachers,

This commit is contained in:
louiscklaw
2025-05-08 14:37:48 +08:00
parent 367e58a8cf
commit 30f494fc35
15 changed files with 72 additions and 59 deletions

View File

@@ -1,11 +0,0 @@
# task
## instruction
with reference to `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/app/_helloworld/page.tsx`
with reference to `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/app/dashboard/lesson_types/edit/[typeId]/page.tsx`
please modify `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/app/dashboard/lesson_categories/edit/page.tsx`
please draft a tsx for showing error to user thanks,

View File

@@ -6,7 +6,7 @@
// //
import * as React from 'react'; import * as React from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { COL_TEACHERS } from '@/constants'; import { COL_USER_METAS } from '@/constants';
import { LoadingButton } from '@mui/lab'; import { LoadingButton } from '@mui/lab';
import Box from '@mui/material/Box'; import Box from '@mui/material/Box';
import Card from '@mui/material/Card'; import Card from '@mui/material/Card';
@@ -49,23 +49,30 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
const [currentPage, setCurrentPage] = React.useState<number>(0); const [currentPage, setCurrentPage] = React.useState<number>(0);
// //
const [recordCount, setRecordCount] = React.useState<number>(0); const [recordCount, setRecordCount] = React.useState<number>(0);
const [listOption, setListOption] = React.useState({}); const [listOption, setListOption] = React.useState({ filter: '' });
const [listSort, setListSort] = React.useState({}); const [listSort, setListSort] = React.useState({});
function isListOptionChanged() {
return JSON.stringify(listOption) === '{}';
}
// //
const reloadRows = async (): Promise<void> => { const reloadRows = async (): Promise<void> => {
try { try {
const listOptionTeacherOnly = isListOptionChanged()
? { filter: `role = "teacher"` }
: { filter: [listOption.filter, `role = "teacher"`].join(' && ') };
const models: ListResult<RecordModel> = await pb const models: ListResult<RecordModel> = await pb
.collection(COL_TEACHERS) .collection(COL_USER_METAS)
.getList(currentPage + 1, rowsPerPage, listOption); .getList(currentPage + 1, rowsPerPage, listOptionTeacherOnly);
const { items, totalItems } = models; const { items, totalItems } = models;
const tempLessonTypes: Teacher[] = items.map((lt) => { const tempTeacher: Teacher[] = items.map((lt) => {
return { ...defaultTeacher, ...lt }; return { ...defaultTeacher, ...lt };
}); });
setLessonCategoriesData(tempLessonTypes); setLessonCategoriesData(tempTeacher);
setRecordCount(totalItems); setRecordCount(totalItems);
setF(tempLessonTypes); setF(tempTeacher);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
setShowError({ setShowError({

View File

@@ -10,13 +10,14 @@ import { CaretDown as CaretDownIcon } from '@phosphor-icons/react/dist/ssr/Caret
import { CheckCircle as CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle'; import { CheckCircle as CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { Customer } from '@/components/dashboard/customer/type.d'; import type { Customer } from '@/components/dashboard/customer/type.d';
import { Teacher } from '@/components/dashboard/teacher/type.d';
// import type { CrCategory } from '@/components/dashboard/cr/categories/type'; // import type { CrCategory } from '@/components/dashboard/cr/categories/type';
function getImageUrlFrRecord(record: Customer): string { function getImageUrlFrRecord(record: Teacher): string {
// TODO: fix this // TODO: fix this
// `http://127.0.0.1:8090/api/files/${'record.collectionId'}/${'record.id'}/${'record.cat_image'}`; // `http://127.0.0.1:8090/api/files/${'record.collectionId'}/${'record.id'}/${'record.cat_image'}`;
return 'getImageUrlFrRecord(helloworld)'; return `http://127.0.0.1:8090/api/files/${record.collectionId}/${record.id}/${record.avatar}`;
} }
export default function SampleTitleCard({ lpModel }: { lpModel: Customer }): React.JSX.Element { export default function SampleTitleCard({ lpModel }: { lpModel: Customer }): React.JSX.Element {

View File

@@ -30,13 +30,13 @@ import BasicDetailCard from './BasicDetailCard';
import TitleCard from './TitleCard'; import TitleCard from './TitleCard';
import { defaultTeacher } from '@/components/dashboard/teacher/_constants'; import { defaultTeacher } from '@/components/dashboard/teacher/_constants';
import type { Teacher } from '@/components/dashboard/teacher/type.d'; import type { Teacher } from '@/components/dashboard/teacher/type.d';
import { COL_TEACHERS } from '@/constants'; import { COL_USER_METAS } from '@/constants';
export default function Page(): React.JSX.Element { export default function Page(): React.JSX.Element {
const { t } = useTranslation(); const { t } = useTranslation();
const router = useRouter(); const router = useRouter();
// //
const { customerId } = useParams<{ customerId: string }>(); const { id } = useParams<{ id: string }>();
// //
const [showLoading, setShowLoading] = React.useState<boolean>(true); const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState({ show: false, detail: '' }); const [showError, setShowError] = React.useState({ show: false, detail: '' });
@@ -48,9 +48,9 @@ export default function Page(): React.JSX.Element {
} }
React.useEffect(() => { React.useEffect(() => {
if (customerId) { if (id) {
pb.collection(COL_TEACHERS) pb.collection(COL_USER_METAS)
.getOne(customerId) .getOne(id)
.then((model: RecordModel) => { .then((model: RecordModel) => {
setShowLessonCategory({ ...defaultTeacher, ...model }); setShowLessonCategory({ ...defaultTeacher, ...model });
}) })
@@ -64,7 +64,8 @@ export default function Page(): React.JSX.Element {
setShowLoading(false); setShowLoading(false);
}); });
} }
}, [customerId]); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
// return <>{JSON.stringify({ showError, showLessonCategory }, null, 2)}</>; // return <>{JSON.stringify({ showError, showLessonCategory }, null, 2)}</>;

View File

@@ -5,18 +5,18 @@
- default value (defaultValue) - default value (defaultValue)
- empty value (emptyValue) - empty value (emptyValue)
- `customers-table.tsx` - `teachers-table.tsx`
- `confirm-delete-modal.tsx` - delete modal component when click delete button on list - `confirm-delete-modal.tsx` - delete modal component when click delete button on list
- `customers-filters.tsx` - `teachers-filters.tsx`
- `customers-pagination.tsx` - `teachers-pagination.tsx`
- `email-filter-popover.tsx` - `email-filter-popover.tsx`
- `phone-filter-popover.tsx` - `phone-filter-popover.tsx`
- `customers-selection-context.tsx` - `teachers-selection-context.tsx`
- `customer-create-form.tsx` - form to create a new customer - `teacher-create-form.tsx` - form to create a new teacher
- `customer-edit-form.tsx` - form to edit a existing customer - `teacher-edit-form.tsx` - form to edit an existing teacher
- `type.d.tsx` - contains type definition - `type.d.tsx` - contains type definition

View File

@@ -83,12 +83,12 @@ export default function ConfirmDeleteModal({
</Avatar> </Avatar>
<Stack spacing={3}> <Stack spacing={3}>
<Stack spacing={1}> <Stack spacing={1}>
<Typography variant="h5">{t('Delete Lesson Type ?')}</Typography> <Typography variant="h5">{t('Delete Teacher ?')}</Typography>
<Typography <Typography
color="text.secondary" color="text.secondary"
variant="body2" variant="body2"
> >
{t('Are you sure you want to delete lesson type ?')} {t('Are you sure you want to delete this teacher ?')}
</Typography> </Typography>
</Stack> </Stack>
<Stack <Stack

View File

@@ -4,7 +4,7 @@ import * as React from 'react';
import RouterLink from 'next/link'; import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation'; import { useParams, useRouter } from 'next/navigation';
// //
import { COL_TEACHERS } from '@/constants'; import { COL_TEACHERS, COL_USER_METAS } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab'; import { LoadingButton } from '@mui/lab';
// //
@@ -89,7 +89,7 @@ export function TeacherEditForm(): React.JSX.Element {
const router = useRouter(); const router = useRouter();
const { t } = useTranslation(['lp_categories']); const { t } = useTranslation(['lp_categories']);
const { customerId } = useParams<{ customerId: string }>(); const { id: teacherId } = useParams<{ id: string }>();
// //
const [isUpdating, setIsUpdating] = React.useState<boolean>(false); const [isUpdating, setIsUpdating] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(false); const [showLoading, setShowLoading] = React.useState<boolean>(false);
@@ -123,17 +123,17 @@ export function TeacherEditForm(): React.JSX.Element {
}; };
try { try {
await pb.collection(COL_TEACHERS).update(customerId, updateData); await pb.collection(COL_USER_METAS).update(teacherId, updateData);
toast.success('Customer updated successfully'); toast.success('Teacher updated successfully');
router.push(paths.dashboard.teachers.list); router.push(paths.dashboard.teachers.list);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
toast.error('Failed to update customer'); toast.error('Failed to update teacher');
} finally { } finally {
setIsUpdating(false); setIsUpdating(false);
} }
}, },
[customerId, router] [teacherId, router]
); );
const avatarInputRef = React.useRef<HTMLInputElement>(null); const avatarInputRef = React.useRef<HTMLInputElement>(null);
@@ -162,13 +162,13 @@ export function TeacherEditForm(): React.JSX.Element {
setShowLoading(true); setShowLoading(true);
try { try {
const result = await pb.collection(COL_TEACHERS).getOne(id); const result = await pb.collection(COL_USER_METAS).getOne(id);
reset({ ...defaultValues, ...result }); reset({ ...defaultValues, ...result });
console.log({ result }); console.log({ result });
if (result.avatar_file) { if (result.avatar) {
const fetchResult = await fetch( const fetchResult = await fetch(
`http://127.0.0.1:8090/api/files/${result.collectionId}/${result.id}/${result.avatar_file}` `http://127.0.0.1:8090/api/files/${result.collectionId}/${result.id}/${result.avatar}`
); );
const blob = await fetchResult.blob(); const blob = await fetchResult.blob();
const url = await fileToBase64(blob); const url = await fileToBase64(blob);
@@ -176,7 +176,7 @@ export function TeacherEditForm(): React.JSX.Element {
} }
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
toast.error('Failed to load customer data'); toast.error('Failed to load teacher data');
setShowError({ show: true, detail: JSON.stringify(error, null, 2) }); setShowError({ show: true, detail: JSON.stringify(error, null, 2) });
} finally { } finally {
setShowLoading(false); setShowLoading(false);
@@ -186,9 +186,9 @@ export function TeacherEditForm(): React.JSX.Element {
); );
React.useEffect(() => { React.useEffect(() => {
void loadExistingData(customerId); void loadExistingData(teacherId);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [customerId]); }, [teacherId]);
if (showLoading) return <FormLoading />; if (showLoading) return <FormLoading />;
if (showError.show) if (showError.show)

View File

@@ -4,7 +4,7 @@
// //
import * as React from 'react'; import * as React from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { getAllCustomersCount } from '@/db/Customers/GetAllCount'; import { getAllTeachersCount } from '@/db/Teachers/GetAllCount';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip'; import Chip from '@mui/material/Chip';
@@ -27,13 +27,15 @@ import GetPendingCount from '@/db/Customers/GetPendingCount';
import GetActiveCount from '@/db/Customers/GetActiveCount'; import GetActiveCount from '@/db/Customers/GetActiveCount';
import PhoneFilterPopover from './phone-filter-popover'; import PhoneFilterPopover from './phone-filter-popover';
import EmailFilterPopover from './email-filter-popover'; import EmailFilterPopover from './email-filter-popover';
import type { CustomersFiltersProps, Filters, SortDir } from './type.d'; import type { TeachersFiltersProps, Filters, SortDir } from './type.d';
import { logger } from '@/lib/default-logger';
export function TeachersFilters({ export function TeachersFilters({
filters = {}, filters = {},
sortDir = 'desc', sortDir = 'desc',
fullData, fullData,
}: CustomersFiltersProps): React.JSX.Element { //
}: TeachersFiltersProps): React.JSX.Element {
const { t } = useTranslation(); const { t } = useTranslation();
const { email, phone, status } = filters; const { email, phone, status } = filters;
@@ -129,7 +131,7 @@ export function TeachersFilters({
React.useEffect(() => { React.useEffect(() => {
const fetchCount = async (): Promise<void> => { const fetchCount = async (): Promise<void> => {
try { try {
const tc = await getAllCustomersCount(); const tc = await getAllTeachersCount();
setTotalCount(tc); setTotalCount(tc);
const bc = await GetBlockedCount(); const bc = await GetBlockedCount();
@@ -140,6 +142,7 @@ export function TeachersFilters({
setActiveCount(ac); setActiveCount(ac);
} catch (error) { } catch (error) {
// //
logger.error(error);
} }
}; };
void fetchCount(); void fetchCount();

View File

@@ -39,7 +39,10 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<Teacher
spacing={1} spacing={1}
sx={{ alignItems: 'center' }} sx={{ alignItems: 'center' }}
> >
<Avatar src={row.avatar} />{' '} <Avatar
src={`http://127.0.0.1:8090/api/files/${row.collectionId}/${row.id}/${row.avatar}`}
variant="rounded"
/>
<div> <div>
<Link <Link
color="inherit" color="inherit"

View File

@@ -5,15 +5,24 @@ export type SortDir = 'asc' | 'desc';
// RULES: core teacher data structure // RULES: core teacher data structure
export interface Teacher { export interface Teacher {
id: string;
name: string; name: string;
//
// NOTE: obslete "avatar" and use "avatar_file"
avatar?: string; avatar?: string;
avatar_file?: string;
//
email: string; email: string;
phone?: string; phone?: string;
quota: number; quota: number;
// status is obsoleted, replace by state
status: 'pending' | 'active' | 'blocked'; status: 'pending' | 'active' | 'blocked';
state: 'pending' | 'active' | 'blocked';
//
id: string;
createdAt: Date; createdAt: Date;
updatedAt?: Date; updatedAt?: Date;
collectionId: string;
} }
// RULES: form data structure for creating new teacher // RULES: form data structure for creating new teacher
@@ -63,7 +72,7 @@ export interface EditFormProps {
} }
// RULES: filter props for teacher search and filtering // RULES: filter props for teacher search and filtering
export interface CustomersFiltersProps { export interface TeachersFiltersProps {
filters?: Filters; filters?: Filters;
sortDir?: SortDir; sortDir?: SortDir;
fullData: Teacher[]; fullData: Teacher[];

View File

@@ -1,6 +1,6 @@
import { pb } from '@/lib/pb'; import { pb } from '@/lib/pb';
import { COL_TEACHERS } from '@/constants'; import { COL_USER_METAS } from '@/constants';
export async function deleteTeacher(id: string): Promise<boolean> { export async function deleteTeacher(id: string): Promise<boolean> {
return pb.collection(COL_TEACHERS).delete(id); return pb.collection(COL_USER_METAS).delete(id);
} }

View File

@@ -1,8 +1,8 @@
import { COL_TEACHERS } from '@/constants'; import { COL_TEACHERS, COL_USER_METAS } from '@/constants';
import { pb } from '@/lib/pb'; import { pb } from '@/lib/pb';
export default async function GetActiveCount(): Promise<number> { export default async function GetActiveCount(): Promise<number> {
const { totalItems: count } = await pb.collection(COL_TEACHERS).getList(1, 1, { const { totalItems: count } = await pb.collection(COL_USER_METAS).getList(1, 1, {
filter: 'status = "active"', filter: 'status = "active"',
}); });
return count; return count;

View File

@@ -1,7 +1,7 @@
import { pb } from '@/lib/pb'; import { pb } from '@/lib/pb';
import { COL_TEACHERS } from '@/constants'; import { COL_USER_METAS } from '@/constants';
export async function getAllTeachersCount(): Promise<number> { export async function getAllTeachersCount(): Promise<number> {
const result = await pb.collection(COL_TEACHERS).getList(1, 1); const result = await pb.collection(COL_USER_METAS).getList(1, 1, { filter: `role = "teacher"` });
return result.totalItems; return result.totalItems;
} }