Compare commits

...

2 Commits

Author SHA1 Message Date
louiscklaw
834f58bde1 update, 2025-05-30 01:14:10 +08:00
louiscklaw
98bc3fe3ce update, 2025-05-30 01:13:54 +08:00
56 changed files with 636 additions and 642 deletions

View File

@@ -511,7 +511,7 @@ model UserCard {
}
model UserItem {
id Int @id @default(autoincrement())
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//

View File

@@ -20,13 +20,13 @@ async function userItem() {
const username = `${firstName.toLowerCase()}-${lastName.toLowerCase()}`;
const alice = await prisma.userItem.upsert({
where: { id: 0 },
where: { id: 'admin_uuid' },
update: {},
create: {
name: `${firstName} ${lastName}`,
name: `admin test`,
city: '',
role: '',
email: `${username}@${SEED_EMAIL_DOMAIN}`,
email: `admin@123.com`,
state: '',
status: '',
address: '',
@@ -37,8 +37,8 @@ async function userItem() {
phoneNumber: '',
isVerified: true,
//
username,
password: await generateHash('Abc1234!'),
username: 'admin@123.com',
password: await generateHash('Aa1234567'),
},
});
@@ -57,16 +57,16 @@ async function userItem() {
}
const randomFaker = getRandomCJKFaker();
const alice = await prisma.userItem.upsert({
where: { id: i },
await prisma.userItem.upsert({
where: { id: i.toString() },
update: {},
create: {
name: randomFaker.person.fullName(),
city: randomFaker.location.city(),
role: 'user',
role: ROLE[Math.floor(Math.random() * ROLE.length)],
email: randomFaker.internet.email(),
state: randomFaker.location.state(),
status: '',
status: STATUS[Math.floor(Math.random() * STATUS.length)],
address: randomFaker.location.streetAddress(),
country: randomFaker.location.country(),
zipCode: randomFaker.location.zipCode(),
@@ -95,3 +95,32 @@ const userItemSeed = userItem()
});
export { userItemSeed };
const ROLE = [
`CEO`,
`CTO`,
`Project Coordinator`,
`Team Leader`,
`Software Developer`,
`Marketing Strategist`,
`Data Analyst`,
`Product Owner`,
`Graphic Designer`,
`Operations Manager`,
`Customer Support Specialist`,
`Sales Manager`,
`HR Recruiter`,
`Business Consultant`,
`Financial Planner`,
`Network Engineer`,
`Content Creator`,
`Quality Assurance Tester`,
`Public Relations Officer`,
`IT Administrator`,
`Compliance Officer`,
`Event Planner`,
`Legal Counsel`,
`Training Coordinator`,
];
const STATUS = ['active', 'pending', 'banned'];

View File

@@ -7,7 +7,6 @@ import prisma from '../../lib/prisma';
export async function GET(req: NextRequest, res: NextResponse) {
try {
const users = await prisma.user.findMany();
console.log({ users });
return response({ users }, STATUS.OK);
} catch (error) {

View File

@@ -0,0 +1,4 @@
###
GET http://localhost:7272/api/helloworld

View File

@@ -24,9 +24,7 @@ export async function GET(req: NextRequest) {
const products = _products();
// Accept search by name or sku
const results = products.filter(
({ name, sku }) => name.toLowerCase().includes(query) || sku?.toLowerCase().includes(query)
);
const results = products.filter(({ name, sku }) => name.toLowerCase().includes(query) || sku?.toLowerCase().includes(query));
logger('[Product] search-results', results.length);

View File

@@ -1,75 +0,0 @@
// src/app/api/product/createProduct/route.ts
//
// PURPOSE:
// create product to db
//
// RULES:
// T.B.A.
//
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* POST - Products
*************************************** */
export async function POST(req: NextRequest) {
// logger('[Product] list', products.length);
const { data } = await req.json();
const createForm: CreateProductData = data as unknown as CreateProductData;
console.log({ createForm });
try {
console.log({ data });
await prisma.productItem.create({ data: createForm });
return response({ hello: 'world' }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world', data });
return handleError('Product - Create', error);
}
}
type CreateProductData = {
// id: string;
sku: string;
name: string;
code: string;
price: number;
taxes: number;
tags: string[];
sizes: string[];
publish: string;
gender: string[];
coverUrl: string;
images: string[];
colors: string[];
quantity: number;
category: string;
available: number;
totalSold: number;
description: string;
totalRatings: number;
totalReviews: number;
inventoryType: string;
subDescription: string;
priceSale: number;
newLabel: {
content: string;
enabled: boolean;
};
saleLabel: {
content: string;
enabled: boolean;
};
// ratings: {
// name: string;
// starCount: number;
// reviewCount: number;
// }[];
};

View File

@@ -0,0 +1,53 @@
// src/app/api/user/createUser/route.ts
//
// PURPOSE:
// create user to db
//
// RULES:
// T.B.A.
//
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/**
***************************************
* POST - create User
***************************************
*/
export async function POST(req: NextRequest) {
// logger('[User] list', users.length);
const { data } = await req.json();
const createForm: CreateUserData = data as unknown as CreateUserData;
try {
const user = await prisma.userItem.create({ data: createForm });
return response({ user }, STATUS.OK);
} catch (error) {
return handleError('User - Create', error);
}
}
type CreateUserData = {
name: string;
city: string;
role: string;
email: string;
state: string;
status: string;
address: string;
country: string;
zipCode: string;
company: string;
avatarUrl: string;
phoneNumber: string;
isVerified: boolean;
//
username: string;
password: string;
};

View File

@@ -0,0 +1,4 @@
###
POST http://localhost:7272/api/user/createUser

View File

@@ -1,44 +0,0 @@
// src/app/api/product/deleteProduct/route.ts
//
// PURPOSE:
// delete product from db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* handle Delete Products
*************************************** */
export async function DELETE(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
// RULES: productId must exist
const productId = searchParams.get('productId');
if (!productId) {
return response({ message: 'Product ID is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: productId confirmed exist, run below
const product = await prisma.productItem.delete({ where: { id: productId } });
if (!product) {
return response({ message: 'Product not found!' }, STATUS.NOT_FOUND);
}
logger('[Product] details', product.id);
return response({ product }, STATUS.OK);
} catch (error) {
return handleError('Product - Get details', error);
}
}

View File

@@ -1,3 +0,0 @@
###
DELETE http://localhost:7272/api/product/deleteProduct?productId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b06

View File

@@ -0,0 +1,47 @@
// src/app/api/product/deleteUser/route.ts
//
// PURPOSE:
// delete product from db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* handle Delete Users
*************************************** */
export async function DELETE(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
// RULES: userId must exist
const userId = searchParams.get('userId');
if (!userId) {
return response({ message: 'User ID is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: userId confirmed exist, run below
const user = await prisma.userItem.delete({
//
where: { id: userId },
});
if (!user) {
return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
}
logger('[User] details', user.id);
return response({ user }, STATUS.OK);
} catch (error) {
return handleError('User - Get details', error);
}
}

View File

@@ -0,0 +1,3 @@
###
DELETE http://localhost:7272/api/user/deleteUser?userId=3f431e6f-ad05-4d60-9c25-6a7e92a954ad

View File

@@ -1,7 +1,7 @@
// src/app/api/product/details/route.ts
//
// PURPOSE:
// save product to db by id
// read user from db by id
//
// RULES:
// T.B.A.
@@ -16,31 +16,31 @@ import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* GET Product detail
* GET User detail
*************************************** */
export async function GET(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
// RULES: productId must exist
const productId = searchParams.get('productId');
if (!productId) {
return response({ message: 'Product ID is required!' }, STATUS.BAD_REQUEST);
// RULES: userId must exist
const userId = searchParams.get('userId');
if (!userId) {
return response({ message: 'userId is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: productId confirmed exist, run below
const product = await prisma.productItem.findFirst({
include: { reviews: true },
where: { id: productId },
// NOTE: userId confirmed exist, run below
const user = await prisma.userItem.findFirst({
// include: { reviews: true },
where: { id: userId },
});
if (!product) {
return response({ message: 'Product not found!' }, STATUS.NOT_FOUND);
if (!user) {
return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
}
logger('[Product] details', product.id);
logger('[User] details', user.id);
return response({ product }, STATUS.OK);
return response({ user }, STATUS.OK);
} catch (error) {
return handleError('Product - Get details', error);
}

View File

@@ -0,0 +1,4 @@
###
GET http://localhost:7272/api/user/details?userId=1165ce3a-29b8-4e1a-9148-1ae08d7e8e01

View File

@@ -1,4 +1,3 @@
###
GET http://localhost:7272/api/user/list

View File

@@ -19,54 +19,40 @@ import prisma from '../../../lib/prisma';
*************************************** */
export async function POST(req: NextRequest) {
// logger('[Product] list', products.length);
const { searchParams } = req.nextUrl;
const userId = searchParams.get('userId');
// RULES: userId must exist
if (!userId) {
return response({ message: 'Product ID is required!' }, STATUS.BAD_REQUEST);
}
const { data } = await req.json();
try {
const products = await prisma.productItem.updateMany({
const user = await prisma.userItem.updateMany({
where: { id: userId },
data: {
status: data.status,
avatarUrl: data.avatarUrl,
isVerified: data.isVerified,
name: data.name,
sku: data.sku,
code: data.code,
price: data.price,
taxes: data.taxes,
tags: data.tags,
sizes: data.sizes,
publish: data.publish,
gender: data.gender,
coverUrl: data.coverUrl,
images: data.images,
colors: data.colors,
quantity: data.quantity,
category: data.category,
available: data.available,
totalSold: data.totalSold,
description: data.description,
totalRatings: data.totalRatings,
totalReviews: data.totalReviews,
inventoryType: data.inventoryType,
subDescription: data.subDescription,
priceSale: data.priceSale,
email: data.email,
phoneNumber: data.phoneNumber,
country: data.country,
state: data.state,
city: data.city,
address: data.address,
zipCode: data.zipCode,
company: data.company,
role: data.role,
//
newLabel: {
content: data.newLabel?.content || '',
enabled: data.newLabel?.enabled ?? false,
},
saleLabel: {
content: data.saleLabel?.content || '',
enabled: data.saleLabel?.enabled ?? false,
},
ratings: {
set: data.ratings.map((rating: { name: string; starCount: number; reviewCount: number }) => ({
name: rating.name,
starCount: rating.starCount,
reviewCount: rating.reviewCount,
})),
},
username: data.username,
password: data.password,
},
where: { id: data.id },
});
return response({ hello: 'world', data }, STATUS.OK);
return response({ user }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world', data });
return handleError('Product - Get list', error);

View File

@@ -0,0 +1,3 @@
###
POST http://localhost:7272/api/user/list

View File

@@ -10,7 +10,9 @@ const config = {
printWidth: 100,
singleQuote: true,
trailingComma: 'es5',
plugins: ['@ianvs/prettier-plugin-sort-imports'],
plugins: [
// '@ianvs/prettier-plugin-sort-imports'
],
};
export default config;

View File

@@ -15,15 +15,14 @@ const swrOptions: SWRConfiguration = {
// ----------------------------------------------------------------------
type UserData = {
type UsersData = {
users: IUserItem[];
};
export function useGetUsers() {
// const url = endpoints.user.list;
const url = `http://localhost:7272/api/user/list`;
const { data, isLoading, error, isValidating, mutate } = useSWR<UserData>(
const { data, isLoading, error, isValidating, mutate } = useSWR<UsersData>(
url,
fetcher,
swrOptions
@@ -46,23 +45,23 @@ export function useGetUsers() {
// ----------------------------------------------------------------------
type ProductData = {
product: IProductItem;
type UserData = {
user: IUserItem;
};
export function useGetProduct(productId: string) {
const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
export function useGetUser(userId: string) {
const url = userId ? [endpoints.user.details, { params: { userId } }] : '';
const { data, isLoading, error, isValidating } = useSWR<ProductData>(url, fetcher, swrOptions);
const { data, isLoading, error, isValidating } = useSWR<UserData>(url, fetcher, swrOptions);
const memoizedValue = useMemo(
() => ({
product: data?.product,
productLoading: isLoading,
productError: error,
productValidating: isValidating,
user: data?.user,
userLoading: isLoading,
userError: error,
userValidating: isValidating,
}),
[data?.product, error, isLoading, isValidating]
[data?.user, error, isLoading, isValidating]
);
return memoizedValue;
@@ -98,59 +97,42 @@ export function useSearchProducts(query: string) {
// ----------------------------------------------------------------------
type SaveProductData = {
// id: string;
sku: string;
type SaveUserData = {
name: string;
code: string;
price: number | null;
taxes: number | null;
tags: string[];
sizes: string[];
// publish: string;
gender: string[];
// coverUrl: string;
images: (string | File)[];
colors: string[];
quantity: number | null;
category: string;
// available: number;
// totalSold: number;
description: string;
// totalRatings: number;
// totalReviews: number;
// inventoryType: string;
subDescription: string;
priceSale: number | null;
newLabel: {
content: string;
enabled: boolean;
};
saleLabel: {
content: string;
enabled: boolean;
};
// ratings: {
// name: string;
// starCount: number;
// reviewCount: number;
// }[];
city: string;
role: string;
email: string;
state: string;
status: string;
address: string;
country: string;
zipCode: string;
company: string;
avatarUrl: string;
phoneNumber: string;
isVerified: boolean;
//
username: string;
password: string;
};
export async function saveProduct(productId: string, saveProductData: SaveProductData) {
console.log('save product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
export async function saveUser(userId: string, saveUserData: SaveUserData) {
// const url = userId ? [endpoints.user.details, { params: { userId } }] : '';
const res = await axiosInstance.post('http://localhost:7272/api/product/saveProduct', {
data: saveProductData,
});
const res = await axiosInstance.post(
//
`http://localhost:7272/api/user/saveUser?userId=${userId}`,
{
data: saveUserData,
}
);
return res;
}
export async function uploadProductImage(saveProductData: SaveProductData) {
console.log('save product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
export async function uploadUserImage(saveUserData: SaveUserData) {
console.log('uploadUserImage ?');
// const url = userId ? [endpoints.user.details, { params: { userId } }] : '';
const res = await axiosInstance.get('http://localhost:7272/api/product/helloworld');
@@ -159,51 +141,31 @@ export async function uploadProductImage(saveProductData: SaveProductData) {
// ----------------------------------------------------------------------
type CreateProductData = {
// id: string;
sku: string;
type CreateUserData = {
name: string;
code: string;
price: number | null;
taxes: number | null;
tags: string[];
sizes: string[];
publish: string;
gender: string[];
coverUrl: string;
images: (string | File)[];
colors: string[];
quantity: number | null;
category: string;
available: number;
totalSold: number;
description: string;
totalRatings: number;
totalReviews: number;
inventoryType: string;
subDescription: string;
priceSale: number | null;
newLabel: {
content: string;
enabled: boolean;
};
saleLabel: {
content: string;
enabled: boolean;
};
// ratings: {
// name: string;
// starCount: number;
// reviewCount: number;
// }[];
city: string;
role: string;
email: string;
state: string;
status: string;
address: string;
country: string;
zipCode: string;
company: string;
avatarUrl: string;
phoneNumber: string;
isVerified: boolean;
//
username: string;
password: string;
};
export async function createProduct(createProductData: CreateProductData) {
export async function createUser(createUserData: CreateUserData) {
console.log('create product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
const res = await axiosInstance.post('http://localhost:7272/api/product/createProduct', {
data: createProductData,
const res = await axiosInstance.post('http://localhost:7272/api/user/createUser', {
data: createUserData,
});
return res;
@@ -211,21 +173,20 @@ export async function createProduct(createProductData: CreateProductData) {
// ----------------------------------------------------------------------
type DeleteProductResponse = {
type DeleteUserResponse = {
success: boolean;
message?: string;
};
export async function deleteUser(productId: string): Promise<DeleteProductResponse> {
const url = `http://localhost:7272/api/product/deleteProduct?productId=${productId}`;
export async function deleteUser(userId: string): Promise<DeleteUserResponse> {
const url = `http://localhost:7272/api/user/deleteUser?userId=${userId}`;
try {
const res = await axiosInstance.delete(url);
console.log({ res });
return {
success: true,
message: 'Product deleted successfully',
message: 'User deleted successfully',
};
} catch (error) {
return {

View File

@@ -5,17 +5,13 @@ import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import type { ConfirmDialogProps } from './types';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
export function ConfirmDialog({
open,
title,
action,
content,
onClose,
...other
}: ConfirmDialogProps) {
export function ConfirmDialog({ open, title, action, content, onClose, ...other }: ConfirmDialogProps) {
const { t } = useTranslation();
return (
<Dialog fullWidth maxWidth="xs" open={open} onClose={onClose} {...other}>
<DialogTitle sx={{ pb: 2 }}>{title}</DialogTitle>
@@ -26,7 +22,7 @@ export function ConfirmDialog({
{action}
<Button variant="outlined" color="inherit" onClick={onClose}>
Cancel
{t('Cancel')}
</Button>
</DialogActions>
</Dialog>

View File

@@ -11,24 +11,20 @@ import { megaMenuClasses } from '../styles';
import { NavUl, NavLi } from './nav-elements';
import type { NavSubItemProps, NavSubListProps } from '../types';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
export function NavSubList({ data, slotProps, ...other }: NavSubListProps) {
const pathname = usePathname();
const { t } = useTranslation();
return (
<>
{data?.map((list) => (
<NavLi key={list?.subheader ?? list.items[0].title} {...other}>
{list?.subheader && (
<Typography
noWrap
component="div"
variant="subtitle2"
className={megaMenuClasses.subheader}
sx={{ mb: 1, ...slotProps?.subheader }}
>
<Typography noWrap component="div" variant="subtitle2" className={megaMenuClasses.subheader} sx={{ mb: 1, ...slotProps?.subheader }}>
{list.subheader}
</Typography>
)}

View File

@@ -13,16 +13,8 @@ import { Iconify, iconifyClasses } from '../../iconify';
export type NavSubheaderProps = ListSubheaderProps & { open?: boolean };
export const NavSubheader = styled(({ open, children, className, ...other }: NavSubheaderProps) => (
<ListSubheader
disableSticky
component="div"
{...other}
className={mergeClasses([navSectionClasses.subheader, className])}
>
<Iconify
width={16}
icon={open ? 'eva:arrow-ios-downward-fill' : 'eva:arrow-ios-forward-fill'}
/>
<ListSubheader disableSticky component="div" {...other} className={mergeClasses([navSectionClasses.subheader, className])}>
<Iconify width={16} icon={open ? 'eva:arrow-ios-downward-fill' : 'eva:arrow-ios-forward-fill'} />
{children}
</ListSubheader>
))(({ theme }) => ({

View File

@@ -27,10 +27,7 @@ export function NavSectionHorizontal({
const cssVars = { ...navSectionCssVars.horizontal(theme), ...overridesVars };
return (
<Scrollbar
sx={{ height: 1 }}
slotProps={{ contentSx: { height: 1, display: 'flex', alignItems: 'center' } }}
>
<Scrollbar sx={{ height: 1 }} slotProps={{ contentSx: { height: 1, display: 'flex', alignItems: 'center' } }}>
<Nav
className={mergeClasses([navSectionClasses.horizontal, className])}
sx={[
@@ -66,14 +63,7 @@ export function NavSectionHorizontal({
// ----------------------------------------------------------------------
function Group({
items,
render,
cssVars,
slotProps,
checkPermissions,
enabledRootRedirect,
}: NavGroupProps) {
function Group({ items, render, cssVars, slotProps, checkPermissions, enabledRootRedirect }: NavGroupProps) {
return (
<NavLi>
<NavUl sx={{ flexDirection: 'row', gap: 'var(--nav-item-gap)' }}>

View File

@@ -26,11 +26,7 @@ export function NavSectionMini({
const cssVars = { ...navSectionCssVars.mini(theme), ...overridesVars };
return (
<Nav
className={mergeClasses([navSectionClasses.mini, className])}
sx={[{ ...cssVars }, ...(Array.isArray(sx) ? sx : [sx])]}
{...other}
>
<Nav className={mergeClasses([navSectionClasses.mini, className])} sx={[{ ...cssVars }, ...(Array.isArray(sx) ? sx : [sx])]} {...other}>
<NavUl sx={{ flex: '1 1 auto', gap: 'var(--nav-item-gap)' }}>
{data.map((group) => (
<Group
@@ -50,14 +46,7 @@ export function NavSectionMini({
// ----------------------------------------------------------------------
function Group({
items,
render,
cssVars,
slotProps,
checkPermissions,
enabledRootRedirect,
}: NavGroupProps) {
function Group({ items, render, cssVars, slotProps, checkPermissions, enabledRootRedirect }: NavGroupProps) {
return (
<NavLi>
<NavUl sx={{ gap: 'var(--nav-item-gap)' }}>

View File

@@ -6,6 +6,7 @@ import { Nav, NavLi, NavSubheader, NavUl } from '../components';
import { navSectionClasses, navSectionCssVars } from '../styles';
import type { NavGroupProps, NavSectionProps } from '../types';
import { NavList } from './nav-list';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -25,11 +26,7 @@ export function NavSectionVertical({
const cssVars = { ...navSectionCssVars.vertical(theme), ...overridesVars };
return (
<Nav
className={mergeClasses([navSectionClasses.vertical, className])}
sx={[{ ...cssVars }, ...(Array.isArray(sx) ? sx : [sx])]}
{...other}
>
<Nav className={mergeClasses([navSectionClasses.vertical, className])} sx={[{ ...cssVars }, ...(Array.isArray(sx) ? sx : [sx])]} {...other}>
<NavUl sx={{ flex: '1 1 auto', gap: 'var(--nav-item-gap)' }}>
{data.map((group) => (
<Group
@@ -49,15 +46,9 @@ export function NavSectionVertical({
// ----------------------------------------------------------------------
function Group({
items,
render,
subheader,
slotProps,
checkPermissions,
enabledRootRedirect,
}: NavGroupProps) {
function Group({ items, render, subheader, slotProps, checkPermissions, enabledRootRedirect }: NavGroupProps) {
const groupOpen = useBoolean(true);
const { t } = useTranslation();
const renderContent = () => (
<NavUl sx={{ gap: 'var(--nav-item-gap)' }}>
@@ -79,13 +70,8 @@ function Group({
<NavLi>
{subheader ? (
<>
<NavSubheader
data-title={subheader}
open={groupOpen.value}
onClick={groupOpen.onToggle}
sx={slotProps?.subheader}
>
{subheader}
<NavSubheader data-title={subheader} open={groupOpen.value} onClick={groupOpen.onToggle} sx={slotProps?.subheader}>
{t(subheader)}
</NavSubheader>
<Collapse in={groupOpen.value}>{renderContent()}</Collapse>
</>

View File

@@ -11,18 +11,12 @@ import { uploadClasses } from './classes';
import { RejectionFiles } from './components/rejection-files';
import type { UploadProps } from './types';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
export function UploadAvatar({
sx,
error,
value,
disabled,
helperText,
className,
...other
}: UploadProps) {
export function UploadAvatar({ sx, error, value, disabled, helperText, className, ...other }: UploadProps) {
const { t } = useTranslation();
const { getRootProps, getInputProps, isDragActive, isDragReject, fileRejections } = useDropzone({
multiple: false,
disabled,
@@ -44,10 +38,7 @@ export function UploadAvatar({
}
}, [value]);
const renderPreview = () =>
hasFile && (
<Image alt="Avatar" src={preview} sx={{ width: 1, height: 1, borderRadius: '50%' }} />
);
const renderPreview = () => hasFile && <Image alt="Avatar" src={preview} sx={{ width: 1, height: 1, borderRadius: '50%' }} />;
const renderPlaceholder = () => (
<Box
@@ -85,7 +76,7 @@ export function UploadAvatar({
>
<Iconify icon="solar:camera-add-bold" width={32} />
<Typography variant="caption">{hasFile ? 'Update photo' : 'Upload photo'}</Typography>
<Typography variant="caption">{hasFile ? t('Update photo') : t('Update photo')}</Typography>
</Box>
);

View File

@@ -35,9 +35,7 @@ const flattenNavItems = (navItems: NavItem[], parentGroup?: string): OutputItem[
};
export function flattenNavSections(navSections: NavSectionProps['data']): OutputItem[] {
return navSections.flatMap((navSection) =>
flattenNavItems(navSection.items, navSection.subheader)
);
return navSections.flatMap((navSection) => flattenNavItems(navSection.items, navSection.subheader));
}
// ----------------------------------------------------------------------
@@ -50,7 +48,5 @@ type ApplyFilterProps = {
export function applyFilter({ inputData, query }: ApplyFilterProps): OutputItem[] {
if (!query) return inputData;
return inputData.filter(({ title, path, group }) =>
[title, path, group].some((field) => field?.toLowerCase().includes(query.toLowerCase()))
);
return inputData.filter(({ title, path, group }) => [title, path, group].some((field) => field?.toLowerCase().includes(query.toLowerCase())));
}

View File

@@ -50,13 +50,7 @@ export type DashboardLayoutProps = LayoutBaseProps & {
};
};
export function DashboardLayout({
sx,
cssVars,
children,
slotProps,
layoutQuery = 'lg',
}: DashboardLayoutProps) {
export function DashboardLayout({ sx, cssVars, children, slotProps, layoutQuery = 'lg' }: DashboardLayoutProps) {
const theme = useTheme();
const { user } = useMockedUser();
@@ -73,8 +67,7 @@ export function DashboardLayout({
const isNavHorizontal = settings.state.navLayout === 'horizontal';
const isNavVertical = isNavMini || settings.state.navLayout === 'vertical';
const canDisplayItemByRole = (allowedRoles: NavItemProps['allowedRoles']): boolean =>
!allowedRoles?.includes(user?.role);
const canDisplayItemByRole = (allowedRoles: NavItemProps['allowedRoles']): boolean => !allowedRoles?.includes(user?.role);
const renderHeader = () => {
const headerSlotProps: HeaderSectionProps['slotProps'] = {
@@ -98,27 +91,13 @@ export function DashboardLayout({
</Alert>
),
bottomArea: isNavHorizontal ? (
<NavHorizontal
data={navData}
layoutQuery={layoutQuery}
cssVars={navVars.section}
checkPermissions={canDisplayItemByRole}
/>
<NavHorizontal data={navData} layoutQuery={layoutQuery} cssVars={navVars.section} checkPermissions={canDisplayItemByRole} />
) : null,
leftArea: (
<>
{/** @slot Nav mobile */}
<MenuButton
onClick={onOpen}
sx={{ mr: 1, ml: -1, [theme.breakpoints.up(layoutQuery)]: { display: 'none' } }}
/>
<NavMobile
data={navData}
open={open}
onClose={onClose}
cssVars={navVars.section}
checkPermissions={canDisplayItemByRole}
/>
<MenuButton onClick={onOpen} sx={{ mr: 1, ml: -1, [theme.breakpoints.up(layoutQuery)]: { display: 'none' } }} />
<NavMobile data={navData} open={open} onClose={onClose} cssVars={navVars.section} checkPermissions={canDisplayItemByRole} />
{/** @slot Logo */}
{isNavHorizontal && (
@@ -131,15 +110,10 @@ export function DashboardLayout({
)}
{/** @slot Divider */}
{isNavHorizontal && (
<VerticalDivider sx={{ [theme.breakpoints.up(layoutQuery)]: { display: 'flex' } }} />
)}
{isNavHorizontal && <VerticalDivider sx={{ [theme.breakpoints.up(layoutQuery)]: { display: 'flex' } }} />}
{/** @slot Workspace popover */}
<WorkspacesPopover
data={_workspaces}
sx={{ ...(isNavHorizontal && { color: 'var(--layout-nav-text-primary-color)' }) }}
/>
<WorkspacesPopover data={_workspaces} sx={{ ...(isNavHorizontal && { color: 'var(--layout-nav-text-primary-color)' }) }} />
</>
),
rightArea: (
@@ -184,12 +158,7 @@ export function DashboardLayout({
layoutQuery={layoutQuery}
cssVars={navVars.section}
checkPermissions={canDisplayItemByRole}
onToggleNav={() =>
settings.setField(
'navLayout',
settings.state.navLayout === 'vertical' ? 'mini' : 'vertical'
)
}
onToggleNav={() => settings.setField('navLayout', settings.state.navLayout === 'vertical' ? 'mini' : 'vertical')}
/>
);

View File

@@ -23,18 +23,7 @@ export type NavVerticalProps = React.ComponentProps<'div'> &
};
};
export function NavVertical({
sx,
data,
slots,
cssVars,
className,
isNavMini,
onToggleNav,
checkPermissions,
layoutQuery = 'md',
...other
}: NavVerticalProps) {
export function NavVertical({ sx, data, slots, cssVars, className, isNavMini, onToggleNav, checkPermissions, layoutQuery = 'md', ...other }: NavVerticalProps) {
const renderNavVertical = () => (
<>
{slots?.topArea ?? (
@@ -44,12 +33,7 @@ export function NavVertical({
)}
<Scrollbar fillContent>
<NavSectionVertical
data={data}
cssVars={cssVars}
checkPermissions={checkPermissions}
sx={{ px: 2, flex: '1 1 auto' }}
/>
<NavSectionVertical data={data} cssVars={cssVars} checkPermissions={checkPermissions} sx={{ px: 2, flex: '1 1 auto' }} />
{slots?.bottomArea ?? <NavUpgrade />}
</Scrollbar>
@@ -110,22 +94,20 @@ export function NavVertical({
const NavRoot = styled('div', {
shouldForwardProp: (prop: string) => !['isNavMini', 'layoutQuery', 'sx'].includes(prop),
})<Pick<NavVerticalProps, 'isNavMini' | 'layoutQuery'>>(
({ isNavMini, layoutQuery = 'md', theme }) => ({
top: 0,
left: 0,
height: '100%',
display: 'none',
position: 'fixed',
flexDirection: 'column',
zIndex: 'var(--layout-nav-zIndex)',
backgroundColor: 'var(--layout-nav-bg)',
width: isNavMini ? 'var(--layout-nav-mini-width)' : 'var(--layout-nav-vertical-width)',
borderRight: `1px solid var(--layout-nav-border-color, ${varAlpha(theme.vars.palette.grey['500Channel'], 0.12)})`,
transition: theme.transitions.create(['width'], {
easing: 'var(--layout-transition-easing)',
duration: 'var(--layout-transition-duration)',
}),
[theme.breakpoints.up(layoutQuery)]: { display: 'flex' },
})
);
})<Pick<NavVerticalProps, 'isNavMini' | 'layoutQuery'>>(({ isNavMini, layoutQuery = 'md', theme }) => ({
top: 0,
left: 0,
height: '100%',
display: 'none',
position: 'fixed',
flexDirection: 'column',
zIndex: 'var(--layout-nav-zIndex)',
backgroundColor: 'var(--layout-nav-bg)',
width: isNavMini ? 'var(--layout-nav-mini-width)' : 'var(--layout-nav-vertical-width)',
borderRight: `1px solid var(--layout-nav-border-color, ${varAlpha(theme.vars.palette.grey['500Channel'], 0.12)})`,
transition: theme.transitions.create(['width'], {
easing: 'var(--layout-transition-easing)',
duration: 'var(--layout-transition-duration)',
}),
[theme.breakpoints.up(layoutQuery)]: { display: 'flex' },
}));

View File

@@ -55,11 +55,7 @@ const shouldForwardProp = (prop: string) => !['open', 'active', 'variant', 'sx']
/**
* @slot root
*/
const ItemRoot = styled(ButtonBase, { shouldForwardProp })<StyledState>(({
active,
open,
theme,
}) => {
const ItemRoot = styled(ButtonBase, { shouldForwardProp })<StyledState>(({ active, open, theme }) => {
const dotTransitions: Record<'in' | 'out', CSSObject> = {
in: { opacity: 0, scale: 0 },
out: { opacity: 1, scale: 1 },

View File

@@ -106,12 +106,7 @@ function NavSubList({ data, subheader, sx, ...other }: NavSubListProps) {
</NavLi>
) : (
<NavLi key={item.title} sx={{ mt: 0.75 }}>
<NavItem
subItem
title={item.title}
path={item.path}
active={isEqualPath(item.path, pathname)}
/>
<NavItem subItem title={item.title} path={item.path} active={isEqualPath(item.path, pathname)} />
</NavLi>
)
)}

View File

@@ -71,5 +71,55 @@
"Rejected": "已反對",
"Quick update": "快速更新",
"Address": "地址",
"Followers": "追隨者",
"Follower": "追隨者",
"Following": "正在追隨",
"Friends": "朋友圈",
"Gallery": "相集",
"About": "關於用戶",
"Social": "社交媒體",
"Post": "發帖",
"Image/Video": "相/視頻",
"Streaming": "直播",
"Delete": "清除",
"Cancel": "取消",
"Overview": "概覽",
"Management": "管理",
"Quick Edit": "簡易編輯",
"Choose a country": "選擇一個城市",
"Create user": "新用戶",
"State/region": "State/region",
"Misc": "雜項",
"Email verified": "電郵核實",
"Update photo": "上傳相片",
"Create a new user": "創建新用戶",
"Allowed": "Allowed",
"max size of": "max size of",
"Disabling this will automatically send the user a verification email": "Disabling this will automatically send the user a verification email",
"Full name": "Full name",
"Email address": "Email address",
"Country": "Country",
"City": "City",
"Zip/code": "Zip/code",
"Update success": "更新完成",
"Create success": "創建完成",
"Save changes": "儲存變更",
"Product List": "產品列表",
"View": "詳細資料",
"Completed": "已完成",
"Cancelled": "已取消",
"Refunded": "已退款",
"Date ": "日期",
"Order ": "訂單",
"Customer ": "客戶",
"Items ": "項目",
"Start date ": "開始日期",
"End date ": "結束日期",
"Search customer or order number... ": "搜尋客戶或訂單號碼...",
"Print ": "列印",
"Import ": "匯入",
"Export ": "匯出",
"Product not found!": "產品未找到!",
"Back to list": "返回列表",
"hello": "world"
}

View File

@@ -13,7 +13,6 @@ export default function Page() {
const { id = '' } = useParams();
const { product } = useGetProduct(id);
console.log({ id });
return (
<>

View File

@@ -1,7 +1,8 @@
import { _userList } from 'src/_mock/_user';
// import { _userList } from 'src/_mock/_user';
import { CONFIG } from 'src/global-config';
import { useParams } from 'src/routes/hooks';
import { UserEditView } from 'src/sections/user/view';
import { useGetUser } from 'src/actions/user';
// ----------------------------------------------------------------------
@@ -10,13 +11,15 @@ const metadata = { title: `User edit | Dashboard - ${CONFIG.appName}` };
export default function Page() {
const { id = '' } = useParams();
const currentUser = _userList.find((user) => user.id === id);
// TODO: remove me
// const currentUser = _userList.find((user) => user.id === id);
const { user } = useGetUser(id);
return (
<>
<title>{metadata.title}</title>
<UserEditView user={currentUser} />
<UserEditView user={user} />
</>
);
}

View File

@@ -63,9 +63,7 @@ export function AccountNotifications({ sx, ...other }: CardProps) {
});
const getSelected = (selectedItems: string[], item: string) =>
selectedItems.includes(item)
? selectedItems.filter((value) => value !== item)
: [...selectedItems, item];
selectedItems.includes(item) ? selectedItems.filter((value) => value !== item) : [...selectedItems, item];
return (
<Form methods={methods} onSubmit={onSubmit}>

View File

@@ -49,23 +49,15 @@ import { InvoiceAnalytic } from '../invoice-analytic';
import { InvoiceTableRow } from '../invoice-table-row';
import { InvoiceTableToolbar } from '../invoice-table-toolbar';
import { InvoiceTableFiltersResult } from '../invoice-table-filters-result';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
const TABLE_HEAD: TableHeadCellProps[] = [
{ id: 'invoiceNumber', label: 'Customer' },
{ id: 'createDate', label: 'Create' },
{ id: 'dueDate', label: 'Due' },
{ id: 'price', label: 'Amount' },
{ id: 'sent', label: 'Sent', align: 'center' },
{ id: 'status', label: 'Status' },
{ id: '' },
];
// ----------------------------------------------------------------------
export function InvoiceListView() {
const theme = useTheme();
const { t } = useTranslation();
const table = useTable({ defaultOrderBy: 'createDate' });
@@ -73,6 +65,16 @@ export function InvoiceListView() {
const [tableData, setTableData] = useState<IInvoice[]>(_invoices);
const TABLE_HEAD: TableHeadCellProps[] = [
{ id: 'invoiceNumber', label: t('Customer') },
{ id: 'createDate', label: t('Create') },
{ id: 'dueDate', label: t('Due') },
{ id: 'price', label: t('Amount') },
{ id: 'sent', label: t('Sent'), align: 'center' },
{ id: 'status', label: t('Status') },
{ id: '' },
];
const filters = useSetState<IInvoiceTableFilters>({
name: '',
service: [],

View File

@@ -1,3 +1,4 @@
// src/sections/order/view/order-list-view.tsx
import type { IOrderItem } from 'src/types/order';
import { useBoolean, usePopover } from 'minimal-shared/hooks';
@@ -26,6 +27,7 @@ import { Label } from 'src/components/label';
import { Iconify } from 'src/components/iconify';
import { ConfirmDialog } from 'src/components/custom-dialog';
import { CustomPopover } from 'src/components/custom-popover';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -41,6 +43,7 @@ export function OrderTableRow({ row, selected, onSelectRow, onDeleteRow, details
const confirmDialog = useBoolean();
const menuActions = usePopover();
const collapseRow = useBoolean();
const { t } = useTranslation();
const renderPrimaryRow = () => (
<TableRow hover selected={selected}>
@@ -195,13 +198,13 @@ export function OrderTableRow({ row, selected, onSelectRow, onDeleteRow, details
sx={{ color: 'error.main' }}
>
<Iconify icon="solar:trash-bin-trash-bold" />
Delete
{t('Delete')}
</MenuItem>
<li>
<MenuItem component={RouterLink} href={detailsHref} onClick={() => menuActions.onClose()}>
<Iconify icon="solar:eye-bold" />
View
{t('View')}
</MenuItem>
</li>
</MenuList>

View File

@@ -16,6 +16,7 @@ import { formHelperTextClasses } from '@mui/material/FormHelperText';
import { Iconify } from 'src/components/iconify';
import { CustomPopover } from 'src/components/custom-popover';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -26,6 +27,7 @@ type Props = {
};
export function OrderTableToolbar({ filters, onResetPage, dateError }: Props) {
const { t } = useTranslation();
const menuActions = usePopover();
const { state: currentFilters, setState: updateFilters } = filters;
@@ -64,17 +66,17 @@ export function OrderTableToolbar({ filters, onResetPage, dateError }: Props) {
<MenuList>
<MenuItem onClick={() => menuActions.onClose()}>
<Iconify icon="solar:printer-minimalistic-bold" />
Print
{t('Print')}
</MenuItem>
<MenuItem onClick={() => menuActions.onClose()}>
<Iconify icon="solar:import-bold" />
Import
{t('Import')}
</MenuItem>
<MenuItem onClick={() => menuActions.onClose()}>
<Iconify icon="solar:export-bold" />
Export
{t('Export')}
</MenuItem>
</MenuList>
</CustomPopover>
@@ -93,7 +95,7 @@ export function OrderTableToolbar({ filters, onResetPage, dateError }: Props) {
}}
>
<DatePicker
label="Start date"
label={t('Start date')}
value={currentFilters.startDate}
onChange={handleFilterStartDate}
slotProps={{ textField: { fullWidth: true } }}
@@ -101,7 +103,7 @@ export function OrderTableToolbar({ filters, onResetPage, dateError }: Props) {
/>
<DatePicker
label="End date"
label={t('End date')}
value={currentFilters.endDate}
onChange={handleFilterEndDate}
slotProps={{
@@ -133,7 +135,7 @@ export function OrderTableToolbar({ filters, onResetPage, dateError }: Props) {
fullWidth
value={currentFilters.name}
onChange={handleFilterName}
placeholder="Search customer or order number..."
placeholder={t('Search customer or order number...')}
slotProps={{
input: {
startAdornment: (

View File

@@ -1,3 +1,5 @@
// src/sections/order/view/order-list-view.tsx
import type { TableHeadCellProps } from 'src/components/table';
import type { IOrderItem, IOrderTableFilters } from 'src/types/order';
@@ -43,30 +45,33 @@ import {
import { OrderTableRow } from '../order-table-row';
import { OrderTableToolbar } from '../order-table-toolbar';
import { OrderTableFiltersResult } from '../order-table-filters-result';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
const STATUS_OPTIONS = [{ value: 'all', label: 'All' }, ...ORDER_STATUS_OPTIONS];
const TABLE_HEAD: TableHeadCellProps[] = [
{ id: 'orderNumber', label: 'Order', width: 88 },
{ id: 'name', label: 'Customer' },
{ id: 'createdAt', label: 'Date', width: 140 },
{ id: 'totalQuantity', label: 'Items', width: 120, align: 'center' },
{ id: 'totalAmount', label: 'Price', width: 140 },
{ id: 'status', label: 'Status', width: 110 },
{ id: '', width: 88 },
];
// ----------------------------------------------------------------------
export function OrderListView() {
const { t } = useTranslation();
const table = useTable({ defaultOrderBy: 'orderNumber' });
const confirmDialog = useBoolean();
const [tableData, setTableData] = useState<IOrderItem[]>(_orders);
const TABLE_HEAD: TableHeadCellProps[] = [
{ id: 'orderNumber', label: t('Order'), width: 88 },
{ id: 'name', label: t('Customer') },
{ id: 'createdAt', label: t('Date'), width: 140 },
{ id: 'totalQuantity', label: t('Items'), width: 120, align: 'center' },
{ id: 'totalAmount', label: t('Price'), width: 140 },
{ id: 'status', label: t('Status'), width: 110 },
{ id: '', width: 88 },
];
const filters = useSetState<IOrderTableFilters>({
name: '',
status: 'all',
@@ -143,7 +148,7 @@ export function OrderListView() {
confirmDialog.onFalse();
}}
>
Delete
{t('Delete')}
</Button>
}
/>
@@ -155,9 +160,9 @@ export function OrderListView() {
<CustomBreadcrumbs
heading="List"
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'Order', href: paths.dashboard.order.root },
{ name: 'List' },
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('Order'), href: paths.dashboard.order.root },
{ name: t('List') },
]}
sx={{ mb: { xs: 3, md: 5 } }}
/>
@@ -178,7 +183,7 @@ export function OrderListView() {
key={tab.value}
iconPosition="end"
value={tab.value}
label={tab.label}
label={t(tab.label)}
icon={
<Label
variant={
@@ -228,7 +233,7 @@ export function OrderListView() {
)
}
action={
<Tooltip title="Delete">
<Tooltip title={t('Delete')}>
<IconButton color="primary" onClick={confirmDialog.onTrue}>
<Iconify icon="solar:trash-bin-trash-bold" />
</IconButton>

View File

@@ -206,7 +206,6 @@ export function ProductNewEditForm({ currentProduct }: Props) {
if (currentProduct) {
// perform save
await saveProduct(currentProduct.id, values);
} else {
// perform create
@@ -215,7 +214,8 @@ export function ProductNewEditForm({ currentProduct }: Props) {
toast.success(currentProduct ? 'Update success!' : 'Create success!');
// router.push(paths.dashboard.product.root);
router.push(paths.dashboard.product.root);
// console.info('DATA', updatedData);
} catch (error) {
console.error(error);

View File

@@ -1,3 +1,4 @@
// src/sections/product/product-table-row.tsx
import type { GridCellParams } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
@@ -43,7 +44,7 @@ export function RenderCellCreatedAt({ params }: ParamsProps) {
}
export function RenderCellStock({ params }: ParamsProps) {
return <>helloworld</>
return <>helloworld</>;
return (
<Box sx={{ width: 1, typography: 'caption', color: 'text.secondary' }}>

View File

@@ -86,7 +86,7 @@ export function ProductDetailsView({ product, error, loading }: Props) {
<DashboardContent sx={{ pt: 5 }}>
<EmptyContent
filled
title="Product not found!"
title={t('Product not found!')}
action={
<Button
component={RouterLink}
@@ -94,7 +94,7 @@ export function ProductDetailsView({ product, error, loading }: Props) {
startIcon={<Iconify width={16} icon="eva:arrow-ios-back-fill" />}
sx={{ mt: 3 }}
>
Back to list
{t('Back to list')}
</Button>
}
sx={{ py: 10, height: 'auto', flexGrow: 'unset' }}

View File

@@ -81,6 +81,11 @@ export function ProductListView() {
{ value: 'out of stock', label: t('Out of stock') },
];
const PUBLISH_OPTIONS = [
{ value: 'published', label: t('Published') },
{ value: 'draft', label: t('Draft') },
];
useEffect(() => {
if (products.length) {
setTableData(products);
@@ -94,11 +99,6 @@ export function ProductListView() {
filters: currentFilters,
});
const PUBLISH_OPTIONS = [
{ value: 'published', label: t('Published') },
{ value: 'draft', label: t('Draft') },
];
const handleDeleteSingleRow = useCallback(async () => {
// const deleteRow = tableData.filter((row) => row.id !== id);
@@ -245,7 +245,7 @@ export function ProductListView() {
confirmDeleteMultiItemsDialog.onFalse();
}}
>
Delete
{t('Delete')}
</Button>
}
/>
@@ -269,7 +269,7 @@ export function ProductListView() {
confirmDeleteSingleItemDialog.onFalse();
}}
>
Delete
{t('Delete')}
</Button>
}
/>
@@ -279,7 +279,7 @@ export function ProductListView() {
<>
<DashboardContent sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
<CustomBreadcrumbs
heading="List"
heading={t('Product List')}
links={[
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('Product'), href: paths.dashboard.product.root },

View File

@@ -27,6 +27,7 @@ import { ProductDetailsReview } from '../product-details-review';
import { ProductDetailsSummary } from '../product-details-summary';
import { ProductDetailsCarousel } from '../product-details-carousel';
import { ProductDetailsDescription } from '../product-details-description';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -57,6 +58,7 @@ type Props = {
};
export function ProductShopDetailsView({ product, error, loading }: Props) {
const { t } = useTranslation();
const { state: checkoutState, onAddToCart } = useCheckoutContext();
const containerStyles: SxProps<Theme> = {
@@ -79,7 +81,7 @@ export function ProductShopDetailsView({ product, error, loading }: Props) {
<Container sx={containerStyles}>
<EmptyContent
filled
title="Product not found!"
title={t('Product not found!')}
action={
<Button
component={RouterLink}

View File

@@ -21,6 +21,7 @@ import { _socials } from 'src/_mock';
import { Iconify } from 'src/components/iconify';
import { ProfilePostItem } from './profile-post-item';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -31,6 +32,7 @@ type Props = {
export function ProfileHome({ info, posts }: Props) {
const fileRef = useRef<HTMLInputElement>(null);
const { t } = useTranslation();
const handleAttach = () => {
if (fileRef.current) {
@@ -40,21 +42,18 @@ export function ProfileHome({ info, posts }: Props) {
const renderFollows = () => (
<Card sx={{ py: 3, textAlign: 'center', typography: 'h4' }}>
<Stack
divider={<Divider orientation="vertical" flexItem sx={{ borderStyle: 'dashed' }} />}
sx={{ flexDirection: 'row' }}
>
<Stack divider={<Divider orientation="vertical" flexItem sx={{ borderStyle: 'dashed' }} />} sx={{ flexDirection: 'row' }}>
<Stack sx={{ width: 1 }}>
{fNumber(info.totalFollowers)}
<Box component="span" sx={{ color: 'text.secondary', typography: 'body2' }}>
Follower
{t('Follower')}
</Box>
</Stack>
<Stack sx={{ width: 1 }}>
{fNumber(info.totalFollowing)}
<Box component="span" sx={{ color: 'text.secondary', typography: 'body2' }}>
Following
{t('Following')}
</Box>
</Stack>
</Stack>
@@ -63,7 +62,7 @@ export function ProfileHome({ info, posts }: Props) {
const renderAbout = () => (
<Card>
<CardHeader title="About" />
<CardHeader title={t('About')} />
<Box
sx={{
@@ -143,16 +142,16 @@ export function ProfileHome({ info, posts }: Props) {
>
<Fab size="small" color="inherit" variant="softExtended" onClick={handleAttach}>
<Iconify icon="solar:gallery-wide-bold" width={24} sx={{ color: 'success.main' }} />
Image/Video
{t('Image/Video')}
</Fab>
<Fab size="small" color="inherit" variant="softExtended">
<Iconify icon="solar:videocamera-record-bold" width={24} sx={{ color: 'error.main' }} />
Streaming
{t('Streaming')}
</Fab>
</Box>
<Button variant="contained">Post</Button>
<Button variant="contained">{t('Post')}</Button>
</Box>
<input ref={fileRef} type="file" style={{ display: 'none' }} />
@@ -161,7 +160,7 @@ export function ProfileHome({ info, posts }: Props) {
const renderSocials = () => (
<Card>
<CardHeader title="Social" />
<CardHeader title={t('Social')} />
<Box sx={{ p: 3, gap: 2, display: 'flex', flexDirection: 'column', typography: 'body2' }}>
{_socials.map((social) => (

View File

@@ -7,15 +7,18 @@ import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import Typography from '@mui/material/Typography';
import { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { isValidPhoneNumber } from 'react-phone-number-input/input';
import { createUser, deleteUser, saveUser } from 'src/actions/user';
import { Field, Form, schemaHelper } from 'src/components/hook-form';
import { Label } from 'src/components/label';
import { toast } from 'src/components/snackbar';
import { useRouter } from 'src/routes/hooks';
import { paths } from 'src/routes/paths';
import type { IUserItem } from 'src/types/user';
import { fileToBase64 } from 'src/utils/file-to-base64';
import { fData } from 'src/utils/format-number';
import { z as zod } from 'zod';
@@ -24,26 +27,27 @@ import { z as zod } from 'zod';
export type NewUserSchemaType = zod.infer<typeof NewUserSchema>;
export const NewUserSchema = zod.object({
avatarUrl: schemaHelper.file({ message: 'Avatar is required!' }),
name: zod.string().min(1, { message: 'Name is required!' }),
city: zod.string().min(1, { message: 'City is required!' }),
role: zod.string().min(1, { message: 'Role is required!' }),
email: zod
.string()
.min(1, { message: 'Email is required!' })
.email({ message: 'Email must be a valid email address!' }),
phoneNumber: schemaHelper.phoneNumber({ isValid: isValidPhoneNumber }),
state: zod.string().min(1, { message: 'State is required!' }),
status: zod.string(),
address: zod.string().min(1, { message: 'Address is required!' }),
country: schemaHelper.nullableInput(zod.string().min(1, { message: 'Country is required!' }), {
// message for null value
message: 'Country is required!',
}),
address: zod.string().min(1, { message: 'Address is required!' }),
company: zod.string().min(1, { message: 'Company is required!' }),
state: zod.string().min(1, { message: 'State is required!' }),
city: zod.string().min(1, { message: 'City is required!' }),
role: zod.string().min(1, { message: 'Role is required!' }),
zipCode: zod.string().min(1, { message: 'Zip code is required!' }),
// Not required
status: zod.string(),
company: zod.string().min(1, { message: 'Company is required!' }),
avatarUrl: schemaHelper.file({ message: 'Avatar is required!' }),
phoneNumber: schemaHelper.phoneNumber({ isValid: isValidPhoneNumber }),
isVerified: zod.boolean(),
username: zod.string(),
password: zod.string(),
});
// ----------------------------------------------------------------------
@@ -61,16 +65,19 @@ export function UserNewEditForm({ currentUser }: Props) {
status: '',
avatarUrl: null,
isVerified: true,
name: '',
email: '',
phoneNumber: '',
country: '',
state: '',
city: '',
address: '',
zipCode: '',
company: '',
role: '',
name: '新用戶名字',
email: 'user@123.com',
phoneNumber: '+85291234567',
country: 'Hong Kong',
state: 'HK',
city: 'hong kong',
address: 'Kwun Tong, Sau Mau Ping',
zipCode: '00000',
company: 'test company',
role: 'user',
//
username: '',
password: '',
};
const methods = useForm<NewUserSchemaType>({
@@ -85,18 +92,50 @@ export function UserNewEditForm({ currentUser }: Props) {
watch,
control,
handleSubmit,
formState: { isSubmitting },
formState: { errors, isSubmitting },
} = methods;
const values = watch();
const onSubmit = handleSubmit(async (data) => {
const [disableDeleteUserButton, setDisableDeleteUserButton] = useState<boolean>(false);
const handleDeleteUserClick = async () => {
setDisableDeleteUserButton(true);
try {
if (currentUser) {
await deleteUser(currentUser.id);
toast.success(t('user deleted'));
router.push(paths.dashboard.user.list);
}
} catch (error) {
console.error(error);
}
setDisableDeleteUserButton(false);
};
const onSubmit = handleSubmit(async (data: any) => {
try {
await new Promise((resolve) => setTimeout(resolve, 500));
reset();
toast.success(currentUser ? 'Update success!' : 'Create success!');
const temp: any = data.avatarUrl;
if (temp instanceof File) {
data.avatarUrl = await fileToBase64(temp);
}
if (currentUser) {
// perform save
await saveUser(currentUser.id, data);
} else {
// perform create
await createUser(data);
}
toast.success(currentUser ? t('Update success!') : t('Create success!'));
router.push(paths.dashboard.user.list);
console.info('DATA', data);
// console.info('DATA', data);
} catch (error) {
console.error(error);
}
@@ -135,8 +174,8 @@ export function UserNewEditForm({ currentUser }: Props) {
color: 'text.disabled',
}}
>
Allowed *.jpeg, *.jpg, *.png, *.gif
<br /> max size of {fData(3145728)}
{t('Allowed')} *.jpeg, *.jpg, *.png, *.gif
<br /> {t('max size of')} {fData(3145728)}
</Typography>
}
/>
@@ -163,10 +202,10 @@ export function UserNewEditForm({ currentUser }: Props) {
label={
<>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Banned
{t('Banned')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
Apply disable account
{t('Apply disable account')}
</Typography>
</>
}
@@ -185,10 +224,10 @@ export function UserNewEditForm({ currentUser }: Props) {
label={
<>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Email verified
{t('Email verified')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
Disabling this will automatically send the user a verification email
{t('Disabling this will automatically send the user a verification email')}
</Typography>
</>
}
@@ -197,8 +236,14 @@ export function UserNewEditForm({ currentUser }: Props) {
{currentUser && (
<Stack sx={{ mt: 3, alignItems: 'center', justifyContent: 'center' }}>
<Button variant="soft" color="error">
Delete user
<Button
disabled={disableDeleteUserButton}
loading={disableDeleteUserButton}
variant="soft"
color="error"
onClick={handleDeleteUserClick}
>
{t('Delete user')}
</Button>
</Stack>
)}
@@ -215,32 +260,33 @@ export function UserNewEditForm({ currentUser }: Props) {
gridTemplateColumns: { xs: 'repeat(1, 1fr)', sm: 'repeat(2, 1fr)' },
}}
>
<Field.Text name="name" label="Full name" />
<Field.Text name="email" label="Email address" />
<Field.Phone
name="phoneNumber"
label="Phone number"
country={!currentUser ? 'DE' : undefined}
/>
<Field.Text name="name" label={t('Full name')} />
<Field.Text name="email" label={t('Email address')} />
<Field.Phone name="phoneNumber" label={t('Phone number')} country="HK" />
<Field.CountrySelect
fullWidth
name="country"
label="Country"
placeholder="Choose a country"
label={t('Country')}
placeholder={t('Choose a country')}
/>
<Field.Text name="state" label="State/region" />
<Field.Text name="city" label="City" />
<Field.Text name="state" label={t('State/region')} />
<Field.Text name="city" label={t('City')} />
<Field.Text name="address" label={t('Address')} />
<Field.Text name="zipCode" label="Zip/code" />
<Field.Text name="company" label="Company" />
<Field.Text name="role" label="Role" />
<Field.Text name="zipCode" label={t('Zip/code')} />
<Field.Text name="company" label={t('Company')} />
<Field.Text name="role" label={t('Role')} />
</Box>
<Stack sx={{ mt: 3, alignItems: 'flex-end' }}>
<Button type="submit" variant="contained" loading={isSubmitting}>
{!currentUser ? 'Create user' : 'Save changes'}
<Button
disabled={isSubmitting}
loading={isSubmitting}
type="submit"
variant="contained"
>
{!currentUser ? t('Create user') : t('Save changes')}
</Button>
</Stack>
</Card>

View File

@@ -19,6 +19,7 @@ import { Label } from 'src/components/label';
import { RouterLink } from 'src/routes/components';
import type { IUserItem } from 'src/types/user';
import { UserQuickEditForm } from './user-quick-edit-form';
import { useState } from 'react';
// ----------------------------------------------------------------------
@@ -55,7 +56,7 @@ export function UserTableRow({ row, selected, editHref, onSelectRow, onDeleteRow
<li>
<MenuItem component={RouterLink} href={editHref} onClick={() => menuActions.onClose()}>
<Iconify icon="solar:pen-bold" />
Edit
{t('Edit')}
</MenuItem>
</li>
@@ -67,21 +68,31 @@ export function UserTableRow({ row, selected, editHref, onSelectRow, onDeleteRow
sx={{ color: 'error.main' }}
>
<Iconify icon="solar:trash-bin-trash-bold" />
Delete
{t('Delete')}
</MenuItem>
</MenuList>
</CustomPopover>
);
const [disableDeleteButton, setDisableDeleteButton] = useState<boolean>(false);
const renderConfirmDialog = () => (
<ConfirmDialog
open={confirmDialog.value}
onClose={confirmDialog.onFalse}
title="Delete"
content="Are you sure want to delete?"
title={t('Delete')}
content={t('Are you sure want to delete user?')}
action={
<Button variant="contained" color="error" onClick={onDeleteRow}>
Delete
<Button
disabled={disableDeleteButton}
loading={disableDeleteButton}
variant="contained"
color="error"
onClick={() => {
setDisableDeleteButton(true);
onDeleteRow();
}}
>
{t('Delete')}
</Button>
}
/>

View File

@@ -10,27 +10,25 @@ import { Iconify } from 'src/components/iconify';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { UserCardList } from '../user-card-list';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
export function UserCardsView() {
const { t } = useTranslation();
return (
<DashboardContent>
<CustomBreadcrumbs
heading="User cards"
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'User', href: paths.dashboard.user.root },
{ name: 'Cards' },
//
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('User'), href: paths.dashboard.user.root },
{ name: t('Cards') },
]}
action={
<Button
component={RouterLink}
href={paths.dashboard.user.new}
variant="contained"
startIcon={<Iconify icon="mingcute:add-line" />}
>
New user
<Button component={RouterLink} href={paths.dashboard.user.new} variant="contained" startIcon={<Iconify icon="mingcute:add-line" />}>
{t('New user')}
</Button>
}
sx={{ mb: { xs: 3, md: 5 } }}

View File

@@ -5,18 +5,22 @@ import { DashboardContent } from 'src/layouts/dashboard';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { UserNewEditForm } from '../user-new-edit-form';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
export function UserCreateView() {
const { t } = useTranslation();
return (
<DashboardContent>
<CustomBreadcrumbs
heading="Create a new user"
heading={t('Create a new user')}
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'User', href: paths.dashboard.user.root },
{ name: 'New user' },
//
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('User'), href: paths.dashboard.user.root },
{ name: t('New user') },
]}
sx={{ mb: { xs: 3, md: 5 } }}
/>

View File

@@ -3,6 +3,7 @@ import { DashboardContent } from 'src/layouts/dashboard';
import { paths } from 'src/routes/paths';
import type { IUserItem } from 'src/types/user';
import { UserNewEditForm } from '../user-new-edit-form';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -11,14 +12,16 @@ type Props = {
};
export function UserEditView({ user: currentUser }: Props) {
const { t } = useTranslation();
return (
<DashboardContent>
<CustomBreadcrumbs
heading="Edit"
backHref={paths.dashboard.user.list}
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'User', href: paths.dashboard.user.root },
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('User'), href: paths.dashboard.user.root },
{ name: currentUser?.name },
]}
sx={{ mb: { xs: 3, md: 5 } }}

View File

@@ -13,7 +13,7 @@ import { varAlpha } from 'minimal-shared/utils';
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { _roles, _userList, USER_STATUS_OPTIONS } from 'src/_mock';
import { useGetUsers } from 'src/actions/user';
import { deleteUser, useGetUsers } from 'src/actions/user';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { ConfirmDialog } from 'src/components/custom-dialog';
import { Iconify } from 'src/components/iconify';
@@ -39,6 +39,8 @@ import type { IUserItem, IUserTableFilters } from 'src/types/user';
import { UserTableFiltersResult } from '../user-table-filters-result';
import { UserTableRow } from '../user-table-row';
import { UserTableToolbar } from '../user-table-toolbar';
import { Router } from 'react-router';
import { useRouter } from 'src/routes/hooks';
// ----------------------------------------------------------------------
@@ -48,6 +50,7 @@ const STATUS_OPTIONS = [{ value: 'all', label: 'All' }, ...USER_STATUS_OPTIONS];
export function UserListView() {
const { t } = useTranslation();
const router = useRouter();
const TABLE_HEAD: TableHeadCellProps[] = [
{ id: 'name', label: t('Name') },
@@ -59,12 +62,13 @@ export function UserListView() {
];
const { users, mutate } = useGetUsers();
const [processNewUser, setProcessNewUser] = useState<boolean>(false);
const table = useTable();
const confirmDialog = useBoolean();
const [tableData, setTableData] = useState<IUserItem[]>(_userList);
const [tableData, setTableData] = useState<IUserItem[]>([]);
useEffect(() => {
setTableData(users);
@@ -87,16 +91,22 @@ export function UserListView() {
const notFound = (!dataFiltered.length && canReset) || !dataFiltered.length;
const handleDeleteRow = useCallback(
(id: string) => {
const deleteRow = tableData.filter((row) => row.id !== id);
async (id: string) => {
// const deleteRow = tableData.filter((row) => row.id !== id);
// toast.success('Delete success!');
// setTableData(deleteRow);
// table.onUpdatePageDeleteRow(dataInPage.length);
toast.success('Delete success!');
setTableData(deleteRow);
table.onUpdatePageDeleteRow(dataInPage.length);
try {
await deleteUser(id);
toast.success('Delete success!');
mutate();
} catch (error) {
console.error(error);
toast.error('Delete failed!');
}
},
[dataInPage.length, table, tableData]
[table, tableData, mutate]
);
const handleDeleteRows = useCallback(() => {
@@ -121,7 +131,7 @@ export function UserListView() {
<ConfirmDialog
open={confirmDialog.value}
onClose={confirmDialog.onFalse}
title="Delete"
title={t('Delete')}
content={
<>
Are you sure want to delete <strong> {table.selected.length} </strong> items?
@@ -133,7 +143,7 @@ export function UserListView() {
color="error"
onClick={() => {
handleDeleteRows();
confirmDialog.onFalse();
// confirmDialog.onFalse();
}}
>
{t('Delete')}
@@ -142,22 +152,33 @@ export function UserListView() {
/>
);
useEffect(() => {
mutate();
}, []);
return (
<>
<DashboardContent>
<CustomBreadcrumbs
heading="List"
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'User', href: paths.dashboard.user.root },
{ name: 'List' },
//
{ name: t('Dashboard'), href: paths.dashboard.root },
{ name: t('User'), href: paths.dashboard.user.root },
{ name: t('List') },
]}
action={
<Button
component={RouterLink}
href={paths.dashboard.user.new}
disabled={processNewUser}
loading={processNewUser}
// component={RouterLink}
// href={paths.dashboard.user.new}
variant="contained"
startIcon={<Iconify icon="mingcute:add-line" />}
onClick={() => {
setProcessNewUser(true);
router.push(paths.dashboard.user.new);
}}
>
{t('New user')}
</Button>

View File

@@ -22,6 +22,7 @@ import { ProfileCover } from '../profile-cover';
import { ProfileFriends } from '../profile-friends';
import { ProfileGallery } from '../profile-gallery';
import { ProfileFollowers } from '../profile-followers';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -53,6 +54,8 @@ const NAV_ITEMS = [
const TAB_PARAM = 'tab';
export function UserProfileView() {
const { t } = useTranslation();
const pathname = usePathname();
const searchParams = useSearchParams();
const selectedTab = searchParams.get(TAB_PARAM) ?? '';
@@ -74,21 +77,12 @@ export function UserProfileView() {
<DashboardContent>
<CustomBreadcrumbs
heading="Profile"
links={[
{ name: 'Dashboard', href: paths.dashboard.root },
{ name: 'User', href: paths.dashboard.user.root },
{ name: user?.displayName },
]}
links={[{ name: t('Dashboard'), href: paths.dashboard.root }, { name: t('User'), href: paths.dashboard.user.root }, { name: user?.displayName }]}
sx={{ mb: { xs: 3, md: 5 } }}
/>
<Card sx={{ mb: 3, height: 290 }}>
<ProfileCover
role={_userAbout.role}
name={user?.displayName}
avatarUrl={user?.photoURL}
coverUrl={_userAbout.coverUrl}
/>
<ProfileCover role={_userAbout.role} name={user?.displayName} avatarUrl={user?.photoURL} coverUrl={_userAbout.coverUrl} />
<Box
sx={{
@@ -109,7 +103,7 @@ export function UserProfileView() {
key={tab.value}
value={tab.value}
icon={tab.icon}
label={tab.label}
label={t(tab.label)}
href={createRedirectPath(pathname, tab.value)}
/>
))}
@@ -121,13 +115,7 @@ export function UserProfileView() {
{selectedTab === 'followers' && <ProfileFollowers followers={_userFollowers} />}
{selectedTab === 'friends' && (
<ProfileFriends
friends={_userFriends}
searchFriends={searchFriends}
onSearchFriends={handleSearchFriends}
/>
)}
{selectedTab === 'friends' && <ProfileFriends friends={_userFriends} searchFriends={searchFriends} onSearchFriends={handleSearchFriends} />}
{selectedTab === 'gallery' && <ProfileGallery gallery={_userGallery} />}
</DashboardContent>

View File

@@ -34,6 +34,11 @@ if (navigator_language.startsWith('sc')) primaryFont = 'Noto Sans SC Variable';
// TODO: not tested, T.B.C.
if (navigator_language.startsWith('jp')) primaryFont = 'Noto Sans JP Variable';
console.log({
navigator_language,
primaryFont,
});
export const themeConfig: ThemeConfig = {
/** **************************************
* Base

View File

@@ -89,6 +89,9 @@ export type IUserItem = {
avatarUrl: string;
phoneNumber: string;
isVerified: boolean;
//
username: string;
password: string;
};
export type IUserAccountBillingHistory = {

View File

@@ -33,4 +33,7 @@ export default defineConfig({
},
server: { port: PORT, host: true },
preview: { port: PORT, host: true },
build: {
sourcemap: true,
},
});