update for lp_categories,

This commit is contained in:
louiscklaw
2025-04-21 05:16:30 +08:00
parent 3679924a6a
commit f65f6df660
60 changed files with 1919 additions and 1047 deletions

View File

@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -ex
reset
pnpm run typecheck:w

View File

@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -ex
reset
pnpm run build

View File

@@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -ex
npx nodemon --ext tsx,ts --exec "reset && pnpm run build"

View File

@@ -1,7 +1,7 @@
'use client';
import * as React from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useRouter } from 'next/navigation';
import Avatar from '@mui/material/Avatar';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
@@ -15,7 +15,6 @@ import { PencilSimple as PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr
import { User as UserIcon } from '@phosphor-icons/react/dist/ssr/User';
import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
import { PropertyItem } from '@/components/core/property-item';
import { PropertyList } from '@/components/core/property-list';
@@ -27,7 +26,6 @@ export default function BasicDetailCard({
handleEditClick: () => void;
}): React.JSX.Element {
const { t } = useTranslation();
const router = useRouter();
return (
<Card>
@@ -48,10 +46,23 @@ export default function BasicDetailCard({
}
title={t('list.basic-details')}
/>
<PropertyList divider={<Divider />} orientation="vertical" sx={{ '--PropertyItem-padding': '12px 24px' }}>
<PropertyList
divider={<Divider />}
orientation="vertical"
sx={{ '--PropertyItem-padding': '12px 24px' }}
>
{(
[
{ key: 'Customer ID', value: <Chip label="USR-001" size="small" variant="soft" /> },
{
key: 'Customer ID',
value: (
<Chip
label="USR-001"
size="small"
variant="soft"
/>
),
},
{ key: 'Name', value: 'Miron Vitold' },
{ key: 'Email', value: 'miron.vitold@domain.com' },
{ key: 'Phone', value: '(425) 434-5535' },
@@ -59,9 +70,20 @@ export default function BasicDetailCard({
{
key: 'Quota',
value: (
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
<LinearProgress sx={{ flex: '1 1 auto' }} value={50} variant="determinate" />
<Typography color="text.secondary" variant="body2">
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center' }}
>
<LinearProgress
sx={{ flex: '1 1 auto' }}
value={50}
variant="determinate"
/>
<Typography
color="text.secondary"
variant="body2"
>
50%
</Typography>
</Stack>
@@ -70,7 +92,11 @@ export default function BasicDetailCard({
] satisfies { key: string; value: React.ReactNode }[]
).map(
(item): React.JSX.Element => (
<PropertyItem key={item.key} name={item.key} value={item.value} />
<PropertyItem
key={item.key}
name={item.key}
value={item.value}
/>
)
)}
</PropertyList>

View File

@@ -15,27 +15,49 @@ export default function SampleTitleCard(): React.JSX.Element {
return (
<>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', flex: '1 1 auto' }}>
<Avatar src="/assets/avatar-1.png" sx={{ '--Avatar-size': '64px' }}>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flex: '1 1 auto' }}
>
<Avatar
src="/assets/avatar-1.png"
sx={{ '--Avatar-size': '64px' }}
>
empty
</Avatar>
<div>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flexWrap: 'wrap' }}
>
<Typography variant="h4">{t('list.customer-name')}</Typography>
<Chip
icon={<CheckCircleIcon color="var(--mui-palette-success-main)" weight="fill" />}
icon={
<CheckCircleIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
}
label={t('list.active')}
size="small"
variant="outlined"
/>
</Stack>
<Typography color="text.secondary" variant="body1">
<Typography
color="text.secondary"
variant="body1"
>
{t('list.customer-email')}
</Typography>
</div>
</Stack>
<div>
<Button endIcon={<CaretDownIcon />} variant="contained">
<Button
endIcon={<CaretDownIcon />}
variant="contained"
>
{t('list.action')}
</Button>
</div>

View File

@@ -12,14 +12,8 @@ import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
import { LessonCategoryEditForm } from '@/components/dashboard/lesson_category/lesson-category-edit-form';
// import { LessonCategoryEditForm } from '@/components/dashboard/lesson_category/lesson-category-edit-form';
export default function Page(): React.JSX.Element {
const { t } = useTranslation(['common', 'lesson_category']);
React.useEffect(() => {
console.log('helloworld');
}, []);
const { t } = useTranslation(['lesson_category']);
return (
<Box

View File

@@ -1,5 +1,9 @@
'use client';
// RULES:
// contains list page for lp_categories (QuizLPCategories)
// contain definition to collection only
//
import * as React from 'react';
import { useRouter } from 'next/navigation';
import { COL_LESSON_TYPES } from '@/constants';
@@ -20,8 +24,6 @@ import { toast } from '@/components/core/toaster';
import ErrorDisplay from '@/components/dashboard/error';
import { defaultLessonType } from '@/components/dashboard/lesson_type/_constants';
import type { LessonType } from '@/components/dashboard/lesson_type/lesson-type';
// import type { LessonType } from '@/components/dashboard/lesson_type/ILessonType';
// import { defaultLessonType, emptyLessonType, safeAssignment } from '@/components/dashboard/lesson_type/interfaces';
import { LessonTypesFilters } from '@/components/dashboard/lesson_type/lesson-types-filters';
import type { Filters } from '@/components/dashboard/lesson_type/lesson-types-filters';
import { LessonTypesPagination } from '@/components/dashboard/lesson_type/lesson-types-pagination';
@@ -39,6 +41,7 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
const [isLoadingAddPage, setIsLoadingAddPage] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState<boolean>(false);
//
const [rowsPerPage, setRowsPerPage] = React.useState<number>(5);
const [f, setF] = React.useState<LessonType[]>([]);
const [currentPage, setCurrentPage] = React.useState<number>(0);
@@ -102,7 +105,11 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
if (showError)
return (
<ErrorDisplay message={t('unable-to-process-request')} code="500" details={t('detailed-error-information')} />
<ErrorDisplay
message={t('unable-to-process-request')}
code="500"
details={t('detailed-error-information')}
/>
);
return (
@@ -115,7 +122,11 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
}}
>
<Stack spacing={4}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} sx={{ alignItems: 'flex-start' }}>
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={3}
sx={{ alignItems: 'flex-start' }}
>
<Box sx={{ flex: '1 1 auto' }}>
<Typography variant="h4">{t('list.title')}</Typography>
</Box>

View File

@@ -0,0 +1,79 @@
'use client';
import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import { PencilSimple as PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr/PencilSimple';
import { User as UserIcon } from '@phosphor-icons/react/dist/ssr/User';
import { useTranslation } from 'react-i18next';
import { PropertyItem } from '@/components/core/property-item';
import { PropertyList } from '@/components/core/property-list';
import { LpCategory } from '@/components/dashboard/lp_categories/type';
export default function BasicDetailCard({
lpModel: model,
handleEditClick,
}: {
lpModel: LpCategory;
handleEditClick: () => void;
}): React.JSX.Element {
const { t } = useTranslation();
return (
<Card>
<CardHeader
action={
<IconButton
onClick={() => {
handleEditClick();
}}
>
<PencilSimpleIcon />
</IconButton>
}
avatar={
<Avatar>
<UserIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
}
title={t('list.basic-details')}
/>
<PropertyList
divider={<Divider />}
orientation="vertical"
sx={{ '--PropertyItem-padding': '12px 24px' }}
>
{(
[
{
key: 'Customer ID',
value: (
<Chip
label={model.id}
size="small"
variant="soft"
/>
),
},
{ key: 'Name', value: model.cat_name },
{ key: 'Remarks', value: model.remarks },
{ key: 'Description', value: model.description },
] satisfies { key: string; value: React.ReactNode }[]
).map(
(item): React.JSX.Element => (
<PropertyItem
key={item.key}
name={item.key}
value={item.value}
/>
)
)}
</PropertyList>
</Card>
);
}

View File

@@ -0,0 +1,73 @@
'use client';
import * as React from 'react';
import { Button } from '@mui/material';
import Avatar from '@mui/material/Avatar';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { CaretDown as CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown';
import { CheckCircle as CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle';
import { useTranslation } from 'react-i18next';
import { LpCategory } from '@/components/dashboard/lp_categories/type';
function getImageUrlFrRecord(record) {
return `http://127.0.0.1:8090/api/files/${record.collectionId}/${record.id}/${record.cat_image}`;
}
export default function SampleTitleCard({ lpModel }: { lpModel: LpCategory }): React.JSX.Element {
const { t } = useTranslation();
return (
<>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flex: '1 1 auto' }}
>
<Avatar
variant="rounded"
src={getImageUrlFrRecord(lpModel)}
sx={{ '--Avatar-size': '64px' }}
>
{t('empty')}
</Avatar>
<div>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flexWrap: 'wrap' }}
>
<Typography variant="h4">{lpModel.cat_name}</Typography>
<Chip
icon={
<CheckCircleIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
}
label={lpModel.visible}
size="small"
variant="outlined"
/>
</Stack>
<Typography
color="text.secondary"
variant="body1"
>
{lpModel.slug}
</Typography>
</div>
</Stack>
<div>
<Button
endIcon={<CaretDownIcon />}
variant="contained"
>
{t('list.action')}
</Button>
</div>
</>
);
}

View File

@@ -3,7 +3,7 @@
import * as React from 'react';
import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import getQuizListeningById from '@/db/QuizListenings/GetById';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Stack from '@mui/material/Stack';
@@ -12,65 +12,67 @@ import { ArrowLeft as ArrowLeftIcon } from '@phosphor-icons/react/dist/ssr/Arrow
import type { RecordModel } from 'pocketbase';
import { useTranslation } from 'react-i18next';
// import type { LpCategory } from '@/types/type.d';
import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { pb } from '@/lib/pb';
import { toast } from '@/components/core/toaster';
import ErrorDisplay from '@/components/dashboard/error';
import { defaultLpCategory, LpCategoryDefaultValue } from '@/components/dashboard/lp_categories/_constants';
import { defaultLpCategory } from '@/components/dashboard/lp_categories/_constants.ts';
import { Notifications } from '@/components/dashboard/lp_categories/notifications';
import { LpCategory } from '@/components/dashboard/lp_categories/type';
import type { LpCategory } from '@/components/dashboard/lp_categories/type';
import FormLoading from '@/components/loading';
import SampleAddressCard from '../../Sample/AddressCard';
import BasicDetailCard from '../../Sample/BasicDetailCard';
import { SampleNotifications } from '../../Sample/Notifications';
import SamplePaymentCard from '../../Sample/SamplePaymentCard';
import SampleSecurityCard from '../../Sample/SampleSecurityCard';
import SampleTitleCard from '../../Sample/SampleTitleCard';
import BasicDetailCard from './BasicDetailCard';
import TitleCard from './TitleCard';
export default function Page(): React.JSX.Element {
const { t } = useTranslation(['listening_practice']);
const { t } = useTranslation();
const router = useRouter();
//
const { lp_cat_id: lpCatId } = useParams<{ lp_cat_id: string }>();
const { cat_id: catId } = useParams<{ cat_id: string }>();
//
const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState<boolean>(false);
const [errorDetails, setErrorDetails] = React.useState('');
const [showError, setShowError] = React.useState({ show: false, detail: '' });
//
const [showLessonType, setShowLessonType] = React.useState<LpCategory>(LpCategoryDefaultValue.default);
const [showLessonCategory, setShowLessonCategory] = React.useState<LpCategory>(defaultLpCategory);
function handleEditClick(): void {
router.push(paths.dashboard.lp_categories.edit(lpCatId));
function handleEditClick() {
router.push(paths.dashboard.lp_categories.edit(showLessonCategory.id));
}
const [lpModel, setLpModel] = React.useState<RecordModel>(null);
React.useEffect(() => {
getQuizListeningById(lpCatId)
if (catId) {
pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES)
.getOne(catId)
.then((model: RecordModel) => {
setShowLessonType({ ...defaultLpCategory, ...model });
setShowLessonCategory({ ...defaultLpCategory, ...model });
setLpModel(model);
})
.catch((err) => {
logger.error(err);
toast(t('list.error'));
setErrorDetails(err);
setShowError(true);
setShowError({ show: true, detail: JSON.stringify(err) });
})
.finally(() => {
setShowLoading(false);
});
}, [lpCatId]);
}
}, [catId]);
if (showLoading) return <FormLoading />;
if (showError)
if (showError.show)
return (
<ErrorDisplay
message={t('error.unable-to-process-request', { ns: 'common' })}
message={t('error.unable-to-process-request')}
code="500"
details={JSON.stringify(errorDetails, null, 2)}
details={showError.detail}
/>
);
@@ -89,7 +91,7 @@ export default function Page(): React.JSX.Element {
<Link
color="text.primary"
component={RouterLink}
href={paths.dashboard.lp_categories.list}
href={paths.dashboard.lesson_categories.list}
sx={{ alignItems: 'center', display: 'inline-flex', gap: 1 }}
variant="subtitle2"
>
@@ -97,18 +99,34 @@ export default function Page(): React.JSX.Element {
{t('list.title')}
</Link>
</div>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} sx={{ alignItems: 'flex-start' }}>
<SampleTitleCard />
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={3}
sx={{ alignItems: 'flex-start' }}
>
<TitleCard lpModel={lpModel} />
</Stack>
</Stack>
<Grid container spacing={4}>
<Grid lg={4} xs={12}>
<Grid
container
spacing={4}
>
<Grid
lg={4}
xs={12}
>
<Stack spacing={4}>
<BasicDetailCard lpCatId={showLessonType.id} handleEditClick={handleEditClick} />
<BasicDetailCard
lpModel={lpModel}
handleEditClick={handleEditClick}
/>
<SampleSecurityCard />
</Stack>
</Grid>
<Grid lg={8} xs={12}>
<Grid
lg={8}
xs={12}
>
<Stack spacing={4}>
<SamplePaymentCard />
<SampleAddressCard />

View File

@@ -1,5 +1,8 @@
'use client';
// RULES:
// T.B.A.
//
import * as React from 'react';
import RouterLink from 'next/link';
import Box from '@mui/material/Box';
@@ -10,10 +13,12 @@ import { ArrowLeft as ArrowLeftIcon } from '@phosphor-icons/react/dist/ssr/Arrow
import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
import { LpCategoryCreateForm } from '@/components/dashboard/lp_categories/lp-categories-create-form';
import { LpCategoryCreateForm } from '@/components/dashboard/lp_categories/lp-category-create-form';
export default function Page(): React.JSX.Element {
const { t } = useTranslation(['lp_category']);
// RULES: follow the name of page directory
const { t } = useTranslation(['lp_categories']);
return (
<Box
sx={{
@@ -29,12 +34,12 @@ export default function Page(): React.JSX.Element {
<Link
color="text.primary"
component={RouterLink}
href={paths.dashboard.lp_categories.list}
href={paths.dashboard.lesson_categories.list}
sx={{ alignItems: 'center', display: 'inline-flex', gap: 1 }}
variant="subtitle2"
>
<ArrowLeftIcon fontSize="var(--icon-fontSize-md)" />
{t('list.title')}
{t('title')}
</Link>
</div>
<div>

View File

@@ -0,0 +1,11 @@
# 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

@@ -10,11 +10,14 @@ import { ArrowLeft as ArrowLeftIcon } from '@phosphor-icons/react/dist/ssr/Arrow
import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
// import { LessonTypeEditForm } from '@/components/dashboard/lesson_type/lesson-type-edit-form';
import { LpCategoryEditForm } from '@/components/dashboard/lp_categories/lp-category-edit-form';
export default function Page(): React.JSX.Element {
const { t } = useTranslation();
const { t } = useTranslation(['lp_categories']);
React.useEffect(() => {
// console.log('helloworld');
}, []);
return (
<Box
@@ -31,16 +34,16 @@ export default function Page(): React.JSX.Element {
<Link
color="text.primary"
component={RouterLink}
href={paths.dashboard.lesson_types.list}
href={paths.dashboard.lp_categories.list}
sx={{ alignItems: 'center', display: 'inline-flex', gap: 1 }}
variant="subtitle2"
>
<ArrowLeftIcon fontSize="var(--icon-fontSize-md)" />
{t('dashboard.lessonTypes.title')}
{t('edit.title')}
</Link>
</div>
<div>
<Typography variant="h4">{t('dashboard.lessonTypes.edit.title')}</Typography>
<Typography variant="h4">{t('edit.title')}</Typography>
</div>
</Stack>
<LpCategoryEditForm />

View File

@@ -0,0 +1,90 @@
import { dayjs } from '@/lib/dayjs';
import { LessonCategory } from '@/components/dashboard/lesson_category/type';
export const LpCategoriesSampleData = [
{
id: 'USR-005',
name: 'Fran Perez',
avatar: '/assets/avatar-5.png',
email: 'fran.perez@domain.com',
phone: '(815) 704-0045',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(1, 'hour').toDate(),
collectionId: '0000000001',
cat_name: '',
pos: 99,
visible: 'visible',
lesson_id: 'lid_00001',
description: '',
remarks: '',
},
{
id: 'USR-004',
name: 'Penjani Inyene',
avatar: '/assets/avatar-4.png',
email: 'penjani.inyene@domain.com',
phone: '(803) 937-8925',
quota: 100,
status: 'active',
createdAt: dayjs().subtract(3, 'hour').toDate(),
collectionId: '0000000001',
cat_name: '',
pos: 99,
visible: 'visible',
lesson_id: 'lid_00001',
description: '',
remarks: '',
},
{
id: 'USR-003',
name: 'Carson Darrin',
avatar: '/assets/avatar-3.png',
email: 'carson.darrin@domain.com',
phone: '(715) 278-5041',
quota: 10,
status: 'blocked',
createdAt: dayjs().subtract(1, 'hour').subtract(1, 'day').toDate(),
collectionId: '0000000001',
cat_name: '',
pos: 99,
visible: 'visible',
lesson_id: 'lid_00001',
description: '',
remarks: '',
},
{
id: 'USR-002',
name: 'Siegbert Gottfried',
avatar: '/assets/avatar-2.png',
email: 'siegbert.gottfried@domain.com',
phone: '(603) 766-0431',
quota: 0,
status: 'pending',
createdAt: dayjs().subtract(7, 'hour').subtract(1, 'day').toDate(),
collectionId: '0000000001',
cat_name: '',
pos: 99,
visible: 'visible',
lesson_id: 'lid_00001',
description: '',
remarks: '',
},
{
id: 'USR-001',
name: 'Miron Vitold',
avatar: '/assets/avatar-1.png',
email: 'miron.vitold@domain.com',
phone: '(425) 434-5535',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(2, 'hour').subtract(2, 'day').toDate(),
collectionId: '0000000001',
cat_name: '',
pos: 99,
visible: 'visible',
lesson_id: 'lid_00001',
description: '',
remarks: '',
},
] satisfies LessonCategory[];

View File

@@ -1,155 +0,0 @@
import { dayjs } from '@/lib/dayjs';
import type { Customer } from '@/components/dashboard/customer/customers-table';
export const LpCategories = [
{
id: 'USR-005',
name: 'Fran Perez',
avatar: '/assets/avatar-5.png',
email: 'fran.perez@domain.com',
phone: '(815) 704-0045',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(1, 'hour').toDate(),
},
{
id: 'USR-004',
name: 'Penjani Inyene',
avatar: '/assets/avatar-4.png',
email: 'penjani.inyene@domain.com',
phone: '(803) 937-8925',
quota: 100,
status: 'active',
createdAt: dayjs().subtract(3, 'hour').toDate(),
},
{
id: 'USR-003',
name: 'Carson Darrin',
avatar: '/assets/avatar-3.png',
email: 'carson.darrin@domain.com',
phone: '(715) 278-5041',
quota: 10,
status: 'blocked',
createdAt: dayjs().subtract(1, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-002',
name: 'Siegbert Gottfried',
avatar: '/assets/avatar-2.png',
email: 'siegbert.gottfried@domain.com',
phone: '(603) 766-0431',
quota: 0,
status: 'pending',
createdAt: dayjs().subtract(7, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-001',
name: 'Miron Vitold',
avatar: '/assets/avatar-1.png',
email: 'miron.vitold@domain.com',
phone: '(425) 434-5535',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(2, 'hour').subtract(2, 'day').toDate(),
},
{
id: 'USR-005',
name: 'Fran Perez',
avatar: '/assets/avatar-5.png',
email: 'fran.perez@domain.com',
phone: '(815) 704-0045',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(1, 'hour').toDate(),
},
{
id: 'USR-004',
name: 'Penjani Inyene',
avatar: '/assets/avatar-4.png',
email: 'penjani.inyene@domain.com',
phone: '(803) 937-8925',
quota: 100,
status: 'active',
createdAt: dayjs().subtract(3, 'hour').toDate(),
},
{
id: 'USR-003',
name: 'Carson Darrin',
avatar: '/assets/avatar-3.png',
email: 'carson.darrin@domain.com',
phone: '(715) 278-5041',
quota: 10,
status: 'blocked',
createdAt: dayjs().subtract(1, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-002',
name: 'Siegbert Gottfried',
avatar: '/assets/avatar-2.png',
email: 'siegbert.gottfried@domain.com',
phone: '(603) 766-0431',
quota: 0,
status: 'pending',
createdAt: dayjs().subtract(7, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-001',
name: 'Miron Vitold',
avatar: '/assets/avatar-1.png',
email: 'miron.vitold@domain.com',
phone: '(425) 434-5535',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(2, 'hour').subtract(2, 'day').toDate(),
},
{
id: 'USR-005',
name: 'Fran Perez',
avatar: '/assets/avatar-5.png',
email: 'fran.perez@domain.com',
phone: '(815) 704-0045',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(1, 'hour').toDate(),
},
{
id: 'USR-004',
name: 'Penjani Inyene',
avatar: '/assets/avatar-4.png',
email: 'penjani.inyene@domain.com',
phone: '(803) 937-8925',
quota: 100,
status: 'active',
createdAt: dayjs().subtract(3, 'hour').toDate(),
},
{
id: 'USR-003',
name: 'Carson Darrin',
avatar: '/assets/avatar-3.png',
email: 'carson.darrin@domain.com',
phone: '(715) 278-5041',
quota: 10,
status: 'blocked',
createdAt: dayjs().subtract(1, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-002',
name: 'Siegbert Gottfried',
avatar: '/assets/avatar-2.png',
email: 'siegbert.gottfried@domain.com',
phone: '(603) 766-0431',
quota: 0,
status: 'pending',
createdAt: dayjs().subtract(7, 'hour').subtract(1, 'day').toDate(),
},
{
id: 'USR-001',
name: 'Miron Vitold',
avatar: '/assets/avatar-1.png',
email: 'miron.vitold@domain.com',
phone: '(425) 434-5535',
quota: 50,
status: 'active',
createdAt: dayjs().subtract(2, 'hour').subtract(2, 'day').toDate(),
},
] satisfies Customer[];

View File

@@ -1,8 +1,12 @@
'use client';
// RULES:
// contains list page for lp_categories (QuizLPCategories)
// contain definition to collection only
//
import * as React from 'react';
import { useRouter } from 'next/navigation';
import listWithOption from '@/db/QuizListenings/ListWithOption';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { LoadingButton } from '@mui/lab';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
@@ -13,54 +17,59 @@ import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import type { ListResult, RecordModel } from 'pocketbase';
import { useTranslation } from 'react-i18next';
// import type { LpCategory } from '@/types/type.d';
import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { pb } from '@/lib/pb';
import { toast } from '@/components/core/toaster';
import ErrorDisplay from '@/components/dashboard/error';
import { defaultLpCategory } from '@/components/dashboard/lp_categories/_constants';
import { LpCategoriesFilters } from '@/components/dashboard/lp_categories/lp-categories-filters';
import type { Filters } from '@/components/dashboard/lp_categories/lp-categories-filters';
import { LpCategoriesPagination } from '@/components/dashboard/lp_categories/lp-categories-pagination';
import { LpCategoriesSelectionProvider } from '@/components/dashboard/lp_categories/lp-categories-selection-context';
import { LpCategoriesTable } from '@/components/dashboard/lp_categories/lp-category-table';
import { LpCategory } from '@/components/dashboard/lp_categories/type';
import { LpCategoriesTable } from '@/components/dashboard/lp_categories/lp-categories-table';
import type { LpCategory } from '@/components/dashboard/lp_categories/type';
import FormLoading from '@/components/loading';
export default function Page({ searchParams }: PageProps): React.JSX.Element {
const { t } = useTranslation(['listening_practice']);
const { t } = useTranslation(['lp_categories']);
const { email, phone, sortDir, status, name, visible, type } = searchParams;
const router = useRouter();
const [lpCategoriesData, setLpCategoriesData] = React.useState<LpCategory[]>([]);
const [lessonCategoriesData, setLessonCategoriesData] = React.useState<LpCategory[]>([]);
//
const [isLoadingAddPage, setIsLoadingAddPage] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState<boolean>(false);
const [showError, setShowError] = React.useState({ show: false, detail: '' });
//
const [rowsPerPage, setRowsPerPage] = React.useState<number>(5);
const [f, setF] = React.useState<LpCategory[]>([]);
const [currentPage, setCurrentPage] = React.useState<number>(0);
const [currentPage, setCurrentPage] = React.useState<number>(1);
const [recordCount, setRecordCount] = React.useState<number>(0);
const [listOption, setListOption] = React.useState({});
const [listSort, setListSort] = React.useState({});
//
const sortedLessonCategories = applySort(lessonCategoriesData, sortDir);
const filteredLessonCategories = applyFilters(sortedLessonCategories, { email, phone, status });
const reloadRows = async (): Promise<void> => {
try {
const models: ListResult<RecordModel> = await listWithOption({
currentPage,
rowsPerPage,
listOption,
});
const models: ListResult<RecordModel> = await pb
.collection(COL_LISTENINGS_PRACTICE_CATEGORIES)
.getList(currentPage + 1, rowsPerPage, {});
const { items, totalItems } = models;
const tempLpCategories: LpCategory[] = items.map((lt) => {
const tempLessonTypes: LpCategory[] = items.map((lt) => {
return { ...defaultLpCategory, ...lt };
});
setLpCategoriesData(tempLpCategories);
setLessonCategoriesData(tempLessonTypes);
setRecordCount(totalItems);
setF(tempLpCategories);
setF(tempLessonTypes);
console.log({ currentPage, f });
} catch (error) {
//
setShowError({ show: true, detail: JSON.stringify(error) });
} finally {
setShowLoading(false);
}
@@ -70,38 +79,15 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
void reloadRows();
}, [currentPage, rowsPerPage, listOption]);
React.useEffect(() => {
let tempFilter = [],
tempSortDir = '';
if (showLoading) return <FormLoading />;
if (visible) {
tempFilter.push(`visible = "${visible}"`);
}
if (sortDir) {
tempSortDir = `-created`;
}
if (name) {
tempFilter.push(`name ~ "%${name}%"`);
}
if (type) {
tempFilter.push(`type ~ "%${type}%"`);
}
setListOption({
filter: tempFilter.join(' && '),
sort: tempSortDir,
//
});
}, [visible, sortDir, name, type]);
if (f.length === 0 || showLoading) return <FormLoading />;
if (showError)
if (showError.show)
return (
<ErrorDisplay message={t('unable-to-process-request')} code="500" details={t('detailed-error-information')} />
<ErrorDisplay
message={t('error.unable-to-process-request')}
code="500"
details={showError.detail}
/>
);
return (
@@ -113,8 +99,14 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
width: 'var(--Content-width)',
}}
>
{JSON.stringify({ currentPage, rowsPerPage })}
<Stack spacing={4}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} sx={{ alignItems: 'flex-start' }}>
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={3}
sx={{ alignItems: 'flex-start' }}
>
<Box sx={{ flex: '1 1 auto' }}>
<Typography variant="h4">{t('list.title')}</Typography>
</Box>
@@ -128,24 +120,22 @@ export default function Page({ searchParams }: PageProps): React.JSX.Element {
startIcon={<PlusIcon />}
variant="contained"
>
{t('add')}
{t('list.add')}
</LoadingButton>
</Box>
</Stack>
<LpCategoriesSelectionProvider LpCategories={f}>
<LpCategoriesSelectionProvider lessonCategories={f}>
<Card>
<LpCategoriesFilters
filters={{ email, phone, status }}
fullData={f}
filters={{ email, phone, status, name, visible, type }}
fullData={lessonCategoriesData}
sortDir={sortDir}
//
/>
<Divider />
<Box sx={{ overflowX: 'auto' }}>
<LpCategoriesTable
rows={f}
reloadRows={reloadRows}
//
rows={f}
/>
</Box>
<Divider />

View File

@@ -25,9 +25,7 @@ import { dayjs } from '@/lib/dayjs';
import { DataTable } from '@/components/core/data-table';
import type { ColumnDef } from '@/components/core/data-table';
// import { LessonCategory } from '../lp_categories/type';
import ConfirmDeleteModal from './confirm-delete-modal';
// import type { LessonCategory } from './interfaces.1ts';
import { useLessonCategoriesSelection } from './lesson-categories-selection-context';
import { LessonCategory } from './type';

View File

@@ -12,6 +12,7 @@ export interface LessonCategory {
lesson_id: string;
description: string;
remarks: string;
createdAt: Date;
//
name: string;
avatar: string;
@@ -19,7 +20,6 @@ export interface LessonCategory {
phone: string;
quota: number;
status: 'pending' | 'active' | 'blocked' | 'NA';
createdAt: Date;
}
export interface CreateForm {

View File

@@ -39,11 +39,6 @@ import { toast } from '@/components/core/toaster';
import { LessonTypeCreateFormDefault } from './_constants';
import { CreateForm } from './lesson-type';
// import { CreateForm, LessonTypeCreateFormDefault } from './interfaces';
// import { createLessonType } from './http-actions';
// import { LessonTypeCreateForm, LessonTypeCreateFormDefault } from './interfaces';
const schema = zod.object({
name: zod.string().min(1, 'Name is required').max(255),
type: zod.string().min(1, 'Name is required').max(255),
@@ -94,6 +89,8 @@ export function LessonTypeCreateForm(): React.JSX.Element {
setIsCreating(false);
});
},
// t is not necessary here
// eslint-disable-next-line react-hooks/exhaustive-deps
[router]
);

View File

@@ -10,6 +10,7 @@ function noop(): void {
interface LessonTypesPaginationProps {
count: number;
page: number;
//
setPage: (page: number) => void;
setRowsPerPage: (page: number) => void;
rowsPerPage: number;
@@ -18,6 +19,7 @@ interface LessonTypesPaginationProps {
export function LessonTypesPagination({
count,
page,
//
setPage,
setRowsPerPage,
rowsPerPage,
@@ -37,12 +39,11 @@ export function LessonTypesPagination({
<TablePagination
component="div"
count={count}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
page={page}
rowsPerPage={rowsPerPage}
rowsPerPageOptions={[5, 10, 25]}
//
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
);
}

View File

@@ -5,7 +5,6 @@ import RouterLink from 'next/link';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import LinearProgress from '@mui/material/LinearProgress';
import Link from '@mui/material/Link';
@@ -26,15 +25,18 @@ import { DataTable } from '@/components/core/data-table';
import type { ColumnDef } from '@/components/core/data-table';
import ConfirmDeleteModal from './confirm-delete-modal';
import { LessonType } from './lesson-type';
// import type { LessonType } from './ILessonType';
import type { LessonType } from './lesson-type';
import { useLessonTypesSelection } from './lesson-types-selection-context';
function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonType>[] {
return [
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<Link
color={row.isEmpty ? 'disabled' : 'inherit'}
component={RouterLink}
@@ -51,7 +53,11 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonT
},
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<div>
<Link
color={row.isEmpty ? 'disabled' : 'inherit'}
@@ -70,7 +76,11 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonT
},
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<div>
<Link
color={row.isEmpty ? 'disabled' : 'inherit'}
@@ -89,24 +99,54 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonT
},
{
formatter: (row): React.JSX.Element => {
// eslint-disable-next-line react-hooks/rules-of-hooks
// const { t } = useTranslation();
const mapping = {
active: { label: 'Active', icon: <CheckCircleIcon color="var(--mui-palette-success-main)" weight="fill" /> },
active: {
label: 'Active',
icon: (
<CheckCircleIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
),
},
blocked: { label: 'Blocked', icon: <MinusIcon color="var(--mui-palette-error-main)" /> },
pending: { label: 'Pending', icon: <ClockIcon color="var(--mui-palette-warning-main)" weight="fill" /> },
pending: {
label: 'Pending',
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
visible: {
label: 'visible',
icon: <ClockIcon color="var(--mui-palette-success-main)" weight="fill" />,
icon: (
<ClockIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
),
},
hidden: {
label: 'hidden',
icon: <ClockIcon color="var(--mui-palette-warning-main)" weight="fill" />,
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
no_value: {
label: 'no_value',
icon: <ClockIcon color="var(--mui-palette-warning-main)" weight="fill" />,
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
} as const;
@@ -136,7 +176,10 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonT
},
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1}>
<Stack
direction="row"
spacing={1}
>
<IconButton
//
disabled={row.isEmpty}
@@ -183,7 +226,12 @@ export function LessonTypesTable({ rows, reloadRows }: LessonTypesTableProps): R
return (
<React.Fragment>
<ConfirmDeleteModal idToDelete={idToDelete} open={open} reloadRows={reloadRows} setOpen={setOpen} />
<ConfirmDeleteModal
idToDelete={idToDelete}
open={open}
reloadRows={reloadRows}
setOpen={setOpen}
/>
<DataTable<LessonType>
columns={columns(handleDeleteClick)}
onDeselectAll={deselectAll}
@@ -200,7 +248,11 @@ export function LessonTypesTable({ rows, reloadRows }: LessonTypesTableProps): R
/>
{!rows.length ? (
<Box sx={{ p: 3 }}>
<Typography color="text.secondary" sx={{ textAlign: 'center' }} variant="body2">
<Typography
color="text.secondary"
sx={{ textAlign: 'center' }}
variant="body2"
>
{/* TODO: use hyphen here */}
{t('no-lesson-types-found')}
</Typography>

View File

@@ -1,57 +1,42 @@
import { NO_NUM, NO_VALUE } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { dayjs } from '@/lib/dayjs';
import type { CreateForm, LpCategory } from './type';
// import type { CreateForm, LpCategory } from './types';
export const LpCategoryCreateFormDefault: CreateForm = {
name: '',
type: '',
pos: 1,
visible: 'visible',
description: '',
isActive: true,
order: 1,
imageUrl: '',
};
import { CreateFormProps, LpCategory } from './type';
export const defaultLpCategory: LpCategory = {
id: '',
collectionId: '',
isEmpty: false,
id: 'default-id',
cat_name: 'default-category-name',
cat_image_url: undefined,
cat_image: undefined,
pos: 0,
visible: 'hidden',
lesson_id: 'default-lesson-id',
description: 'default-description',
remarks: 'default-remarks',
//
cat_name: '',
cat_image_url: '',
cat_image: '',
pos: 1,
lesson_id: '1',
description: '',
remarks: '',
createdAt: dayjs().toDate(),
visible: 'visible',
collectionId: '0000000000',
createdAt: dayjs('2099-01-01').toDate(),
//
name: '',
avatar: '',
email: '',
phone: '',
quota: 0,
order: 1,
status: 'NA',
isActive: true,
imageUrl: '',
};
// export const LpCategoryCreateFormDefault: CreateFormProps = {
// name: '',
// type: '',
// pos: 1,
// visible: 'visible',
// description: '',
// isActive: true,
// order: 1,
// imageUrl: '',
// };
export const emptyLpCategory: LpCategory = {
...defaultLpCategory,
isActive: false,
isEmpty: true,
};
export const LpCategoryDefaultValue = {
createForm: LpCategoryCreateFormDefault,
default: defaultLpCategory,
empty: emptyLpCategory,
};
export default LpCategoryDefaultValue;

View File

@@ -1,3 +0,0 @@
const helloworld = 'helloworld';
export { helloworld };

View File

@@ -1,388 +0,0 @@
'use client';
import * as React from 'react';
import RouterLink from 'next/link';
import { useRouter } from 'next/navigation';
import { zodResolver } from '@hookform/resolvers/zod';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import Checkbox from '@mui/material/Checkbox';
import Divider from '@mui/material/Divider';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';
import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { fileToBase64 } from '@/lib/file-to-base64';
import { Option } from '@/components/core/option';
import { toast } from '@/components/core/toaster';
const schema = zod.object({
avatar: zod.string().optional(),
name: zod.string().min(1, 'Name is required').max(255),
email: zod.string().email('Must be a valid email').min(1, 'Email is required').max(255),
phone: zod.string().min(1, 'Phone is required').max(15),
company: zod.string().max(255),
billingAddress: zod.object({
country: zod.string().min(1, 'Country is required').max(255),
state: zod.string().min(1, 'State is required').max(255),
city: zod.string().min(1, 'City is required').max(255),
zipCode: zod.string().min(1, 'Zip code is required').max(255),
line1: zod.string().min(1, 'Street line 1 is required').max(255),
line2: zod.string().max(255).optional(),
}),
taxId: zod.string().max(255).optional(),
timezone: zod.string().min(1, 'Timezone is required').max(255),
language: zod.string().min(1, 'Language is required').max(255),
currency: zod.string().min(1, 'Currency is required').max(255),
});
const defaultValues = {
avatar: '',
name: '',
email: '',
phone: '',
company: '',
billingAddress: { country: '', state: '', city: '', zipCode: '', line1: '', line2: '' },
taxId: '',
timezone: 'new_york',
language: 'en',
currency: 'USD',
} satisfies Values;
export type Values = zod.infer<typeof schema>;
export function LpCategoryCreateForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation();
const {
control,
handleSubmit,
formState: { errors },
setValue,
watch,
} = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });
const onSubmit = React.useCallback(
async (_: Values): Promise<void> => {
try {
// Make API request
toast.success('Customer updated');
router.push(paths.dashboard.customers.details('1'));
} catch (err) {
logger.error(err);
toast.error('Something went wrong!');
}
},
[router]
);
const avatarInputRef = React.useRef<HTMLInputElement>(null);
const avatar = watch('avatar');
const handleAvatarChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const url = await fileToBase64(file);
setValue('avatar', url);
}
},
[setValue]
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack divider={<Divider />} spacing={4}>
<Stack spacing={3}>
<Typography variant="h6">{t('Account information')}</Typography>
<Grid container spacing={3}>
<Grid xs={12}>
<Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
borderRadius: '50%',
display: 'inline-flex',
p: '4px',
}}
>
<Avatar
src={avatar}
sx={{
'--Avatar-size': '100px',
'--Icon-fontSize': 'var(--icon-fontSize-lg)',
alignItems: 'center',
bgcolor: 'var(--mui-palette-background-level1)',
color: 'var(--mui-palette-text-primary)',
display: 'flex',
justifyContent: 'center',
}}
>
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
</Box>
<Stack spacing={1} sx={{ alignItems: 'flex-start' }}>
<Typography variant="subtitle1">{t('Avatar')}</Typography>
<Typography variant="caption">{t('Min 400x400px, PNG or JPEG')}</Typography>
<Button
color="secondary"
onClick={() => {
avatarInputRef.current?.click();
}}
variant="outlined"
>
{t('Select')}
</Button>
<input hidden onChange={handleAvatarChange} ref={avatarInputRef} type="file" />
</Stack>
</Stack>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="name"
render={({ field }) => (
<FormControl error={Boolean(errors.name)} fullWidth>
<InputLabel required>{t('Name')}</InputLabel>
<OutlinedInput {...field} />
{errors.name ? <FormHelperText>{errors.name.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="email"
render={({ field }) => (
<FormControl error={Boolean(errors.email)} fullWidth>
<InputLabel required>{t('Email address')}</InputLabel>
<OutlinedInput {...field} type="email" />
{errors.email ? <FormHelperText>{errors.email.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="phone"
render={({ field }) => (
<FormControl error={Boolean(errors.phone)} fullWidth>
<InputLabel required>{t('Phone number')}</InputLabel>
<OutlinedInput {...field} />
{errors.phone ? <FormHelperText>{errors.phone.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="company"
render={({ field }) => (
<FormControl error={Boolean(errors.company)} fullWidth>
<InputLabel>{t('Company')}</InputLabel>
<OutlinedInput {...field} />
{errors.company ? <FormHelperText>{errors.company.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
<Stack spacing={3}>
<Typography variant="h6">{t('Billing information')}</Typography>
<Grid container spacing={3}>
<Grid md={6} xs={12}>
<Controller
control={control}
name="billingAddress.country"
render={({ field }) => (
<FormControl error={Boolean(errors.billingAddress?.country)} fullWidth>
<InputLabel required>{t('Country')}</InputLabel>
<Select {...field}>
<Option value="">{t('Choose a country')}</Option>
<Option value="us">{t('United States')}</Option>
<Option value="de">{t('Germany')}</Option>
<Option value="es">{t('Spain')}</Option>
</Select>
{errors.billingAddress?.country ? (
<FormHelperText>{errors.billingAddress?.country?.message}</FormHelperText>
) : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="billingAddress.state"
render={({ field }) => (
<FormControl error={Boolean(errors.billingAddress?.state)} fullWidth>
<InputLabel required>{t('State')}</InputLabel>
<OutlinedInput {...field} />
{errors.billingAddress?.state ? (
<FormHelperText>{errors.billingAddress?.state?.message}</FormHelperText>
) : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="billingAddress.city"
render={({ field }) => (
<FormControl error={Boolean(errors.billingAddress?.city)} fullWidth>
<InputLabel required>{t('City')}</InputLabel>
<OutlinedInput {...field} />
{errors.billingAddress?.city ? (
<FormHelperText>{errors.billingAddress?.city?.message}</FormHelperText>
) : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="billingAddress.zipCode"
render={({ field }) => (
<FormControl error={Boolean(errors.billingAddress?.zipCode)} fullWidth>
<InputLabel required>{t('Zip code')}</InputLabel>
<OutlinedInput {...field} />
{errors.billingAddress?.zipCode ? (
<FormHelperText>{errors.billingAddress?.zipCode?.message}</FormHelperText>
) : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="billingAddress.line1"
render={({ field }) => (
<FormControl error={Boolean(errors.billingAddress?.line1)} fullWidth>
<InputLabel required>{t('Address')}</InputLabel>
<OutlinedInput {...field} />
{errors.billingAddress?.line1 ? (
<FormHelperText>{errors.billingAddress?.line1?.message}</FormHelperText>
) : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="taxId"
render={({ field }) => (
<FormControl error={Boolean(errors.taxId)} fullWidth>
<InputLabel>{t('Tax ID')}</InputLabel>
<OutlinedInput {...field} placeholder={t('e.g EU372054390')} />
{errors.taxId ? <FormHelperText>{errors.taxId.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
<Stack spacing={3}>
<Typography variant="h6">{t('Shipping information')}</Typography>
<FormControlLabel control={<Checkbox defaultChecked />} label={t('Same as billing address')} />
</Stack>
<Stack spacing={3}>
<Typography variant="h6">{t('Additional information')}</Typography>
<Grid container spacing={3}>
<Grid md={6} xs={12}>
<Controller
control={control}
name="timezone"
render={({ field }) => (
<FormControl error={Boolean(errors.timezone)} fullWidth>
<InputLabel required>{t('Timezone')}</InputLabel>
<Select {...field}>
<Option value="">{t('Select a timezone')}</Option>
<Option value="new_york">{t('US - New York')}</Option>
<Option value="california">{t('US - California')}</Option>
<Option value="london">{t('UK - London')}</Option>
</Select>
{errors.timezone ? <FormHelperText>{errors.timezone.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="language"
render={({ field }) => (
<FormControl error={Boolean(errors.language)} fullWidth>
<InputLabel required>{t('Language')}</InputLabel>
<Select {...field}>
<Option value="">{t('Select a language')}</Option>
<Option value="en">{t('English')}</Option>
<Option value="es">{t('Spanish')}</Option>
<Option value="de">{t('German')}</Option>
</Select>
{errors.language ? <FormHelperText>{errors.language.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="currency"
render={({ field }) => (
<FormControl error={Boolean(errors.currency)} fullWidth>
<InputLabel>{t('Currency')}</InputLabel>
<Select {...field}>
<Option value="">{t('Select a currency')}</Option>
<Option value="USD">{t('USD')}</Option>
<Option value="EUR">{t('EUR')}</Option>
<Option value="RON">{t('RON')}</Option>
</Select>
{errors.currency ? <FormHelperText>{errors.currency.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button color="secondary" component={RouterLink} href={paths.dashboard.lp_categories.list}>
{t('cancel')}
</Button>
<Button type="submit" variant="contained">
{t('create-category')}
</Button>
</CardActions>
</Card>
</form>
);
}

View File

@@ -2,6 +2,7 @@
import * as React from 'react';
import { useRouter } from 'next/navigation';
// import { COL_LESSON_CATEGORIES } from '@/constants';
import GetAllCount from '@/db/QuizListenings/GetAllCount';
import GetHiddenCount from '@/db/QuizListenings/GetHiddenCount';
import GetVisibleCount from '@/db/QuizListenings/GetVisibleCount';
@@ -19,12 +20,13 @@ import Typography from '@mui/material/Typography';
import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
// import { pb } from '@/lib/pb';
import { FilterButton, FilterPopover, useFilterContext } from '@/components/core/filter-button';
import { Option } from '@/components/core/option';
// import { LessonCategory } from '../lp_categories/type';
import { useLpCategoriesSelection } from './lp-categories-selection-context';
// import type { LpCategory } from '@/types/type.d';
import type { LpCategory } from './type';
import { LpCategory } from './type';
export interface Filters {
email?: string;
@@ -59,6 +61,18 @@ export function LpCategoriesFilters({
const selection = useLpCategoriesSelection();
function getVisible(): number {
return fullData.reduce((count, item: LpCategory) => {
return item.visible === 'visible' ? count + 1 : count;
}, 0);
}
function getHidden(): number {
return fullData.reduce((count, item: LpCategory) => {
return item.visible === 'hidden' ? count + 1 : count;
}, 0);
}
// The tabs should be generated using API data.
const tabs = [
{ label: t('All'), value: '', count: totalCount },
@@ -101,6 +115,7 @@ export function LpCategoriesFilters({
searchParams.set('visible', newFilters.visible);
}
// NOTE: modify according to COLLECTION
router.push(`${paths.dashboard.lp_categories.list}?${searchParams.toString()}`);
},
[router]
@@ -181,13 +196,7 @@ export function LpCategoriesFilters({
return (
<div>
<Tabs
onChange={handleVisibleChange}
sx={{ px: 3 }}
value={visible ?? ''}
variant="scrollable"
//
>
<Tabs onChange={handleVisibleChange} sx={{ px: 3 }} value={visible ?? ''} variant="scrollable">
{tabs.map((tab) => (
<Tab
icon={<Chip label={tab.count} size="small" variant="soft" />}
@@ -316,7 +325,7 @@ function NameFilterPopover(): React.JSX.Element {
}}
variant="contained"
>
{t('Apply')}
{t('apply')}
</Button>
</FilterPopover>
);
@@ -325,6 +334,7 @@ function NameFilterPopover(): React.JSX.Element {
function EmailFilterPopover(): React.JSX.Element {
const { anchorEl, onApply, onClose, open, value: initialValue } = useFilterContext();
const [value, setValue] = React.useState<string>('');
const { t } = useTranslation();
React.useEffect(() => {
setValue((initialValue as string | undefined) ?? '');
@@ -351,7 +361,7 @@ function EmailFilterPopover(): React.JSX.Element {
}}
variant="contained"
>
Apply
{t('Apply')}
</Button>
</FilterPopover>
);
@@ -360,6 +370,7 @@ function EmailFilterPopover(): React.JSX.Element {
function PhoneFilterPopover(): React.JSX.Element {
const { anchorEl, onApply, onClose, open, value: initialValue } = useFilterContext();
const [value, setValue] = React.useState<string>('');
const { t } = useTranslation();
React.useEffect(() => {
setValue((initialValue as string | undefined) ?? '');
@@ -386,7 +397,7 @@ function PhoneFilterPopover(): React.JSX.Element {
}}
variant="contained"
>
Apply
{t('Apply')}
</Button>
</FilterPopover>
);

View File

@@ -7,9 +7,10 @@ function noop(): void {
return undefined;
}
interface LpCategoriesPaginationProps {
interface LessonCategoriesPaginationProps {
count: number;
page: number;
//
setPage: (page: number) => void;
setRowsPerPage: (page: number) => void;
rowsPerPage: number;
@@ -18,10 +19,11 @@ interface LpCategoriesPaginationProps {
export function LpCategoriesPagination({
count,
page,
//
setPage,
setRowsPerPage,
rowsPerPage,
}: LpCategoriesPaginationProps): React.JSX.Element {
}: LessonCategoriesPaginationProps): React.JSX.Element {
// You should implement the pagination using a similar logic as the filters.
// Note that when page change, you should keep the filter search params.
const handleChangePage = (event: unknown, newPage: number) => {
@@ -37,12 +39,11 @@ export function LpCategoriesPagination({
<TablePagination
component="div"
count={count}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
page={page}
rowsPerPage={rowsPerPage}
rowsPerPageOptions={[5, 10, 25]}
//
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
);
}

View File

@@ -2,10 +2,11 @@
import * as React from 'react';
// import type { LessonCategory } from '@/types/lesson-type';
import { useSelection } from '@/hooks/use-selection';
import type { Selection } from '@/hooks/use-selection';
import type { LpCategory } from './type';
import { LpCategory } from './type';
function noop(): void {
return undefined;
@@ -13,7 +14,7 @@ function noop(): void {
export interface LpCategoriesSelectionContextValue extends Selection {}
export const CustomersSelectionContext = React.createContext<LpCategoriesSelectionContextValue>({
export const LpCategoriesSelectionContext = React.createContext<LpCategoriesSelectionContextValue>({
deselectAll: noop,
deselectOne: noop,
selectAll: noop,
@@ -25,19 +26,21 @@ export const CustomersSelectionContext = React.createContext<LpCategoriesSelecti
interface LpCategoriesSelectionProviderProps {
children: React.ReactNode;
LpCategories: LpCategory[];
lessonCategories: LpCategory[];
}
export function LpCategoriesSelectionProvider({
children,
LpCategories: customers = [],
lessonCategories = [],
}: LpCategoriesSelectionProviderProps): React.JSX.Element {
const customerIds = React.useMemo(() => customers.map((customer) => customer.id), [customers]);
const customerIds = React.useMemo(() => lessonCategories.map((customer) => customer.id), [lessonCategories]);
const selection = useSelection(customerIds);
return <CustomersSelectionContext.Provider value={{ ...selection }}>{children}</CustomersSelectionContext.Provider>;
return (
<LpCategoriesSelectionContext.Provider value={{ ...selection }}>{children}</LpCategoriesSelectionContext.Provider>
);
}
export function useLpCategoriesSelection(): LpCategoriesSelectionContextValue {
return React.useContext(CustomersSelectionContext);
return React.useContext(LpCategoriesSelectionContext);
}

View File

@@ -5,7 +5,6 @@ import RouterLink from 'next/link';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import LinearProgress from '@mui/material/LinearProgress';
import Link from '@mui/material/Link';
@@ -33,7 +32,11 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
return [
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<Link
color="inherit"
component={RouterLink}
@@ -41,13 +44,23 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
sx={{ whiteSpace: 'nowrap' }}
variant="subtitle2"
>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Avatar src={getCatImageFromId(row)} variant="rounded">
<Stack
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<Avatar
src={`http://127.0.0.1:8090/api/files/${row.collectionId}/${row.id}/${row.cat_image}`}
variant="rounded"
>
<ImagesIcon size={32} />
</Avatar>{' '}
<div>
<Box sx={{ whiteSpace: 'nowrap' }}>{row.cat_name}</Box>
<Typography color="text.secondary" variant="body2">
<Typography
color="text.secondary"
variant="body2"
>
slug: {row.cat_name}
</Typography>
</div>
@@ -60,12 +73,21 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
},
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
<LinearProgress sx={{ flex: '1 1 auto' }} value={row.quota} variant="determinate" />
<Typography color="text.secondary" variant="body2">
{new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 2 }).format(
row?.quota ? row.quota / 100 : 0
)}
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center' }}
>
<LinearProgress
sx={{ flex: '1 1 auto' }}
value={row.quota}
variant="determinate"
/>
<Typography
color="text.secondary"
variant="body2"
>
{new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 2 }).format(row.quota / 100)}
</Typography>
</Stack>
),
@@ -76,13 +98,36 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
{
formatter: (row): React.JSX.Element => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { t } = useTranslation();
const mapping = {
active: { label: 'Active', icon: <CheckCircleIcon color="var(--mui-palette-success-main)" weight="fill" /> },
active: {
label: 'Active',
icon: (
<CheckCircleIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
),
},
blocked: { label: 'Blocked', icon: <MinusIcon color="var(--mui-palette-error-main)" /> },
pending: { label: 'Pending', icon: <ClockIcon color="var(--mui-palette-warning-main)" weight="fill" /> },
NA: { label: 'NA', icon: <ClockIcon color="var(--mui-palette-warning-main)" weight="fill" /> },
pending: {
label: 'Pending',
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
NA: {
label: 'NA',
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
} as const;
const { label, icon } = mapping[row.status] ?? { label: 'Unknown', icon: null };
@@ -110,7 +155,10 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
},
{
formatter: (row): React.JSX.Element => (
<Stack direction="row" spacing={1}>
<Stack
direction="row"
spacing={1}
>
<IconButton
//
component={RouterLink}
@@ -137,17 +185,13 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LpCateg
];
}
export interface LpCategoryTableProps {
export interface LessonCategoriesTableProps {
rows: LpCategory[];
reloadRows: () => void;
}
function getCatImageFromId(row: LpCategory): string | undefined {
return `http://127.0.0.1:8090/api/files/${row.collectionId}/${row.id}/${row.cat_image}`;
}
export function LpCategoriesTable({ rows, reloadRows }: LpCategoryTableProps): React.JSX.Element {
const { t } = useTranslation();
export function LpCategoriesTable({ rows, reloadRows }: LessonCategoriesTableProps): React.JSX.Element {
const { t } = useTranslation(['lp_categories']);
const { deselectAll, deselectOne, selectAll, selectOne, selected } = useLpCategoriesSelection();
const [idToDelete, setIdToDelete] = React.useState('');
@@ -160,7 +204,12 @@ export function LpCategoriesTable({ rows, reloadRows }: LpCategoryTableProps): R
return (
<React.Fragment>
<ConfirmDeleteModal idToDelete={idToDelete} open={open} reloadRows={reloadRows} setOpen={setOpen} />
<ConfirmDeleteModal
idToDelete={idToDelete}
open={open}
reloadRows={reloadRows}
setOpen={setOpen}
/>
<DataTable<LpCategory>
columns={columns(handleDeleteClick)}
onDeselectAll={deselectAll}
@@ -177,8 +226,12 @@ export function LpCategoriesTable({ rows, reloadRows }: LpCategoryTableProps): R
/>
{!rows.length ? (
<Box sx={{ p: 3 }}>
<Typography color="text.secondary" sx={{ textAlign: 'center' }} variant="body2">
{t('No customers found')}
<Typography
color="text.secondary"
sx={{ textAlign: 'center' }}
variant="body2"
>
{t('no-lesson-categories-found')}
</Typography>
</Box>
) : null}

View File

@@ -0,0 +1,419 @@
'use client';
import * as React from 'react';
import RouterLink from 'next/link';
import { useRouter } from 'next/navigation';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, Divider, MenuItem, Select } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
// import axios from 'axios';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';
import { paths } from '@/paths';
import isDevelopment from '@/lib/check-is-development';
import { logger } from '@/lib/default-logger';
import { base64ToFile, fileToBase64 } from '@/lib/file-to-base64';
import { pb } from '@/lib/pb';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';
import type { CreateFormProps } from './type';
const schema = zod.object({
cat_name: zod.string().min(1, 'name-is-required').max(255),
cat_image: zod.array(zod.any()).optional(),
pos: zod.number().min(1, 'position is required').max(99),
init_answer: zod.string().optional(),
visible: zod.string(),
slug: zod.string().min(1, 'slug-is-required').max(255),
remarks: zod.string().optional(),
description: zod.string().optional(),
// NOTE: for image handling
avatar: zod.string().optional(),
// TODO: remove me
type: zod.string().optional(),
isActive: zod.boolean().optional(),
order: zod.number().optional(),
});
type Values = zod.infer<typeof schema>;
export const defaultValues = {
cat_name: '',
cat_image: undefined,
pos: 1,
init_answer: '',
visible: 'hidden',
slug: '',
remarks: '',
description: '',
} satisfies Values;
export function LpCategoryCreateForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation(['lp_categories']);
const [isCreating, setIsCreating] = React.useState<boolean>(false);
const {
control,
handleSubmit,
formState: { errors },
setValue,
watch,
} = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });
const onSubmit = React.useCallback(
async (values: Values): Promise<void> => {
setIsCreating(true);
const payload: CreateFormProps = {
cat_name: values.cat_name,
cat_image: values.avatar ? [await base64ToFile(values.avatar)] : null,
pos: values.pos,
init_answer: values.init_answer,
visible: values.visible,
slug: values.slug,
remarks: values.remarks,
description: values.description,
//
// TODO: remove me
type: 'type tet',
isActive: true,
order: 1,
};
try {
const result = await pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).create(payload);
logger.debug(result);
toast.success(t('create.success'));
router.push(paths.dashboard.lp_categories.list);
} catch (error) {
logger.error(error);
toast.error(t('create.failed'));
} finally {
setIsCreating(false);
}
},
// t is not necessary here
// eslint-disable-next-line react-hooks/exhaustive-deps
[router]
);
const avatarInputRef = React.useRef<HTMLInputElement>(null);
const avatar = watch('avatar');
const handleAvatarChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const url = await fileToBase64(file);
setValue('avatar', url);
}
},
[setValue]
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack
divider={<Divider />}
spacing={4}
>
<Stack spacing={3}>
<Typography variant="h6">{t('create.basic-info')}</Typography>
<Grid
container
spacing={3}
>
<Grid xs={12}>
<Stack
direction="row"
spacing={3}
sx={{ alignItems: 'center' }}
>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
borderRadius: '5%',
display: 'inline-flex',
p: '4px',
}}
>
<Avatar
variant="rounded"
src={avatar}
sx={{
'--Avatar-size': '100px',
'--Icon-fontSize': 'var(--icon-fontSize-lg)',
alignItems: 'center',
bgcolor: 'var(--mui-palette-background-level1)',
color: 'var(--mui-palette-text-primary)',
display: 'flex',
justifyContent: 'center',
}}
>
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
</Box>
<Stack
spacing={1}
sx={{ alignItems: 'flex-start' }}
>
<Typography variant="subtitle1">{t('create.avatar')}</Typography>
<Typography variant="caption">{t('create.avatarRequirements')}</Typography>
<Button
color="secondary"
onClick={() => {
avatarInputRef.current?.click();
}}
variant="outlined"
>
{t('create.avatar_select')}
</Button>
<input
hidden
onChange={handleAvatarChange}
ref={avatarInputRef}
type="file"
/>
</Stack>
</Stack>
</Grid>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="cat_name"
render={({ field }) => (
<FormControl
disabled={isCreating}
error={Boolean(errors.cat_name)}
fullWidth
>
<InputLabel required>{t('create.cat_name')}</InputLabel>
<OutlinedInput {...field} />
{errors.cat_name ? <FormHelperText>{errors.cat_name.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="pos"
render={({ field }) => (
<FormControl
error={Boolean(errors.pos)}
fullWidth
>
<InputLabel required>{t('create.pos')}</InputLabel>
<OutlinedInput
{...field}
onChange={(e) => {
field.onChange(parseInt(e.target.value));
}}
type="number"
/>
{errors.pos ? <FormHelperText>{errors.pos.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="slug"
render={({ field }) => (
<FormControl
error={Boolean(errors.slug)}
fullWidth
>
<InputLabel required>{t('create.slug')}</InputLabel>
<OutlinedInput {...field} />
{errors.slug ? <FormHelperText>{errors.slug.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="visible"
render={({ field }) => (
<FormControl
error={Boolean(errors.visible)}
fullWidth
>
<InputLabel>{t('edit.visible')}</InputLabel>
<Select {...field}>
<MenuItem value="visible">{t('edit.visible')}</MenuItem>
<MenuItem value="hidden">{t('edit.hidden')}</MenuItem>
</Select>
{errors.visible ? <FormHelperText>{errors.visible.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="init_answer"
render={({ field }) => (
<FormControl
error={Boolean(errors.init_answer)}
fullWidth
>
<InputLabel required>{t('create.init_answer')}</InputLabel>
<OutlinedInput {...field} />
{errors.init_answer ? <FormHelperText>{errors.init_answer.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
<Stack spacing={3}>
<Typography variant="h6">{t('create.detail-information')}</Typography>
<Grid
container
spacing={3}
>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="description"
render={({ field }) => {
return (
<Box>
<Typography
variant="subtitle1"
color="text-secondary"
>
{t('create.description')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor
{...field}
content=""
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getHTML() } });
}}
placeholder={t('create.description.default')}
/>
</Box>
</Box>
);
}}
/>
</Grid>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isCreating}
control={control}
name="remarks"
render={({ field }) => (
<Box>
<Typography
variant="subtitle1"
color="text.secondary"
>
{t('create.remarks')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor
content=""
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getText() } });
}}
hideToolbar
placeholder={t('create.remarks.default')}
/>
</Box>
</Box>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button
color="secondary"
component={RouterLink}
href={paths.dashboard.lesson_categories.list}
>
{t('create.cancelButton')}
</Button>
<LoadingButton
disabled={isCreating}
loading={isCreating}
type="submit"
variant="contained"
>
{t('create.createButton')}
</LoadingButton>
</CardActions>
</Card>
<Box sx={{ display: isDevelopment ? 'block' : 'none' }}>
<pre>{JSON.stringify({ errors }, null, 2)}</pre>
</Box>
</form>
);
}

View File

@@ -3,88 +3,101 @@
import * as React from 'react';
import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { COL_LESSON_TYPES } from '@/constants';
import getQuizListeningById from '@/db/QuizListenings/GetById';
//
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, MenuItem } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
//
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
// import Checkbox from '@mui/material/Checkbox';
import Divider from '@mui/material/Divider';
import FormControl from '@mui/material/FormControl';
// import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import type { RecordModel } from 'pocketbase';
import PocketBase from 'pocketbase';
//
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
//
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';
import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { base64ToFile, fileToBase64 } from '@/lib/file-to-base64';
import { pb } from '@/lib/pb';
// import { Option } from '@/components/core/option';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';
import { EditFormProps } from '@/components/dashboard/lp_categories/type';
import FormLoading from '@/components/loading';
import { LessonTypeEditFormProps } from '../lesson_type/lesson-type';
import { defaultLpCategory } from './_constants';
// import { getLessonTypeById, updateLessonType } from './http-actions';
// import { LessonTypeEditFormProps } from './types';
// import { defaultLessonType, type LessonTypeEditFormProps } from './interfaces';
// function fileToBase64(file: Blob): Promise<string> {
// return new Promise((resolve, reject) => {
// const reader = new FileReader();
// reader.readAsDataURL(file);
// reader.onload = () => {
// resolve(reader.result as string);
// };
// reader.onerror = () => {
// reject(new Error('Error converting file to base64'));
// };
// });
// }
import ErrorDisplay from '../error';
import type { EditFormProps } from './type';
// TODO: review this
const schema = zod.object({
cat_name: zod.string().min(1, 'Name is required').max(255),
type: zod.string().min(1, 'Name is required').max(255),
slug: zod.string().min(1, 'Name is required').max(255),
pos: zod.number().min(1, 'Phone is required').max(15),
visible_to_user: zod.string().max(255),
cat_name: zod.string().min(1, 'name-is-required').max(255),
// accept file object when user change image
// accept http string when user not changing image
cat_image: zod.union([zod.array(zod.any()), zod.string()]).optional(),
// position
pos: zod.number().min(1, 'position is required').max(99),
// it should be a valid JSON
init_answer: zod
.string()
.refine(
(value) => {
try {
JSON.parse(value);
return true;
} catch (error) {
return false;
}
},
{ message: 'init_answer must be a valid JSON' }
)
.optional(),
visible: zod.string(),
slug: zod.string().min(0, 'slug-is-required').max(255).optional(),
remarks: zod.string().optional(),
description: zod.string().optional(),
// NOTE: for image handling
avatar: zod.string().optional(),
});
type Values = zod.infer<typeof schema>;
const defaultValues = {
cat_name: '',
slug: '',
type: '',
cat_image: undefined,
pos: 1,
visible_to_user: 'visible',
init_answer: JSON.stringify({}),
visible: 'hidden',
slug: '',
remarks: '',
description: '',
} satisfies Values;
export function LpCategoryEditForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation();
const { typeId } = useParams<{ typeId: string }>();
const { t } = useTranslation(['lp_categories']);
const { cat_id: catId } = useParams<{ cat_id: string }>();
//
const [isUpdating, setIsUpdating] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(false);
//
const [showError, setShowError] = React.useState({ show: false, detail: '' });
const {
control,
@@ -95,92 +108,144 @@ export function LpCategoryEditForm(): React.JSX.Element {
watch,
} = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });
const onSubmit = React.useCallback(async (values: Values): Promise<void> => {
const onSubmit = React.useCallback(
async (values: Values): Promise<void> => {
setIsUpdating(true);
const tempUpdate: EditFormProps = {
cat_name: values.cat_name,
type: values.type,
cat_image: values.avatar ? [await base64ToFile(values.avatar)] : null,
pos: values.pos,
visible: values.visible_to_user ? 'visible' : 'hidden',
init_answer: JSON.parse(values.init_answer) || {},
visible: values.visible,
slug: values.slug || 'not-defined',
remarks: values.remarks,
description: values.description,
//
// TODO: remove below
type: '',
};
pb.collection(COL_LESSON_TYPES)
.update(typeId, tempUpdate)
.then((res) => {
logger.debug(res);
toast.success(t('dashboard.lessonTypes.update.success'));
try {
const result = await pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).update(catId, tempUpdate);
logger.debug(result);
toast.success(t('edit.success'));
router.push(paths.dashboard.lp_categories.list);
} catch (error) {
logger.error(error);
toast.error(t('update.failed'));
} finally {
setIsUpdating(false);
router.push(paths.dashboard.lesson_types.list);
})
.catch((err) => {
logger.error(err);
toast.error('Something went wrong!');
setIsUpdating(false);
});
}, []);
}
},
// t is not necessary here
// eslint-disable-next-line react-hooks/exhaustive-deps
[router]
);
const avatarInputRef = React.useRef<HTMLInputElement>(null);
// const avatar = watch('avatar');
const avatar = watch('avatar');
const handleAvatarChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
// const url = await fileToBase64(file);
// setValue('avatar', url);
const url = await fileToBase64(file);
setValue('avatar', url);
}
},
[setValue]
);
const handleLoad = React.useCallback(
(id: string) => {
// TODO: need to align with save form
// use trycatch
const [textDescription, setTextDescription] = React.useState<string>('');
const [textRemarks, setTextRemarks] = React.useState<string>('');
// load existing data when user arrive
const loadExistingData = React.useCallback(
async (id: string) => {
setShowLoading(true);
getQuizListeningById(id)
.then((model: RecordModel) => {
reset({ ...defaultLpCategory, ...model });
})
.catch((err) => {
logger.error(err);
toast(t('dashboard.lessonTypes.list.error'));
})
.finally(() => {
try {
const result = await pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).getOne(id);
reset({ ...defaultValues, ...result, init_answer: JSON.stringify(result.init_answer) });
setTextDescription(result.description);
setTextRemarks(result.remarks);
if (result.cat_image !== '') {
const fetchResult = await fetch(
`http://127.0.0.1:8090/api/files/${result.collectionId}/${result.id}/${result.cat_image}`
);
const blob = await fetchResult.blob();
const url = await fileToBase64(blob);
setValue('avatar', url);
} else {
setValue('avatar', '');
}
} catch (error) {
logger.error(error);
toast(t('list.error'));
setShowError({ show: true, detail: JSON.stringify(error, null, 2) });
} finally {
setShowLoading(false);
});
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[typeId]
[catId]
);
React.useEffect(() => {
handleLoad(typeId);
void loadExistingData(catId);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [typeId]);
}, [catId]);
if (showLoading) return <FormLoading />;
if (showError.show)
return (
<ErrorDisplay
message={t('error.unable-to-process-request')}
code="500"
details={showError.detail}
/>
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack divider={<Divider />} spacing={4}>
<Stack
divider={<Divider />}
spacing={4}
>
<Stack spacing={3}>
<Typography variant="h6">{t('dashboard.lessonTypes.edit.typeInformation')}</Typography>
<Grid container spacing={3}>
<Typography variant="h6">{t('edit.basic-info')}</Typography>
<Grid
container
spacing={3}
>
<Grid xs={12}>
<Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={3}
sx={{ alignItems: 'center' }}
>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
borderRadius: '50%',
borderRadius: '5%',
display: 'inline-flex',
p: '4px',
}}
>
{/*
<Avatar
variant="rounded"
src={avatar}
sx={{
'--Avatar-size': '100px',
@@ -194,11 +259,13 @@ export function LpCategoryEditForm(): React.JSX.Element {
>
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
*/}
</Box>
<Stack spacing={1} sx={{ alignItems: 'flex-start' }}>
<Typography variant="subtitle1">{t('dashboard.lessonTypes.edit.avatar')}</Typography>
<Typography variant="caption">{t('dashboard.lessonTypes.edit.avatarRequirements')}</Typography>
<Stack
spacing={1}
sx={{ alignItems: 'flex-start' }}
>
<Typography variant="subtitle1">{t('edit.avatar')}</Typography>
<Typography variant="caption">{t('edit.avatarRequirements')}</Typography>
<Button
color="secondary"
onClick={() => {
@@ -206,45 +273,53 @@ export function LpCategoryEditForm(): React.JSX.Element {
}}
variant="outlined"
>
{t('dashboard.lessonTypes.edit.select')}
{t('edit.avatar_select')}
</Button>
<input hidden onChange={handleAvatarChange} ref={avatarInputRef} type="file" />
<input
hidden
onChange={handleAvatarChange}
ref={avatarInputRef}
type="file"
/>
</Stack>
</Stack>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="cat_name"
render={({ field }) => (
<FormControl error={Boolean(errors.cat_name)} fullWidth>
<InputLabel required>{t('dashboard.lessonTypes.edit.name')}</InputLabel>
<FormControl
disabled={isUpdating}
error={Boolean(errors.cat_name)}
fullWidth
>
<InputLabel required>{t('edit.cat_name')}</InputLabel>
<OutlinedInput {...field} />
{errors.cat_name ? <FormHelperText>{errors.cat_name.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
control={control}
name="type"
render={({ field }) => (
<FormControl error={Boolean(errors.type)} fullWidth>
<InputLabel required>{t('dashboard.lessonTypes.edit.type')}</InputLabel>
<OutlinedInput {...field} />
{errors.type ? <FormHelperText>{errors.type.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="pos"
render={({ field }) => (
<FormControl error={Boolean(errors.pos)} fullWidth>
<InputLabel required>{t('dashboard.lessonTypes.edit.position')}</InputLabel>
<FormControl
error={Boolean(errors.pos)}
fullWidth
>
<InputLabel required>{t('edit.pos')}</InputLabel>
<OutlinedInput
{...field}
onChange={(e) => {
@@ -252,41 +327,170 @@ export function LpCategoryEditForm(): React.JSX.Element {
}}
type="number"
/>
{errors.pos ? <FormHelperText>{errors.pos.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="visible_to_user"
name="slug"
render={({ field }) => (
<FormControl error={Boolean(errors.visible_to_user)} fullWidth>
<InputLabel>{t('dashboard.lessonTypes.edit.visibleToUser')}</InputLabel>
<FormControl
error={Boolean(errors.slug)}
fullWidth
>
<InputLabel required>{t('edit.slug')}</InputLabel>
<OutlinedInput {...field} />
{errors.slug ? <FormHelperText>{errors.slug.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="visible"
render={({ field }) => (
<FormControl
error={Boolean(errors.visible)}
fullWidth
>
<InputLabel>{t('edit.visible')}</InputLabel>
<Select {...field}>
<MenuItem value="visible">{t('dashboard.lessonTypes.edit.visible')}</MenuItem>
<MenuItem value="hidden">{t('dashboard.lessonTypes.edit.hidden')}</MenuItem>
<MenuItem value="visible">{t('edit.visible')}</MenuItem>
<MenuItem value="hidden">{t('edit.hidden')}</MenuItem>
</Select>
{errors.visible_to_user ? (
<FormHelperText>{errors.visible_to_user.message}</FormHelperText>
) : null}
{errors.visible ? <FormHelperText>{errors.visible.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="init_answer"
render={({ field }) => (
<FormControl
error={Boolean(errors.init_answer)}
fullWidth
>
<InputLabel required>{t('edit.init_answer')}</InputLabel>
<OutlinedInput {...field} />
{errors.init_answer ? <FormHelperText>{errors.init_answer.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
<Stack spacing={3}>
<Typography variant="h6">{t('edit.detail-information')}</Typography>
<Grid
container
spacing={3}
>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="description"
render={({ field }) => {
return (
<Box>
<Typography
variant="subtitle1"
color="text-secondary"
>
{t('edit.description')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '200px' } }}>
<TextEditor
{...field}
content={textDescription}
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getHTML() } });
}}
placeholder={t('edit.description.default')}
/>
</Box>
</Box>
);
}}
/>
</Grid>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="remarks"
render={({ field }) => (
<Box>
<Typography
variant="subtitle1"
color="text.secondary"
>
{t('edit.remarks')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '200px' } }}>
<TextEditor
content={textRemarks}
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getText() } });
}}
hideToolbar
placeholder={t('edit.remarks.default')}
/>
</Box>
</Box>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button color="secondary" component={RouterLink} href={paths.dashboard.lesson_types.list}>
{t('dashboard.lessonTypes.edit.cancelButton')}
<Button
color="secondary"
component={RouterLink}
href={paths.dashboard.lp_categories.list}
>
{t('edit.cancelButton')}
</Button>
<LoadingButton disabled={isUpdating} loading={isUpdating} type="submit" variant="contained">
{t('dashboard.lessonTypes.edit.updateButton')}
<LoadingButton
disabled={isUpdating}
loading={isUpdating}
type="submit"
variant="contained"
>
{t('edit.updateButton')}
</LoadingButton>
</CardActions>
</Card>

View File

@@ -1,7 +1,6 @@
'use client';
import * as React from 'react';
import { Notification } from '@/app/dashboard/Sample/Notifications/type';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
@@ -13,14 +12,19 @@ import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { EnvelopeSimple as EnvelopeSimpleIcon } from '@phosphor-icons/react/dist/ssr/EnvelopeSimple';
import { useTranslation } from 'react-i18next';
// import type { Notification } from '@/types/type';
import { dayjs } from '@/lib/dayjs';
import { DataTable } from '@/components/core/data-table';
import type { ColumnDef } from '@/components/core/data-table';
import { Option } from '@/components/core/option';
export interface Notification {
id: string;
type: string;
status: 'delivered' | 'pending' | 'failed';
createdAt: Date;
}
const columns = [
{
formatter: (row): React.JSX.Element => (
@@ -61,8 +65,6 @@ export interface NotificationsProps {
}
export function Notifications({ notifications }: NotificationsProps): React.JSX.Element {
const { t } = useTranslation();
return (
<Card>
<CardHeader
@@ -71,19 +73,19 @@ export function Notifications({ notifications }: NotificationsProps): React.JSX.
<EnvelopeSimpleIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
}
title={t('Notifications')}
title="Notifications"
/>
<CardContent>
<Stack spacing={3}>
<Stack spacing={2}>
<Select defaultValue="last_invoice" name="type" sx={{ maxWidth: '100%', width: '320px' }}>
<Option value="last_invoice">{t('Resend last invoice')}</Option>
<Option value="password_reset">{t('Send password reset')}</Option>
<Option value="verification">{t('Send verification')}</Option>
<Option value="last_invoice">Resend last invoice</Option>
<Option value="password_reset">Send password reset</Option>
<Option value="verification">Send verification</Option>
</Select>
<div>
<Button startIcon={<EnvelopeSimpleIcon />} variant="contained">
{t('Send email')}
Send email
</Button>
</div>
</Stack>

View File

@@ -14,7 +14,6 @@ import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import { ShoppingCartSimple as ShoppingCartSimpleIcon } from '@phosphor-icons/react/dist/ssr/ShoppingCartSimple';
import { useTranslation } from 'react-i18next';
import { dayjs } from '@/lib/dayjs';
import type { ColumnDef } from '@/components/core/data-table';
@@ -79,13 +78,12 @@ export interface PaymentsProps {
}
export function Payments({ ordersValue, payments = [], refundsValue, totalOrders }: PaymentsProps): React.JSX.Element {
const { t } = useTranslation();
return (
<Card>
<CardHeader
action={
<Button color="secondary" startIcon={<PlusIcon />}>
{t('Create Payment')}
Create Payment
</Button>
}
avatar={
@@ -93,7 +91,7 @@ export function Payments({ ordersValue, payments = [], refundsValue, totalOrders
<ShoppingCartSimpleIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
}
title={t('Payments')}
title="Payments"
/>
<CardContent>
<Stack spacing={3}>
@@ -106,13 +104,13 @@ export function Payments({ ordersValue, payments = [], refundsValue, totalOrders
>
<div>
<Typography color="text.secondary" variant="overline">
{t('Total orders')}
Total orders
</Typography>
<Typography variant="h6">{new Intl.NumberFormat('en-US').format(totalOrders)}</Typography>
</div>
<div>
<Typography color="text.secondary" variant="overline">
{t('Orders value')}
Orders value
</Typography>
<Typography variant="h6">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(ordersValue)}
@@ -120,7 +118,7 @@ export function Payments({ ordersValue, payments = [], refundsValue, totalOrders
</div>
<div>
<Typography color="text.secondary" variant="overline">
{t('Refunds')}
Refunds
</Typography>
<Typography variant="h6">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(refundsValue)}

View File

@@ -1,5 +1,3 @@
'use client';
import * as React from 'react';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
@@ -8,17 +6,22 @@ import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { PencilSimple as PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr/PencilSimple';
import { useTranslation } from 'react-i18next';
import type { Address } from '@/types/Address';
export interface Address {
id: string;
country: string;
state: string;
city: string;
zipCode: string;
street: string;
primary?: boolean;
}
export interface ShippingAddressProps {
address: Address;
}
export function ShippingAddress({ address }: ShippingAddressProps): React.ReactElement {
const { t } = useTranslation();
return (
<Card sx={{ borderRadius: 1, height: '100%' }} variant="outlined">
<CardContent>
@@ -31,9 +34,9 @@ export function ShippingAddress({ address }: ShippingAddressProps): React.ReactE
{address.zipCode}
</Typography>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
{address.primary ? <Chip color="warning" label={t('Primary')} variant="soft" /> : <span />}
{address.primary ? <Chip color="warning" label="Primary" variant="soft" /> : <span />}
<Button color="secondary" size="small" startIcon={<PencilSimpleIcon />}>
{t('Edit')}
Edit
</Button>
</Stack>
</Stack>

View File

@@ -12,36 +12,45 @@ export interface LpCategory {
lesson_id: string;
description: string;
remarks: string;
createdAt: Date;
visible: 'pending' | 'active' | 'blocked' | 'NA' | 'visible' | 'hidden';
//
name: string;
avatar: string;
email: string;
phone: string;
quota: number;
status: 'pending' | 'active' | 'blocked' | 'NA';
isActive: boolean;
order: number;
imageUrl: string;
createdAt: Date;
}
export interface CreateForm {
name: string;
type: string;
export interface CreateFormProps {
cat_name: string;
cat_image: File[] | null;
pos: number;
init_answer?: string;
visible: string;
description: string;
slug: string;
remarks?: string;
description?: string;
//
// TODO: to remove
type: string;
isActive: boolean;
order: number;
imageUrl: string;
name?: string;
imageUrl?: string;
}
export interface EditFormProps {
cat_name: string;
cat_image: File[] | null;
pos: number;
init_answer: any;
visible: string;
description?: string;
slug: string;
remarks?: string;
description?: string;
//
// TODO: remove below
type: string;
}

View File

@@ -1,44 +1,60 @@
'use client';
/*
# PROMPT
this is a subset of a typescript project
clone `LessonTypeCount`, `LessonCategoriesCount` to `UserCount` and do modifiy to get the count of users, thanks.
*/
import * as React from 'react';
import getAllUserMetasCount from '@/db/UserMetas/GetAllCount';
// import GetAllUsersCount from '@/db/Users/GetAllCount.tsx';
import { Typography } from '@mui/material';
import { Users as UsersIcon } from '@phosphor-icons/react/dist/ssr/Users';
import { useTranslation } from 'react-i18next';
import { Summary } from '@/components/dashboard/overview/summary';
import { LoadingSummary } from '../LoadingSummary';
function ActiveUserCount(): React.JSX.Element {
const { t } = useTranslation();
const [amount, setAmount] = React.useState<number>(0);
const [isLoading, setIsLoading] = React.useState<boolean>(true);
const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState<boolean>(false);
const [errorDetail, setErrorDetail] = React.useState<string>('');
React.useEffect(() => {
getAllUserMetasCount()
.then((count) => {
setAmount(count);
setIsLoading(false);
})
.catch((err) => {
setAmount(-99);
});
async function count(): Promise<void> {
try {
const tempCount = await getAllUserMetasCount();
setAmount(tempCount);
} catch (error) {
setAmount(-9);
setErrorDetail(JSON.stringify(error));
setShowError(true);
} finally {
setShowLoading(false);
}
}
void count();
}, []);
if (isLoading) {
return <Typography>Loading...</Typography>;
if (showLoading) {
return <LoadingSummary diff={10} icon={UsersIcon} title={t('用戶數量')} trend="up" />;
}
if (showError) return <div>{errorDetail}</div>;
return (
<Summary
amount={amount}
diff={10}
icon={UsersIcon}
title={t('用戶數量1')}
title={t('用戶數量')}
trend="up"
//
/>
);
}
export default ActiveUserCount;
export default React.memo(ActiveUserCount);

View File

@@ -8,35 +8,43 @@ this is a subset of a typescript project
clone `LessonTypeCount`, `LessonCategoriesCount` to `UserCount` and do modifiy to get the count of users, thanks.
*/
import * as React from 'react';
import GetAllCount from '@/db/LessonCategories/GetAllCount.tsx';
import { Typography } from '@mui/material';
import getAllLessonCategoriesCount from '@/db/LessonCategories/GetAllCount.tsx';
import { ListChecks as ListChecksIcon } from '@phosphor-icons/react/dist/ssr/ListChecks';
import { useTranslation } from 'react-i18next';
import { Summary } from '@/components/dashboard/overview/summary';
import { LoadingSummary } from '../LoadingSummary';
function LessonCategoriesCount(): React.JSX.Element {
const { t } = useTranslation();
const [amount, setAmount] = React.useState<number>(0);
const [isLoading, setIsLoading] = React.useState<boolean>(true);
const [showLoading, setShowLoading] = React.useState<boolean>(true);
const [showError, setShowError] = React.useState<boolean>(false);
const [errorDetail, setErrorDetail] = React.useState<string>('');
React.useEffect(() => {
GetAllCount()
.then((count) => {
setAmount(count);
})
.catch((err) => {
// console.error(err);
})
.finally(() => {
setIsLoading(false);
});
async function count(): Promise<void> {
try {
const tempCount = await getAllLessonCategoriesCount();
setAmount(tempCount);
} catch (error) {
setAmount(-9);
setErrorDetail(JSON.stringify(error));
setShowError(true);
} finally {
setShowLoading(false);
}
}
void count();
}, []);
if (isLoading) {
return <Typography>Loading</Typography>;
if (showLoading) {
return <LoadingSummary diff={10} icon={ListChecksIcon} title={t('用戶數量')} trend="up" />;
}
if (showError) return <div>{errorDetail}</div>;
return (
<Summary
amount={amount}

View File

@@ -1,52 +1,43 @@
'use client';
/*
# PROMPT
this is a subset of a typescript project
clone `LessonTypeCount` to `LessonCategoriesCount` and do modifiy to get the count of lesson category, thanks.
*/
import * as React from 'react';
import GetAllCount from '@/db/LessonTypes/GetAllCount.tsx';
import { Typography } from '@mui/material';
import { ListChecks as ListChecksIcon } from '@phosphor-icons/react/dist/ssr/ListChecks';
import { useTranslation } from 'react-i18next';
import { Summary } from '@/components/dashboard/overview/summary';
import { LoadingSummary } from '@/components/dashboard/overview/summary/LoadingSummary';
function LessonTypeCount(): React.JSX.Element {
const { t } = useTranslation();
const [amount, setAmount] = React.useState<number>(0);
const [isLoading, setIsLoading] = React.useState<boolean>(true);
const [error, setError] = React.useState<string | null>(null);
React.useEffect(() => {
GetAllCount()
.then((count) => {
const fetchData = async () => {
try {
const count = await GetAllCount();
setAmount(count);
})
.catch((err) => {
// console.error(err);
})
.finally(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setIsLoading(false);
});
}
};
void fetchData();
}, []);
if (isLoading) {
return <Typography>Loading...</Typography>;
return <LoadingSummary />;
}
return (
<Summary
amount={amount}
diff={15}
icon={ListChecksIcon}
title={t('課程類型')}
trend="up"
//
/>
);
if (error) {
return <Summary amount={0} diff={0} icon={ListChecksIcon} title={t('Error')} trend="down" />;
}
return <Summary amount={amount} diff={15} icon={ListChecksIcon} title={t('課程類型')} trend="up" />;
}
export default React.memo(LessonTypeCount);

View File

@@ -0,0 +1,81 @@
'use client';
/*
# PROMPT
this is a subset of a typescript project
clone `LessonTypeCount`, `LessonCategoriesCount` to `UserCount` and do modifiy to get the count of users, thanks.
*/
import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import type { Icon } from '@phosphor-icons/react/dist/lib/types';
import { TrendDown as TrendDownIcon } from '@phosphor-icons/react/dist/ssr/TrendDown';
import { TrendUp as TrendUpIcon } from '@phosphor-icons/react/dist/ssr/TrendUp';
import { useTranslation } from 'react-i18next';
export interface SummaryProps {
diff: number;
icon: Icon;
title: string;
trend: 'up' | 'down';
}
export function LoadingSummary({ diff, icon: Icon, title, trend }: SummaryProps): React.JSX.Element {
const { t } = useTranslation();
return (
<Card>
<CardContent>
<Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
<Avatar
sx={{
'--Avatar-size': '48px',
bgcolor: 'var(--mui-palette-background-paper)',
boxShadow: 'var(--mui-shadows-8)',
color: 'var(--mui-palette-text-primary)',
}}
>
<Icon fontSize="var(--icon-fontSize-lg)" />
</Avatar>
<div>
<Typography color="text.secondary" variant="body1">
{title}
</Typography>
<Typography variant="h3">Loading</Typography>
</div>
</Stack>
</CardContent>
<Divider />
<Box sx={{ p: '16px' }}>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
<Box
sx={{
alignItems: 'center',
color: trend === 'up' ? 'var(--mui-palette-success-main)' : 'var(--mui-palette-error-main)',
display: 'flex',
justifyContent: 'center',
}}
>
{trend === 'up' ? (
<TrendUpIcon fontSize="var(--icon-fontSize-md)" />
) : (
<TrendDownIcon fontSize="var(--icon-fontSize-md)" />
)}
</Box>
<Typography color="text.secondary" variant="body2">
<Typography color={trend === 'up' ? 'success.main' : 'error.main'} component="span" variant="subtitle2">
{new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 2 }).format(diff / 100)}
</Typography>{' '}
{trend === 'up' ? t('increase') : t('decrease')} {t('vs last month')}
</Typography>
</Stack>
</Box>
</Card>
);
}

View File

@@ -6,7 +6,10 @@ const NO_NUM = -Infinity;
const NS_LESSON_CATEGORY = 'lesson_category';
const COL_USERS = 'users';
const COL_USER_METAS = 'UserMetas';
const COL_QUIZ_LISTENINGS = 'QuizLPCategories';
// do not use LP_CATEGORIES
const COL_LISTENINGS_PRACTICE_CATEGORIES = 'QuizLPCategories';
const COL_QUIZ_LP_QUESTIONS = 'QuizLPQuestions';
export {
COL_LESSON_TYPES,
@@ -16,6 +19,7 @@ export {
NS_LESSON_CATEGORY,
COL_USERS,
COL_USER_METAS,
COL_QUIZ_LISTENINGS,
COL_LISTENINGS_PRACTICE_CATEGORIES,
COL_QUIZ_LP_QUESTIONS,
//
};

View File

@@ -79,3 +79,8 @@ please revise
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/types/LpCategory.tsx` `interface LpCategory`
to the collection `QuizLPCategories` align the dbml file in the previous prompt
please modify `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/lp_categories/_constants.tsx`
to follow the type definition in `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/types/LpCategory.tsx`, the constant `defaultLpCategory`

View File

@@ -2,8 +2,8 @@ import { COL_LESSON_CATEGORIES } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
import type { CreateForm } from '@/components/dashboard/lp_categories/type';
import type { CreateFormProps } from '@/components/dashboard/lp_categories/type';
export default function createLessonCategory(data: CreateForm): Promise<RecordModel> {
export default function createLessonCategory(data: CreateFormProps): Promise<RecordModel> {
return pb.collection(COL_LESSON_CATEGORIES).create(data);
}

View File

@@ -1,9 +1,14 @@
// REQ0006
// RULES:
// error handled by caller
// contain definition to collection only
import { COL_LESSON_CATEGORIES } from '@/constants';
import { pb } from '@/lib/pb';
export default async function GetAllCount(): Promise<number> {
const { totalItems: count } = await pb.collection(COL_LESSON_CATEGORIES).getList(1, 9999, {});
return count;
export default function getAllLessonCategoriesCount(): Promise<number> {
return pb
.collection(COL_LESSON_CATEGORIES)
.getList(1, 9999)
.then((res) => res.totalItems);
}

View File

@@ -2,8 +2,8 @@ import { COL_LESSON_CATEGORIES } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
import type { CreateForm } from '@/components/dashboard/lp_categories/type';
import type { CreateFormProps } from '@/components/dashboard/lp_categories/type';
export default function updateLessonCategory(id: string, data: CreateForm): Promise<RecordModel> {
export default function updateLessonCategory(id: string, data: CreateFormProps): Promise<RecordModel> {
return pb.collection(COL_LESSON_CATEGORIES).update(id, data);
}

View File

@@ -1,8 +1,8 @@
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
export default function deleteQuizListening(id: string): Promise<boolean> {
return pb.collection(COL_QUIZ_LISTENINGS).delete(id);
return pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).delete(id);
}

View File

@@ -1,8 +1,8 @@
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
export default function getAllQuizListenings(): Promise<RecordModel[]> {
return pb.collection(COL_QUIZ_LISTENINGS).getFullList();
return pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).getFullList();
}

View File

@@ -1,9 +1,9 @@
// REQ0006
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { pb } from '@/lib/pb';
export default async function GetAllCount(): Promise<number> {
const { totalItems: count } = await pb.collection(COL_QUIZ_LISTENINGS).getList(1, 9999, {});
const { totalItems: count } = await pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).getList(1, 9999, {});
return count;
}

View File

@@ -1,8 +1,8 @@
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import type { RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
export default function getQuizListeningById(id: string): Promise<RecordModel> {
return pb.collection(COL_QUIZ_LISTENINGS).getOne(id);
return pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).getOne(id);
}

View File

@@ -1,11 +1,13 @@
// REQ0006
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { pb } from '@/lib/pb';
export default async function GetHiddenCount(): Promise<number> {
try {
const result = await pb.collection(COL_QUIZ_LISTENINGS).getList(1, 9999, { filter: 'visible = "hidden"' });
const result = await pb
.collection(COL_LISTENINGS_PRACTICE_CATEGORIES)
.getList(1, 9999, { filter: 'visible = "hidden"' });
const { totalItems: count } = result;
return count;
} catch (error) {

View File

@@ -1,11 +1,13 @@
// REQ0006
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import { pb } from '@/lib/pb';
export default async function GetVisibleCount(): Promise<number> {
try {
const result = await pb.collection(COL_QUIZ_LISTENINGS).getList(1, 9999, { filter: 'visible = "visible"' });
const result = await pb
.collection(COL_LISTENINGS_PRACTICE_CATEGORIES)
.getList(1, 9999, { filter: 'visible = "visible"' });
const { totalItems: count } = result;
return count;
} catch (error) {

View File

@@ -1,4 +1,4 @@
import { COL_QUIZ_LISTENINGS } from '@/constants';
import { COL_LISTENINGS_PRACTICE_CATEGORIES } from '@/constants';
import type { ListResult, RecordModel } from 'pocketbase';
import { pb } from '@/lib/pb';
@@ -18,5 +18,5 @@ export default function listWithOption({
rowsPerPage,
listOption = {},
}: ListWithOptionParams): Promise<ListResult<RecordModel>> {
return pb.collection(COL_QUIZ_LISTENINGS).getList(currentPage + 1, rowsPerPage, listOption);
return pb.collection(COL_LISTENINGS_PRACTICE_CATEGORIES).getList(currentPage + 1, rowsPerPage, listOption);
}

View File

@@ -1,13 +1,14 @@
// RULES:
// error handled by caller
// contain definition to collection only
import { COL_USER_METAS } from '@/constants';
import { pb } from '@/lib/pb';
export default async function getAllUserMetasCount(): Promise<number> {
try {
const result = await pb.collection(COL_USER_METAS).getList(1, 9998);
return result.totalItems;
} catch (error) {
console.error(error);
return -99;
}
export default function getAllUserMetasCount(): Promise<number> {
return pb
.collection(COL_USER_METAS)
.getList(1, 9998)
.then((res) => res.totalItems);
}

View File

@@ -0,0 +1,23 @@
Hi, please study the documentation below,
i will send you the task afterwards,
please read and understand the documentation below and link up the ideas
reply `OK` when you done
no need to state me any other things, thanks
1. `schema.dbml`
- this describe the database schema in dbml format
- filepath: `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/001_documentation/Requirements/REQ0006/schema.dbml`
2. `schema.json`
- this is the schema export in pocketbase format
- filepath: `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db/schema.json`
3. `_AI_GUIDELINE`:
- there are the markdown files that help you better understand the implementation
- directory: `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/_AI_GUIDELINE`
thanks

View File

@@ -0,0 +1,35 @@
update `LpCategoryDefaultValue`
in file `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/lp_categories/_constants.ts`
thanks
you can find the type def in `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/types/LpCategory.tsx`
please help to draft code file:
base_dir=`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db`
using
`$base_dir/QuizListenings/GetHiddenCount.tsx`,
`$base_dir/QuizListenings/GetVisibleCount.tsx`,
`$base_dir/LessonTypes/GetHiddenCount.tsx`,
`$base_dir/LessonTypes/GetVisibleCount.tsx`,
as reference,
look into the all directories under base_dir e.g. `QuizCategories`.
propergate `GetHiddenCount.tsx` and `GetVisibleCount.tsx` if missing, do the change to suit the collection.
use `<filename>.draft.tsx` instead when you write file
---
rewrite `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db/LessonCategories/GetAllCount.tsx` to match `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db/UserMetas/GetAllCount.tsx` style
---
style rewrite
study
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/overview/summary/ActiveUserCount/index.tsx`
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/overview/summary/LessonCategoriesCount/index.tsx`
and rewrite `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/overview/summary/LessonTypeCount/index.tsx` to match style above thanks

View File

@@ -0,0 +1,47 @@
please draft with idea:
```
await pb
.collection(COL_LESSON_TYPES)
.getList(currentPage + 1, rowsPerPage, listOption);
```
for Listening Practice
thanks
I want you to clone
from `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db/LessonTypes/GetVisibleCount.tsx` (source file)
to `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db/QuizListenings/GetVisibleCount.tsx` (dest file)
please extract , link up and remember the document properties
(e.g. types, functions, variables, constants, etc)
from source file
draft dest file
update the variables and properties of dest file to reflect `listening practice categories`/`lp_categories`
---
## task
update `schema.dbml` to reflect `schema.json`
## details
Hi,
I have a pocketbase export json file:
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/pocketbase/pb_hooks/seed/schema.json`
and a dbml file:
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/001_documentation/Requirements/REQ0006/schema.dbml`
the collection name in pocketbase should be reflected by a table in dbml,
## steps
compare `schema.json` and `schema.dbml`
please keep `schema.json` remain unchanged
update `schema.dbml` to reflect `schema.json`
do check again when finished

View File

@@ -0,0 +1,57 @@
---
clone `GetVisibleCount.tsx` and `GetHiddenCount.tsx` from `LessonTypes` to `LessonCategories` and update it
please draft `GetHiddenCount.tsx` for COL_LESSON_TYPES and `status = hidden`
well done !, please proceed to another request
working directory: `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/db`
according information from `schema.json`, get the collection of `Students`
pleaes clone the `tsx` files from `LessonTypes` and `LessonCategories` to `Students` and update the content
when you draft coding, review file and append with `.tsx.draft`
---
- this is part of react typescript project, with pocketbase
- `schema.dbml`, describe the collections(tables)
- folder `LessonCategories`, the correct references
- folder `LessonTypes`, the correct references
- you can find the `schema.dbml` and schema information from `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/001_documentation/Requirements/REQ0006`
- do not read root directory, assume it is a fresh copy of nextjs project is ok
## instruction
- break the questions into smaller parts
- review file append with `.draft`, see if the content aligned with the correct references
- read and understand `dbml` file
- lookup the every folder
## tasks
Thanks
---
please take a look in `schema.dbml` and `schema.json`,
associate the collection from json file to the table in dbml file
please modify the `schema.dbml` to align with `schema.json`
to the collection `QuizLPCategories` align the dbml file in the previous prompt
---
please revise
please revise
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/types/LpCategory.tsx` `interface LpCategory`
to the collection `QuizLPCategories` align the dbml file in the previous prompt
please modify `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/lp_categories/_constants.tsx`
to follow the type definition in `/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/types/LpCategory.tsx`, the constant `defaultLpCategory`

View File

@@ -0,0 +1,6 @@
`/home/logic/_wsl_workspace/001_github_ws/lettersoup-online-ws/lettersoup-online/project/002_source/cms/src/components/dashboard/lp_categories/lp-categories-filters.tsx`
this file is original for `lesson_category` model,
please modify it to fit `lp_category` (listening practice category)
thanks

View File

@@ -1356,6 +1356,59 @@
"presentable": false,
"system": false,
"type": "autodate"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2058414169",
"max": 0,
"min": 0,
"name": "visible",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2560465762",
"max": 0,
"min": 0,
"name": "slug",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1156222427",
"max": 0,
"min": 0,
"name": "remarks",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"convertURLs": false,
"hidden": false,
"id": "editor1843675174",
"maxSize": 0,
"name": "description",
"presentable": false,
"required": false,
"system": false,
"type": "editor"
}
],
"indexes": [],

View File

@@ -10,3 +10,20 @@ export function fileToBase64(file: Blob): Promise<string> {
};
});
}
export function base64ToFile(base64String: string, filename?: string): Promise<File> {
return new Promise((resolve, reject) => {
const arr = base64String.split(',');
const type = arr[0].match(/:(.*?);/)![1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], filename || 'file', { type });
resolve(file);
});
}