Compare commits

...

3 Commits

Author SHA1 Message Date
louiscklaw
5a707427c6 "feat: enhance order management with new APIs and schema changes" 2025-05-30 11:40:25 +08:00
louiscklaw
834f58bde1 update, 2025-05-30 01:14:10 +08:00
louiscklaw
98bc3fe3ce update, 2025-05-30 01:13:54 +08:00
84 changed files with 1635 additions and 759 deletions

View File

@@ -27,7 +27,7 @@
"unseed": "tsx ./prisma/unseed.ts",
"db:generate": "prisma generate",
"db:push": "prisma db push --force-reset",
"db:push:w": "npx nodemon --delay 5 --ext \"ts,tsx,prisma\" --exec \"yarn db:push && yarn seed && yarn db:studio\"",
"db:push:w": "npx nodemon --delay 5 --ext \"ts,tsx,prisma\" --exec \"yarn db:push && yarn seed\"",
"db:studio": "prisma studio"
},
"engines": {

View File

@@ -266,85 +266,85 @@ model Mail {
// attachments MailAttachment[]
}
model OrderHistory {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
orderTime DateTime
paymentTime DateTime
deliveryTime DateTime
completionTime DateTime
timeline Json[]
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderHistory {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// orderTime DateTime @default(now())
// paymentTime DateTime
// deliveryTime DateTime
// completionTime DateTime
// timeline Json[]
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderShippingAddress {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
fullAddress String
phoneNumber String
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderShippingAddress {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// fullAddress String
// phoneNumber String
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderPayment {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
cardType String
cardNumber String
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderPayment {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// cardType String
// cardNumber String
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderDelivery {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
shipBy String
speedy String
trackingNumber String
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderDelivery {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// shipBy String
// speedy String
// trackingNumber String
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderCustomer {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
name String
email String
avatarUrl String
ipAddress String
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderCustomer {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// name String
// email String
// avatarUrl String
// ipAddress String
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderProductItem {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
sku String
name String
price Float
coverUrl String
quantity Float
OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
orderItemId Int?
}
// model OrderProductItem {
// id Int @id @default(autoincrement())
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// //
// sku String
// name String
// price Float
// coverUrl String
// quantity Float
// OrderItem OrderItem? @relation(fields: [orderItemId], references: [id])
// orderItemId Int?
// }
model OrderItem {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
taxes Float
status String
@@ -354,12 +354,18 @@ model OrderItem {
orderNumber String
totalAmount Float
totalQuantity Float
history OrderHistory[]
payment OrderPayment[]
customer OrderCustomer[]
delivery OrderDelivery[]
items OrderProductItem[]
shippingAddress OrderShippingAddress[]
history Json
payment Json
customer Json
delivery Json
items Json[]
shippingAddress Json
// OrderProductItem OrderProductItem[]
// OrderHistory OrderHistory[]
// OrderDelivery OrderDelivery[]
// OrderCustomer OrderCustomer[]
// OrderPayment OrderPayment[]
// OrderShippingAddress OrderShippingAddress[]
}
// src/types/tour.ts
@@ -511,7 +517,7 @@ model UserCard {
}
model UserItem {
id Int @id @default(autoincrement())
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//

View File

@@ -23,6 +23,8 @@ import { ProductReview } from './seeds/productReview';
import { ProductItem } from './seeds/productItem';
import { FileStore } from './seeds/fileStore';
import { userItemSeed } from './seeds/userItem';
import { orderItemSeed } from './seeds/orderItem';
//
// import { Blog } from './seeds/blog';
// import { Mail } from './seeds/mail';
@@ -39,6 +41,7 @@ import { userItemSeed } from './seeds/userItem';
await FileStore;
await ProductItem;
await userItemSeed;
await orderItemSeed;
// await Blog;
// await Mail;
// await File;

View File

@@ -10,8 +10,8 @@ async function order() {
title: 'Single Party with Dating',
order_time: new Date(),
last_payment_date: new Date(),
status: 'Pending'
}
status: 'Pending',
},
});
}

View File

@@ -0,0 +1,94 @@
import { PrismaClient } from '@prisma/client';
import { _mock } from './_mock';
const prisma = new PrismaClient();
const ITEMS = Array.from({ length: 3 }, (_, index) => ({
id: _mock.id(index),
sku: `16H9UR${index}`,
quantity: index + 1,
name: _mock.productName(index),
coverUrl: _mock.image.product(index),
price: _mock.number.price(index),
}));
async function orderItem() {
await prisma.orderItem.deleteMany({});
for (let index = 1; index < 20 + 1; index++) {
const shipping = 10;
const discount = 10;
const taxes = 10;
const items = (index % 2 && ITEMS.slice(0, 1)) || (index % 3 && ITEMS.slice(1, 3)) || ITEMS;
const totalQuantity = items.reduce((accumulator, item) => accumulator + item.quantity, 0);
const subtotal = items.reduce((accumulator, item) => accumulator + item.price * item.quantity, 0);
const totalAmount = subtotal - shipping - discount + taxes;
const customer = {
id: _mock.id(index),
name: _mock.fullName(index),
email: _mock.email(index),
avatarUrl: _mock.image.avatar(index),
ipAddress: '192.158.1.38',
};
const delivery = { shipBy: 'DHL', speedy: 'Standard', trackingNumber: 'SPX037739199373' };
const history = {
orderTime: _mock.time(1),
paymentTime: _mock.time(2),
deliveryTime: _mock.time(3),
completionTime: _mock.time(4),
timeline: [
{ title: 'Delivery successful', time: _mock.time(1) },
{ title: 'Transporting to [2]', time: _mock.time(2) },
{ title: 'Transporting to [1]', time: _mock.time(3) },
{ title: 'The shipping unit has picked up the goods', time: _mock.time(4) },
{ title: 'Order has been created', time: _mock.time(5) },
],
};
const temp = await prisma.orderItem.upsert({
where: { id: index.toString() },
update: {},
create: {
id: index.toString(),
orderNumber: `#601${index}`,
taxes,
items,
history,
subtotal: items.reduce((accumulator, item) => accumulator + item.price * item.quantity, 0),
shipping,
discount,
customer,
delivery,
totalAmount,
totalQuantity,
shippingAddress: {
fullAddress: '19034 Verna Unions Apt. 164 - Honolulu, RI / 87535',
phoneNumber: '365-374-4961',
},
payment: {
//
cardType: 'mastercard',
cardNumber: '4111 1111 1111 1111',
},
status: (index % 2 && 'completed') || (index % 3 && 'pending') || (index % 4 && 'cancelled') || 'refunded',
},
});
}
console.log('seed orderItem done');
}
const orderItemSeed = orderItem()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
export { orderItemSeed };

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

@@ -0,0 +1,98 @@
// src/app/api/product/saveProduct/route.ts
//
// PURPOSE:
// save product to db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* PUT - change order status
*************************************** */
export async function PUT(req: NextRequest) {
// logger('[Order] list', products.length);
const { searchParams } = req.nextUrl;
const orderId = searchParams.get('orderId');
// RULES: orderId must exist
if (!orderId) {
return response({ message: 'Order ID is required!' }, STATUS.BAD_REQUEST);
}
const { data } = await req.json();
try {
const order = await prisma.orderItem.updateMany({
where: { id: orderId },
data: { status: data.status },
});
return response({ order }, STATUS.OK);
} catch (error) {
console.log({ data });
return handleError('Order - Get list', error);
}
}
export type IProductItem = {
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;
// createdAt: IDateValue;
inventoryType: string;
subDescription: string;
priceSale: number | null;
// reviews: IProductReview[];
newLabel: {
content: string;
enabled: boolean;
};
saleLabel: {
content: string;
enabled: boolean;
};
ratings: {
name: string;
starCount: number;
reviewCount: number;
}[];
};
export type IDateValue = string | number | null;
export type IProductReview = {
id: string;
name: string;
rating: number;
comment: string;
helpful: number;
avatarUrl: string;
postedAt: IDateValue;
isPurchased: boolean;
attachments?: string[];
};

View File

@@ -0,0 +1,9 @@
###
PUT http://localhost:7272/api/order/changeStatus?orderId=1
content-type: application/json
{
"data":{"status": "helloworld"}
}

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

@@ -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

@@ -0,0 +1,47 @@
// src/app/api/order/details/route.ts
//
// PURPOSE:
// read order 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';
// ----------------------------------------------------------------------
/** **************************************
* GET Order detail
*************************************** */
export async function GET(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
// RULES: orderId must exist
const orderId = searchParams.get('orderId');
if (!orderId) {
return response({ message: 'orderId is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: orderId confirmed exist, run below
const order = await prisma.orderItem.findFirst({
// include: { reviews: true },
where: { id: orderId.toString() },
});
if (!order) {
return response({ message: 'Order not found!' }, STATUS.NOT_FOUND);
}
logger('[Order] details', order.id);
return response({ order }, STATUS.OK);
} catch (error) {
return handleError('Product - Get details', error);
}
}

View File

@@ -0,0 +1,4 @@
###
GET http://localhost:7272/api/order/details?orderId=1

View File

@@ -0,0 +1,30 @@
// src/app/api/product/image/upload/route.ts
//
// PURPOSE:
// handle upload product image
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
// import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* GET - Products
*************************************** */
export async function POST(req: NextRequest) {
try {
const { data } = await req.json();
console.log('helloworld');
return response({ hello: 'world' }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world' });
return handleError('Product - store product image', error);
}
}

View File

@@ -0,0 +1,22 @@
// src/app/api/order/list/route.ts
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* GET - OrderItem
*************************************** */
export async function GET() {
try {
const orders = await prisma.orderItem.findMany();
logger('[Order] list', orders.length);
return response({ orders }, STATUS.OK);
} catch (error) {
return handleError('OrderItem - Get list', error);
}
}

View File

@@ -0,0 +1,3 @@
###
GET http://localhost:7272/api/order/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

@@ -0,0 +1,37 @@
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import { _products } from 'src/_mock/_product';
// ----------------------------------------------------------------------
export const runtime = 'edge';
/** **************************************
* GET - Search products
*************************************** */
export async function GET(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
const query = searchParams.get('query')?.trim().toLowerCase();
if (!query) {
return response({ results: [] }, STATUS.OK);
}
const products = _products();
// Accept search by name or sku
const results = products.filter(
({ name, sku }) => name.toLowerCase().includes(query) || sku?.toLowerCase().includes(query)
);
logger('[Product] search-results', results.length);
return response({ results }, STATUS.OK);
} catch (error) {
return handleError('Product - Get search', error);
}
}

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

@@ -0,0 +1,115 @@
// src/app/api/product/saveProduct/route.ts
//
// PURPOSE:
// save product to db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* GET - Products
*************************************** */
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 user = await prisma.userItem.updateMany({
where: { id: userId },
data: {
status: data.status,
avatarUrl: data.avatarUrl,
isVerified: data.isVerified,
name: data.name,
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,
//
username: data.username,
password: data.password,
},
});
return response({ user }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world', data });
return handleError('Product - Get list', error);
}
}
export type IProductItem = {
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;
// createdAt: IDateValue;
inventoryType: string;
subDescription: string;
priceSale: number | null;
// reviews: IProductReview[];
newLabel: {
content: string;
enabled: boolean;
};
saleLabel: {
content: string;
enabled: boolean;
};
ratings: {
name: string;
starCount: number;
reviewCount: number;
}[];
};
export type IDateValue = string | number | null;
export type IProductReview = {
id: string;
name: string;
rating: number;
comment: string;
helpful: number;
avatarUrl: string;
postedAt: IDateValue;
isPurchased: boolean;
attachments?: string[];
};

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

@@ -75,7 +75,11 @@ export const _orders = Array.from({ length: 20 }, (_, index) => {
fullAddress: '19034 Verna Unions Apt. 164 - Honolulu, RI / 87535',
phoneNumber: '365-374-4961',
},
payment: { cardType: 'mastercard', cardNumber: '**** **** **** 5678' },
payment: {
//
cardType: 'mastercard',
cardNumber: '**** **** **** 5678',
},
status:
(index % 2 && 'completed') ||
(index % 3 && 'pending') ||

View File

@@ -0,0 +1,226 @@
// src/actions/order.ts
import { useMemo } from 'react';
import axiosInstance, { endpoints, fetcher } from 'src/lib/axios';
import type { IProductItem } from 'src/types/product';
import type { IOrderItem } from 'src/types/order';
import type { SWRConfiguration } from 'swr';
import useSWR from 'swr';
// ----------------------------------------------------------------------
const swrOptions: SWRConfiguration = {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
};
// ----------------------------------------------------------------------
type OrdersData = {
orders: IOrderItem[];
};
export function useGetOrders() {
const url = endpoints.order.list;
const { data, isLoading, error, isValidating, mutate } = useSWR<OrdersData>(
url,
fetcher,
swrOptions
);
const memoizedValue = useMemo(
() => ({
orders: data?.orders || [],
ordersLoading: isLoading,
ordersError: error,
ordersValidating: isValidating,
ordersEmpty: !isLoading && !isValidating && !data?.orders.length,
mutate,
}),
[data?.orders, error, isLoading, isValidating, mutate]
);
return memoizedValue;
}
// ----------------------------------------------------------------------
type OrderData = {
order: IOrderItem;
};
export function useGetOrder(orderId: string) {
const url = orderId ? [endpoints.order.details, { params: { orderId } }] : '';
const { data, isLoading, error, isValidating } = useSWR<OrderData>(url, fetcher, swrOptions);
const memoizedValue = useMemo(
() => ({
order: data?.order,
orderLoading: isLoading,
orderError: error,
orderValidating: isValidating,
}),
[data?.order, error, isLoading, isValidating]
);
return memoizedValue;
}
// ----------------------------------------------------------------------
type SearchResultsData = {
results: IProductItem[];
};
export function useSearchProducts(query: string) {
const url = query ? [endpoints.product.search, { params: { query } }] : '';
const { data, isLoading, error, isValidating } = useSWR<SearchResultsData>(url, fetcher, {
...swrOptions,
keepPreviousData: true,
});
const memoizedValue = useMemo(
() => ({
searchResults: data?.results || [],
searchLoading: isLoading,
searchError: error,
searchValidating: isValidating,
searchEmpty: !isLoading && !isValidating && !data?.results.length,
}),
[data?.results, error, isLoading, isValidating]
);
return memoizedValue;
}
// ----------------------------------------------------------------------
type SaveOrderData = {
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;
//
ordername: string;
password: string;
};
export async function saveOrder(orderId: string, saveOrderData: SaveOrderData) {
// const url = orderId ? [endpoints.order.details, { params: { orderId } }] : '';
const res = await axiosInstance.post(
//
`http://localhost:7272/api/order/saveOrder?orderId=${orderId}`,
{
data: saveOrderData,
}
);
return res;
}
export async function uploadOrderImage(saveOrderData: SaveOrderData) {
console.log('uploadOrderImage ?');
// const url = orderId ? [endpoints.order.details, { params: { orderId } }] : '';
const res = await axiosInstance.get('http://localhost:7272/api/product/helloworld');
return res;
}
// ----------------------------------------------------------------------
type CreateOrderData = {
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;
//
ordername: string;
password: string;
};
export async function createOrder(createOrderData: CreateOrderData) {
console.log('create product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
const res = await axiosInstance.post('http://localhost:7272/api/order/createOrder', {
data: createOrderData,
});
return res;
}
// ----------------------------------------------------------------------
type DeleteOrderResponse = {
success: boolean;
message?: string;
};
export async function deleteOrder(orderId: string): Promise<DeleteOrderResponse> {
const url = `http://localhost:7272/api/order/deleteOrder?orderId=${orderId}`;
try {
const res = await axiosInstance.delete(url);
return {
success: true,
message: 'Order deleted successfully',
};
} catch (error) {
return {
success: false,
message: error instanceof Error ? error.message : 'Failed to delete product',
};
}
}
// ----------------------------------------------------------------------
type ChangeStatusResponse = {
success: boolean;
message?: string;
};
export async function changeStatus(
orderId: string,
newOrderStatus: string
): Promise<ChangeStatusResponse> {
const url = endpoints.order.changeStatus(orderId);
try {
const res = await axiosInstance.put(url, { data: { status: newOrderStatus } });
return {
success: true,
message: 'status updated successfully',
};
} catch (error) {
return {
success: false,
message: error instanceof Error ? error.message : 'Failed to delete product',
};
}
}

View File

@@ -1,3 +1,4 @@
// src/actions/product.ts
import { useMemo } from 'react';
import axiosInstance, { endpoints, fetcher } from 'src/lib/axios';
import type { IProductItem } from 'src/types/product';

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

@@ -1,7 +1,9 @@
// src/pages/dashboard/order/details.tsx
import { useParams } from 'src/routes/hooks';
import { _orders } from 'src/_mock/_order';
import { CONFIG } from 'src/global-config';
import { useGetOrder } from 'src/actions/order';
import { OrderDetailsView } from 'src/sections/order/view';
@@ -12,13 +14,18 @@ const metadata = { title: `Order details | Dashboard - ${CONFIG.appName}` };
export default function Page() {
const { id = '' } = useParams();
const currentOrder = _orders.find((order) => order.id === id);
// const currentOrder = _orders.find((order) => order.id === id);
// TODO: error handling
const { order, orderLoading, orderError } = useGetOrder(id);
if (!order) return <>loading</>;
if (orderLoading) return <>loading</>;
return (
<>
<title>{metadata.title}</title>
<OrderDetailsView order={currentOrder} />
<OrderDetailsView order={order} />
</>
);
}

View File

@@ -1,3 +1,5 @@
// src/pages/dashboard/product/details.tsx
import { useParams } from 'src/routes/hooks';
import { CONFIG } from 'src/global-config';

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/order-details-history.tsx
import type { IOrderHistory } from 'src/types/order';
import Box from '@mui/material/Box';
@@ -13,6 +14,7 @@ import TimelineConnector from '@mui/lab/TimelineConnector';
import TimelineItem, { timelineItemClasses } from '@mui/lab/TimelineItem';
import { fDateTime } from 'src/utils/format-time';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -21,6 +23,8 @@ type Props = {
};
export function OrderDetailsHistory({ history }: Props) {
const { t } = useTranslation();
const renderSummary = () => (
<Paper
variant="outlined"
@@ -37,22 +41,22 @@ export function OrderDetailsHistory({ history }: Props) {
}}
>
<div>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>Order time</Box>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>{t('Order time')}</Box>
{fDateTime(history?.orderTime)}
</div>
<div>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>Payment time</Box>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>{t('Payment time')}</Box>
{fDateTime(history?.orderTime)}
</div>
<div>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>Delivery time for the carrier</Box>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>{t('Delivery time for the carrier')}</Box>
{fDateTime(history?.orderTime)}
</div>
<div>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>Completion time</Box>
<Box sx={{ mb: 0.5, color: 'text.disabled' }}>{t('Completion time')}</Box>
{fDateTime(history?.orderTime)}
</div>
</Paper>

View File

@@ -12,6 +12,7 @@ import { fCurrency } from 'src/utils/format-number';
import { Iconify } from 'src/components/iconify';
import { Scrollbar } from 'src/components/scrollbar';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -34,6 +35,7 @@ export function OrderDetailsItems({
totalAmount,
...other
}: Props) {
const { t } = useTranslation();
const renderTotal = () => (
<Box
sx={{
@@ -47,32 +49,32 @@ export function OrderDetailsItems({
}}
>
<Box sx={{ display: 'flex' }}>
<Box sx={{ color: 'text.secondary' }}>Subtotal</Box>
<Box sx={{ color: 'text.secondary' }}>{t('Subtotal')}</Box>
<Box sx={{ width: 160, typography: 'subtitle2' }}>{fCurrency(subtotal) || '-'}</Box>
</Box>
<Box sx={{ display: 'flex' }}>
<Box sx={{ color: 'text.secondary' }}>Shipping</Box>
<Box sx={{ color: 'text.secondary' }}>{t('Shipping')}</Box>
<Box sx={{ width: 160, ...(shipping && { color: 'error.main' }) }}>
{shipping ? `- ${fCurrency(shipping)}` : '-'}
</Box>
</Box>
<Box sx={{ display: 'flex' }}>
<Box sx={{ color: 'text.secondary' }}>Discount</Box>
<Box sx={{ color: 'text.secondary' }}>{t('Discount')}</Box>
<Box sx={{ width: 160, ...(discount && { color: 'error.main' }) }}>
{discount ? `- ${fCurrency(discount)}` : '-'}
</Box>
</Box>
<Box sx={{ display: 'flex' }}>
<Box sx={{ color: 'text.secondary' }}>Taxes</Box>
<Box sx={{ color: 'text.secondary' }}>{t('Taxes')}</Box>
<Box sx={{ width: 160 }}>{taxes ? fCurrency(taxes) : '-'}</Box>
</Box>
<Box sx={{ display: 'flex', typography: 'subtitle1' }}>
<div>Total</div>
<div>{t('Total')}</div>
<Box sx={{ width: 160 }}>{fCurrency(totalAmount) || '-'}</Box>
</Box>
</Box>

View File

@@ -1,3 +1,5 @@
// src/sections/order/order-details-toolbar.tsx
import type { IDateValue } from 'src/types/common';
import { usePopover } from 'minimal-shared/hooks';
@@ -17,6 +19,7 @@ import { fDateTime } from 'src/utils/format-time';
import { Label } from 'src/components/label';
import { Iconify } from 'src/components/iconify';
import { CustomPopover } from 'src/components/custom-popover';
import { useTranslation } from 'react-i18next';
// ----------------------------------------------------------------------
@@ -37,6 +40,7 @@ export function OrderDetailsToolbar({
statusOptions,
onChangeStatus,
}: Props) {
const { t } = useTranslation();
const menuActions = usePopover();
const renderMenuActions = () => (
@@ -56,7 +60,7 @@ export function OrderDetailsToolbar({
onChangeStatus(option.value);
}}
>
{option.label}
{t(option.label)}
</MenuItem>
))}
</MenuList>
@@ -124,11 +128,11 @@ export function OrderDetailsToolbar({
variant="outlined"
startIcon={<Iconify icon="solar:printer-minimalistic-bold" />}
>
Print
{t('Print (not implemented)')}
</Button>
<Button color="inherit" variant="contained" startIcon={<Iconify icon="solar:pen-bold" />}>
Edit
{t('Edit')}
</Button>
</Box>
</Box>

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,6 +1,8 @@
// src/sections/order/view/order-details-view.tsx
import type { IOrderItem } from 'src/types/order';
import { useState, useCallback } from 'react';
import { useState, useCallback, useEffect } from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
@@ -19,19 +21,39 @@ import { OrderDetailsPayment } from '../order-details-payment';
import { OrderDetailsCustomer } from '../order-details-customer';
import { OrderDetailsDelivery } from '../order-details-delivery';
import { OrderDetailsShipping } from '../order-details-shipping';
import { useTranslate } from 'src/locales';
import { useTranslation } from 'react-i18next';
import { changeStatus } from 'src/actions/order';
import { toast } from 'sonner';
// ----------------------------------------------------------------------
type Props = {
order?: IOrderItem;
order: IOrderItem;
};
export function OrderDetailsView({ order }: Props) {
const [status, setStatus] = useState(order?.status);
const { t } = useTranslation();
const handleChangeStatus = useCallback((newValue: string) => {
setStatus(newValue);
}, []);
const [status, setStatus] = useState(order.status);
const handleChangeStatus = useCallback(
async (newValue: string) => {
setStatus(newValue);
// change order status
try {
if (order?.id) {
await changeStatus(order.id, newValue);
toast.success('order status updated');
}
} catch (error) {
console.error(error);
toast.warning('error during update order status');
}
},
[order.id]
);
return (
<DashboardContent>
@@ -47,7 +69,12 @@ export function OrderDetailsView({ order }: Props) {
<Grid container spacing={3}>
<Grid size={{ xs: 12, md: 8 }}>
<Box
sx={{ gap: 3, display: 'flex', flexDirection: { xs: 'column-reverse', md: 'column' } }}
sx={{
//
gap: 3,
display: 'flex',
flexDirection: { xs: 'column-reverse', md: 'column' },
}}
>
<OrderDetailsItems
items={order?.items}

View File

@@ -1,7 +1,9 @@
// src/sections/order/view/order-list-view.tsx
import type { TableHeadCellProps } from 'src/components/table';
import type { IOrderItem, IOrderTableFilters } from 'src/types/order';
import { useState, useCallback } from 'react';
import { useState, useCallback, useEffect } from 'react';
import { varAlpha } from 'minimal-shared/utils';
import { useBoolean, useSetState } from 'minimal-shared/hooks';
@@ -43,29 +45,41 @@ 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';
import { useRouter } from 'src/routes/hooks';
import { deleteOrder, useGetOrders } from 'src/actions/order';
// ----------------------------------------------------------------------
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 router = useRouter();
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 { orders, mutate, ordersLoading } = useGetOrders();
const table = useTable({ defaultOrderBy: 'orderNumber' });
const confirmDialog = useBoolean();
const [tableData, setTableData] = useState<IOrderItem[]>(_orders);
const [tableData, setTableData] = useState<IOrderItem[]>([]);
useEffect(() => {
setTableData(orders);
}, [orders]);
const filters = useSetState<IOrderTableFilters>({
name: '',
@@ -94,16 +108,23 @@ export function OrderListView() {
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!');
try {
await deleteOrder(id);
toast.success('Delete success!');
mutate();
} catch (error) {
console.error(error);
toast.error('Delete failed!');
}
setTableData(deleteRow);
table.onUpdatePageDeleteRow(dataInPage.length);
// toast.success('Delete success!');
// setTableData(deleteRow);
// table.onUpdatePageDeleteRow(dataInPage.length);
},
[dataInPage.length, table, tableData]
[table, tableData, mutate]
);
const handleDeleteRows = useCallback(() => {
@@ -128,7 +149,7 @@ export function OrderListView() {
<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?
@@ -140,24 +161,32 @@ export function OrderListView() {
color="error"
onClick={() => {
handleDeleteRows();
confirmDialog.onFalse();
// confirmDialog.onFalse();
}}
>
Delete
{t('Delete')}
</Button>
}
/>
);
useEffect(() => {
mutate();
}, []);
if (!orders) return <>loading</>;
if (ordersLoading) return <>loading</>;
return (
<>
<DashboardContent>
<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 +207,7 @@ export function OrderListView() {
key={tab.value}
iconPosition="end"
value={tab.value}
label={tab.label}
label={t(tab.label)}
icon={
<Label
variant={
@@ -228,7 +257,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

@@ -1,3 +1,5 @@
// src/sections/product/view/product-details-view.tsx
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
@@ -86,7 +88,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 +96,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>
@@ -231,7 +252,7 @@ export function UserListView() {
)
}
action={
<Tooltip title="Delete">
<Tooltip title={t('Delete')}>
<IconButton color="primary" onClick={confirmDialog.onTrue}>
<Iconify icon="solar:trash-bin-trash-bold" />
</IconButton>

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

@@ -52,6 +52,8 @@ export type IOrderProductItem = {
export type IOrderItem = {
id: string;
createdAt: IDateValue;
//
taxes: number;
status: string;
shipping: number;
@@ -60,8 +62,7 @@ export type IOrderItem = {
orderNumber: string;
totalAmount: number;
totalQuantity: number;
createdAt: IDateValue;
history: IOrderHistory;
history: IOrderHistory | undefined;
payment: IOrderPayment;
customer: IOrderCustomer;
delivery: IOrderDelivery;

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,
},
});