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

@@ -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> => {
setIsUpdating(true);
const tempUpdate: EditFormProps = {
cat_name: values.cat_name,
type: values.type,
pos: values.pos,
visible: values.visible_to_user ? 'visible' : 'hidden',
};
const onSubmit = React.useCallback(
async (values: Values): Promise<void> => {
setIsUpdating(true);
pb.collection(COL_LESSON_TYPES)
.update(typeId, tempUpdate)
.then((res) => {
logger.debug(res);
toast.success(t('dashboard.lessonTypes.update.success'));
const tempUpdate: EditFormProps = {
cat_name: values.cat_name,
cat_image: values.avatar ? [await base64ToFile(values.avatar)] : null,
pos: values.pos,
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: '',
};
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(() => {
setShowLoading(false);
});
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>
);
}