Compare commits

..

19 Commits

Author SHA1 Message Date
louiscklaw
c319c103f6 "add .env.example with API endpoint configurations" 2025-06-15 04:28:03 +08:00
louiscklaw
3213ef951b update, 2025-06-15 04:24:57 +08:00
louiscklaw
cc35015a3e update, 2025-06-15 04:23:50 +08:00
louiscklaw
253c2f2487 update, 2025-06-15 04:23:06 +08:00
louiscklaw
c74a273928 update, 2025-06-15 04:22:18 +08:00
louiscklaw
bebf9834e6 update, 2025-06-15 04:09:29 +08:00
louiscklaw
45bac1b3c8 update, 2025-06-15 03:50:15 +08:00
louiscklaw
862c5bd29c "add isDev environment flag to constants" 2025-06-15 02:52:37 +08:00
louiscklaw
1e1a2d63ae "update dev script to install dev dependencies and clear screen before running dev" 2025-06-15 02:51:57 +08:00
louiscklaw
3d2a8bb4f8 "update dev script to run db:push, seed and db:studio in development workflow" 2025-06-15 02:47:41 +08:00
louiscklaw
f53cf9d932 "implement product CRUD API endpoints and frontend integration" 2025-06-15 02:47:25 +08:00
louiscklaw
48e90bca1b update docker compose dev ports to expose mobile service on port 8081 2025-06-15 02:26:28 +08:00
louiscklaw
c3c93fbde9 "update dev script to clear screen and run lint check" 2025-06-15 02:26:19 +08:00
louiscklaw
17080edb40 update REQ0185, 2025-06-14 22:26:00 +08:00
louiscklaw
17249dee44 update REQ0185, 2025-06-14 22:25:08 +08:00
louiscklaw
bd7e6dd9e0 update REQ0183 2025-06-14 13:24:59 +08:00
louiscklaw
87ccb2f1ff update REQ0182, REQ0183, 2025-06-14 12:41:17 +08:00
louiscklaw
46f784d587 update add REQ0181 & REQ0182, 2025-06-14 12:31:00 +08:00
louiscklaw
66b9bf5bdd "Update docker compose files to expose service ports as per REQ0180" 2025-06-13 18:56:56 +08:00
82 changed files with 932 additions and 524 deletions

View File

@@ -0,0 +1,9 @@
---
tags: frontend, side-menu
---
# REQ0181 frontend side menu configuration
## sources
`src/layouts/nav-config-dashboard.tsx`

View File

@@ -0,0 +1,11 @@
---
tags: frontend, product, details
---
# REQ0182 frontend product details
frontend page to display product details
## sources
T.B.A.

View File

@@ -0,0 +1,15 @@
---
tags: frontend, product, new
---
# REQ0183 frontend product new
frontend page to create new product
## sources
T.B.A.
## branch
develop/requirements/REQ0183

View File

@@ -0,0 +1,17 @@
---
tags: frontend, product, delete
---
# REQ0184 frontend product delete
frontend page to delete product
list page
## sources
T.B.A.
## branch
develop/requirements/REQ0184

View File

@@ -0,0 +1,17 @@
---
tags: frontend, product, update
---
# REQ0185 frontend product update
frontend page to update product
edit page T.B.A.
## sources
T.B.A.
## branch
develop/requirements/REQ0185

View File

@@ -158,3 +158,8 @@
- [REQ0169: DemoStorageExample](./REQ0169/index.md)
- [REQ0170: DemoWeatherAppUi](./REQ0170/index.md)
- [REQ0180: REQ0180 service port schedule](./REQ0180/index.md)
- [REQ0181: REQ0181 frontend side menu configuration](./REQ0181/index.md)
- [REQ0182: REQ0182 frontend product details](./REQ0182/index.md)
- [REQ0183: REQ0183 frontend product new](./REQ0183/index.md)
- [REQ0184: REQ0184 frontend product delete](./REQ0184/index.md)
- [REQ0185: REQ0185 frontend product update](./REQ0185/index.md)

View File

@@ -195,32 +195,32 @@ model ProductItem {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
sku String
name String
code String
price Float
taxes Float
tags String[]
sizes String[]
publish String
gender String[]
coverUrl String
images String[]
colors String[]
quantity Int
category String
available Int
totalSold Int
category String
code String
colors String[]
coverUrl String
description String
totalRatings Float
totalReviews Int
gender String[]
images String[]
inventoryType String
subDescription String
priceSale Float?
name String
newLabel Json
saleLabel Json
price Float
priceSale Float?
publish String
quantity Int
ratings Json[]
reviews ProductReview[]
saleLabel Json
sizes String[]
sku String
subDescription String
tags String[]
taxes Float
totalRatings Float
totalReviews Int
totalSold Int
}
model MailSender {

View File

@@ -1,7 +1,16 @@
#!/usr/bin/env bash
yarn --dev
clear
while true; do
yarn --dev
yarn db:push
yarn seed
yarn db:studio &
yarn dev
echo "restarting..."

View File

@@ -0,0 +1,43 @@
// src/app/api/product/createProduct/route.ts
// REQ0183 frontend product new
//
// PURPOSE:
// create product to db
//
// RULES:
// T.B.A.
//
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { isDev } from 'src/constants';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
/** **************************************
* POST - Products
*************************************** */
export async function POST(req: NextRequest) {
const { productData } = await req.json();
try {
if (isDev) {
console.log({ productData });
}
await prisma.productItem.create({ data: productData });
if (isDev) {
console.log('create done');
}
return response({ hello: 'world' }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world', productData });
return handleError('Product - Create', error);
}
}

View File

@@ -0,0 +1,51 @@
###
POST http://localhost:7272/api/product/createProduct
Content-Type: application/json
{
"data": {
"available": 99,
"category": "T-shirts",
"code": "PD-12345",
"colors": [
"Red"
],
"coverUrl": "",
"description": "this is description, 会員管理機能は、単なるデータ管理ツール以上の価値を持ちます。 企業は顧客の情報や動向を深く理解し、長期的な顧客関係の構築やロイヤルティの確立、そして迅速な市場変動への対応に直結します。 会員管理機能は、現代のビジネスにおいて企業の競争力を高める基盤として欠かせないものとなっています。",
"gender": [
"Men"
],
"images": [
"data:image/png;base64,C",
"data:image/png;base64,C"
],
"inventoryType": "test",
"name": "hello product",
"newLabel": {
"enabled": false,
"content": ""
},
"price": 99.99,
"priceSale": null,
"publish": "yes",
"quantity": 99,
"saleLabel": {
"enabled": false,
"content": ""
},
"sizes": [
"7"
],
"sku": "SK-122345",
"subDescription": "this is test sub-description",
"tags": [
"Travel",
"Finance"
],
"taxes": 0,
"totalRatings": 1,
"totalReviews": 1,
"totalSold": 1
}
}

View File

@@ -1,4 +1,5 @@
// src/app/api/product/createProduct/route.ts
// REQ0183 frontend product new
//
// PURPOSE:
// create product to db
@@ -11,6 +12,8 @@ import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { isDev } from 'src/constants';
import prisma from '../../../lib/prisma';
// ----------------------------------------------------------------------
@@ -19,57 +22,22 @@ 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 });
if (isDev) {
console.log({ data });
}
await prisma.productItem.create({ data });
if (isDev) {
console.log('create done');
}
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,51 @@
###
POST http://localhost:7272/api/product/createProduct
Content-Type: application/json
{
"data": {
"available": 99,
"category": "T-shirts",
"code": "PD-12345",
"colors": [
"Red"
],
"coverUrl": "",
"description": "this is description, 会員管理機能は、単なるデータ管理ツール以上の価値を持ちます。 企業は顧客の情報や動向を深く理解し、長期的な顧客関係の構築やロイヤルティの確立、そして迅速な市場変動への対応に直結します。 会員管理機能は、現代のビジネスにおいて企業の競争力を高める基盤として欠かせないものとなっています。",
"gender": [
"Men"
],
"images": [
"data:image/png;base64,C",
"data:image/png;base64,C"
],
"inventoryType": "test",
"name": "hello product",
"newLabel": {
"enabled": false,
"content": ""
},
"price": 99.99,
"priceSale": null,
"publish": "yes",
"quantity": 99,
"saleLabel": {
"enabled": false,
"content": ""
},
"sizes": [
"7"
],
"sku": "SK-122345",
"subDescription": "this is test sub-description",
"tags": [
"Travel",
"Finance"
],
"taxes": 0,
"totalRatings": 1,
"totalReviews": 1,
"totalSold": 1
}
}

View File

@@ -0,0 +1,22 @@
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { deleteProduct } from 'src/app/services/product.service';
/** **************************************
* PATCH - Delete product
*************************************** */
export async function PATCH(req: NextRequest) {
try {
const { productId } = await req.json();
if (!productId) throw new Error('productId cannot be null');
await deleteProduct(productId);
return response({ productId }, STATUS.OK);
} catch (error) {
return handleError('Product - Delete', error);
}
}

View File

@@ -1,5 +1,7 @@
// src/app/api/product/details/route.ts
//
// REQ0182 frontend product details
//
// PURPOSE:
// get product from db by id
//

View File

@@ -1,3 +1,5 @@
###
GET http://localhost:7272/api/product/details?productId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01
###
GET http://localhost:7272/api/product/details?productId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01

View File

@@ -1,23 +0,0 @@
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 - Products
*************************************** */
export async function GET() {
try {
const products = _products();
logger('[Product] list', products.length);
return response({ products }, STATUS.OK);
} catch (error) {
return handleError('Product - Get list', error);
}
}

View File

@@ -17,7 +17,7 @@ import prisma from '../../../lib/prisma';
/** **************************************
* GET - Products
*************************************** */
export async function POST(req: NextRequest) {
export async function PUT(req: NextRequest) {
// logger('[Product] list', products.length);
const { data } = await req.json();

View File

@@ -0,0 +1,51 @@
###
PUT http://localhost:7272/api/product/createProduct
Content-Type: application/json
{
"data": {
"available": 99,
"category": "T-shirts",
"code": "PD-12345",
"colors": [
"Red"
],
"coverUrl": "",
"description": "this is description, 会員管理機能は、単なるデータ管理ツール以上の価値を持ちます。 企業は顧客の情報や動向を深く理解し、長期的な顧客関係の構築やロイヤルティの確立、そして迅速な市場変動への対応に直結します。 会員管理機能は、現代のビジネスにおいて企業の競争力を高める基盤として欠かせないものとなっています。",
"gender": [
"Men"
],
"images": [
"data:image/png;base64,C",
"data:image/png;base64,C"
],
"inventoryType": "test",
"name": "hello product",
"newLabel": {
"enabled": false,
"content": ""
},
"price": 99.99,
"priceSale": null,
"publish": "yes",
"quantity": 99,
"saleLabel": {
"enabled": false,
"content": ""
},
"sizes": [
"7"
],
"sku": "SK-122345",
"subDescription": "this is test sub-description",
"tags": [
"Travel",
"Finance"
],
"taxes": 0,
"totalRatings": 1,
"totalReviews": 1,
"totalSold": 1
}
}

View File

@@ -0,0 +1,129 @@
// 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 PUT(req: NextRequest) {
// logger('[Product] list', products.length);
const { productData } = await req.json();
try {
const products = await prisma.productItem.updateMany({
data: {
name: productData.name,
sku: productData.sku,
code: productData.code,
price: productData.price,
taxes: productData.taxes,
tags: productData.tags,
sizes: productData.sizes,
publish: productData.publish,
gender: productData.gender,
coverUrl: productData.coverUrl,
images: productData.images,
colors: productData.colors,
quantity: productData.quantity,
category: productData.category,
available: productData.available,
totalSold: productData.totalSold,
description: productData.description,
totalRatings: productData.totalRatings,
totalReviews: productData.totalReviews,
inventoryType: productData.inventoryType,
subDescription: productData.subDescription,
priceSale: productData.priceSale,
//
newLabel: {
content: productData.newLabel?.content || '',
enabled: productData.newLabel?.enabled ?? false,
},
saleLabel: {
content: productData.saleLabel?.content || '',
enabled: productData.saleLabel?.enabled ?? false,
},
ratings: {
set: productData.ratings.map((rating: { name: string; starCount: number; reviewCount: number }) => ({
name: rating.name,
starCount: rating.starCount,
reviewCount: rating.reviewCount,
})),
},
},
where: { id: productData.id },
});
return response({ data: productData }, STATUS.OK);
} catch (error) {
console.log({ data: productData });
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,51 @@
###
PUT http://localhost:7272/api/product/createProduct
Content-Type: application/json
{
"data": {
"available": 99,
"category": "T-shirts",
"code": "PD-12345",
"colors": [
"Red"
],
"coverUrl": "",
"description": "this is description, 会員管理機能は、単なるデータ管理ツール以上の価値を持ちます。 企業は顧客の情報や動向を深く理解し、長期的な顧客関係の構築やロイヤルティの確立、そして迅速な市場変動への対応に直結します。 会員管理機能は、現代のビジネスにおいて企業の競争力を高める基盤として欠かせないものとなっています。",
"gender": [
"Men"
],
"images": [
"data:image/png;base64,C",
"data:image/png;base64,C"
],
"inventoryType": "test",
"name": "hello product",
"newLabel": {
"enabled": false,
"content": ""
},
"price": 99.99,
"priceSale": null,
"publish": "yes",
"quantity": 99,
"saleLabel": {
"enabled": false,
"content": ""
},
"sizes": [
"7"
],
"sku": "SK-122345",
"subDescription": "this is test sub-description",
"tags": [
"Travel",
"Finance"
],
"taxes": 0,
"totalRatings": 1,
"totalReviews": 1,
"totalSold": 1
}
}

View File

@@ -1,5 +1,7 @@
// src/app/services/product.service.ts
//
// REQ0182 frontend product details
//
// PURPOSE:
// - Service for handling ProductItem Record
//
@@ -65,11 +67,19 @@ type UpdateProduct = {
};
async function listProducts(): Promise<ProductItem[]> {
return prisma.productItem.findMany();
return prisma.productItem.findMany({
include: {
reviews: true,
},
});
}
async function getProduct(productId: string): Promise<ProductItem | null> {
return prisma.productItem.findUnique({ where: { id: productId } });
return prisma.productItem.findUnique({
where: { id: productId },
include: { reviews: true },
//
});
}
async function createProduct(createForm: CreateProduct) {

View File

@@ -1,7 +1,9 @@
const isDev = process.env.NODE_ENV === 'development';
const L_ERROR = 0;
const L_WARN = 1;
const L_INFO = 2;
const L_DEBUG = 3;
const L_TRACE = 4;
export { L_WARN, L_INFO, L_ERROR, L_DEBUG, L_TRACE };
export { L_WARN, L_INFO, L_ERROR, L_DEBUG, L_TRACE, isDev };

View File

@@ -1,14 +1,23 @@
#
# REQ0180 service port schedule
#
services:
frontend:
command: 'sleep infinity'
command: "sleep infinity"
ports:
- 8080:8080
mobile:
command: 'sleep infinity'
command: "sleep infinity"
ports:
- 8081:3000
cms_backend:
command: 'sleep infinity'
command: "sleep infinity"
ports:
- 7272:7272
- 5555:5555
postgres:
# container_name: postgres
ports:
- '5432:5432'
- 5432:5432

View File

@@ -1,3 +1,6 @@
#
# REQ0180 service port schedule
#
volumes:
db:
driver: local

View File

@@ -1,3 +1,8 @@
**/*del
**/*bak
**/*copy*
# Logs
logs
*.log

View File

@@ -92,6 +92,8 @@ const sortImportsRules = () => {
};
return {
'perfectionist/sort-named-imports': [1, { type: 'line-length', order: 'asc' }],
'perfectionist/sort-named-exports': [1, { type: 'line-length', order: 'asc' }],
'perfectionist/sort-exports': [
1,
{
@@ -100,8 +102,6 @@ const sortImportsRules = () => {
groupKind: 'values-first',
},
],
'perfectionist/sort-named-imports': [1, { type: 'line-length', order: 'asc' }],
'perfectionist/sort-named-exports': [1, { type: 'line-length', order: 'asc' }],
'perfectionist/sort-imports': [
2,
{

View File

@@ -21,7 +21,7 @@
"re:build": "yarn clean && yarn install && yarn build",
"re:build-npm": "npm run clean && npm install && npm run build",
"tsc:dev": "yarn dev & yarn tsc:watch",
"tsc:watch": "tsc --noEmit --watch",
"tsc:w": "tsc --noEmit --watch",
"tsc:print": "npx tsc --showConfig"
},
"engines": {
@@ -43,6 +43,7 @@
"@fontsource-variable/noto-sans-sc": "^5.2.5",
"@fontsource-variable/noto-sans-tc": "^5.2.5",
"@fontsource-variable/nunito-sans": "^5.2.5",
"@fontsource-variable/public-sans": "^5.2.5",
"@fontsource/barlow": "^5.2.5",
"@fullcalendar/core": "^6.1.15",
"@fullcalendar/daygrid": "^6.1.15",
@@ -52,7 +53,7 @@
"@fullcalendar/timegrid": "^6.1.15",
"@fullcalendar/timeline": "^6.1.15",
"@hookform/resolvers": "^4.1.3",
"@ianvs/prettier-plugin-sort-imports": "^4.4.1",
"@ianvs/prettier-plugin-sort-imports": "^4.4.2",
"@iconify/react": "^5.2.0",
"@mui/lab": "^7.0.0-beta.10",
"@mui/material": "^7.0.1",

View File

@@ -12,7 +12,7 @@ const config = {
trailingComma: 'es5',
plugins: [
//
// '@ianvs/prettier-plugin-sort-imports',
'@ianvs/prettier-plugin-sort-imports',
],
};

View File

@@ -2,6 +2,8 @@
yarn --dev
clear
while true; do
# yarn tsc:print
yarn lint:print

View File

@@ -1,10 +1,8 @@
import type { SWRConfiguration } from 'swr';
import type { IPostItem } from 'src/types/blog';
import useSWR from 'swr';
import { useMemo } from 'react';
import { fetcher, endpoints } from 'src/lib/axios';
import { endpoints, fetcher } from 'src/lib/axios';
import type { IPostItem } from 'src/types/blog';
import type { SWRConfiguration } from 'swr';
import useSWR from 'swr';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,9 @@
import type { SWRConfiguration } from 'swr';
import type { ICalendarEvent } from 'src/types/calendar';
import { useMemo } from 'react';
import axios, { endpoints, fetcher } from 'src/lib/axios';
import type { ICalendarEvent } from 'src/types/calendar';
import type { SWRConfiguration } from 'swr';
import useSWR, { mutate } from 'swr';
import axios, { fetcher, endpoints } from 'src/lib/axios';
// ----------------------------------------------------------------------
const enableServer = false;

View File

@@ -1,12 +1,10 @@
import type { SWRConfiguration } from 'swr';
import type { IChatMessage, IChatParticipant, IChatConversation } from 'src/types/chat';
import { useMemo } from 'react';
import { keyBy } from 'es-toolkit';
import { useMemo } from 'react';
import axios, { endpoints, fetcher } from 'src/lib/axios';
import type { IChatConversation, IChatMessage, IChatParticipant } from 'src/types/chat';
import type { SWRConfiguration } from 'swr';
import useSWR, { mutate } from 'swr';
import axios, { fetcher, endpoints } from 'src/lib/axios';
// ----------------------------------------------------------------------
const enableServer = false;

View File

@@ -1,11 +1,9 @@
import type { SWRConfiguration } from 'swr';
import type { UniqueIdentifier } from '@dnd-kit/core';
import type { IKanban, IKanbanTask, IKanbanColumn } from 'src/types/kanban';
import { startTransition, useMemo } from 'react';
import axios, { endpoints, fetcher } from 'src/lib/axios';
import type { IKanban, IKanbanColumn, IKanbanTask } from 'src/types/kanban';
import type { SWRConfiguration } from 'swr';
import useSWR, { mutate } from 'swr';
import { useMemo, startTransition } from 'react';
import axios, { fetcher, endpoints } from 'src/lib/axios';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,9 @@
import type { SWRConfiguration } from 'swr';
import type { IMail, IMailLabel } from 'src/types/mail';
import useSWR from 'swr';
import { useMemo } from 'react';
import { keyBy } from 'es-toolkit';
import { fetcher, endpoints } from 'src/lib/axios';
import { useMemo } from 'react';
import { endpoints, fetcher } from 'src/lib/axios';
import type { IMail, IMailLabel } from 'src/types/mail';
import type { SWRConfiguration } from 'swr';
import useSWR from 'swr';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,8 @@
// 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 { IProductItem } from 'src/types/product';
import type { SWRConfiguration } from 'swr';
import useSWR from 'swr';

View File

@@ -1,9 +1,11 @@
//
// src/actions/product.ts
//
import { useMemo } from 'react';
import axiosInstance, { endpoints, fetcher } from 'src/lib/axios';
import type { IProductItem } from 'src/types/product';
import type { SWRConfiguration } from 'swr';
import useSWR from 'swr';
import useSWR, { mutate } from 'swr';
// ----------------------------------------------------------------------
@@ -22,11 +24,7 @@ type ProductsData = {
export function useGetProducts() {
const url = endpoints.product.list;
const { data, isLoading, error, isValidating, mutate } = useSWR<ProductsData>(
url,
fetcher,
swrOptions
);
const { data, isLoading, error, isValidating } = useSWR<ProductsData>(url, fetcher, swrOptions);
const memoizedValue = useMemo(
() => ({
@@ -35,9 +33,8 @@ export function useGetProducts() {
productsError: error,
productsValidating: isValidating,
productsEmpty: !isLoading && !isValidating && !data?.products.length,
mutate,
}),
[data?.products, error, isLoading, isValidating, mutate]
[data?.products, error, isLoading, isValidating]
);
return memoizedValue;
@@ -56,10 +53,11 @@ export function useGetProduct(productId: string) {
const memoizedValue = useMemo(
() => ({
currentProduct: data?.product,
product: data?.product,
productLoading: isLoading,
productError: error,
productValidating: isValidating,
mutate,
}),
[data?.product, error, isLoading, isValidating]
);
@@ -97,140 +95,80 @@ export function useSearchProducts(query: string) {
// ----------------------------------------------------------------------
type SaveProductData = {
// id: string;
export async function createProduct(productData: IProductItem) {
/**
* Work on server
*/
const data = { productData };
await axiosInstance.post(endpoints.product.create, data);
sku: string;
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;
// }[];
};
/**
* Work in local
*/
mutate(
endpoints.product.list,
(currentData: any) => {
const currentProducts: IProductItem[] = currentData?.products;
export async function saveProduct(productId: string, saveProductData: SaveProductData) {
console.log('save product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
const products = [...currentProducts, productData];
const res = await axiosInstance.post('http://localhost:7272/api/product/saveProduct', {
data: saveProductData,
});
return res;
}
export async function uploadProductImage(saveProductData: SaveProductData) {
console.log('save product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
const res = await axiosInstance.get('http://localhost:7272/api/product/helloworld');
return res;
return { ...currentData, products };
},
false
);
}
// ----------------------------------------------------------------------
type CreateProductData = {
// id: string;
sku: string;
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;
// }[];
};
export async function updateProduct(productData: Partial<IProductItem>) {
/**
* Work on server
*/
const data = { productData };
await axiosInstance.put(endpoints.product.update, data);
export async function createProduct(createProductData: CreateProductData) {
console.log('create product ?');
// const url = productId ? [endpoints.product.details, { params: { productId } }] : '';
/**
* Work in local
*/
const res = await axiosInstance.post('http://localhost:7272/api/product/createProduct', {
data: createProductData,
});
mutate(
endpoints.product.list,
(currentData: any) => {
const currentProducts: IProductItem[] = currentData?.products;
return res;
const products = currentProducts.map((product) =>
product.id === productData.id ? { ...product, ...productData } : product
);
return { ...currentData, products };
},
false
);
}
// ----------------------------------------------------------------------
type DeleteProductResponse = {
success: boolean;
message?: string;
};
export async function deleteProduct(productId: string) {
/**
* Work on server
*/
const data = { productId };
await axiosInstance.patch(endpoints.product.delete, data);
export async function deleteProduct(productId: string): Promise<DeleteProductResponse> {
const url = `http://localhost:7272/api/product/deleteProduct?productId=${productId}`;
/**
* Work in local
*/
try {
const res = await axiosInstance.delete(url);
console.log({ res });
mutate(
endpoints.product.list,
(currentData: any) => {
console.log({ currentData });
const currentProducts: IProductItem[] = currentData?.products;
return {
success: true,
message: 'Product deleted successfully',
};
} catch (error) {
return {
success: false,
message: error instanceof Error ? error.message : 'Failed to delete product',
};
}
const products = currentProducts.filter((product) => product.id !== productId);
return { ...currentData, products };
},
false
);
}

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,8 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { CONFIG } from 'src/global-config';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,9 +1,6 @@
import type { SvgIconProps } from '@mui/material/SvgIcon';
import { memo } from 'react';
import SvgIcon from '@mui/material/SvgIcon';
import { memo } from 'react';
import { BackgroundShape } from './background-shape';
// ----------------------------------------------------------------------

View File

@@ -1,15 +1,21 @@
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import type { ConfirmDialogProps } from './types';
import DialogTitle from '@mui/material/DialogTitle';
import { useTranslation } from 'react-i18next';
import type { ConfirmDialogProps } from './types';
// ----------------------------------------------------------------------
export function ConfirmDialog({ open, title, action, content, onClose, ...other }: ConfirmDialogProps) {
export function ConfirmDialog({
open,
title,
action,
content,
onClose,
...other
}: ConfirmDialogProps) {
const { t } = useTranslation();
return (

View File

@@ -1,22 +1,22 @@
// src/components/hook-form/fields.tsx
//
import { RHFCode } from './rhf-code';
import { RHFRating } from './rhf-rating';
import { RHFEditor } from './rhf-editor';
import { RHFSlider } from './rhf-slider';
import { RHFUpload } from './rhf-upload';
import { RHFTextField } from './rhf-text-field';
import { RHFUploadBox } from './rhf-upload-box';
import { RHFRadioGroup } from './rhf-radio-group';
import { RHFPhoneInput } from './rhf-phone-input';
import { RHFNumberInput } from './rhf-number-input';
import { RHFAutocomplete } from './rhf-autocomplete';
import { RHFUploadAvatar } from './rhf-upload-avatar';
import { RHFCountrySelect } from './rhf-country-select';
import { RHFSwitch, RHFMultiSwitch } from './rhf-switch';
import { RHFSelect, RHFMultiSelect } from './rhf-select';
import { RHFCheckbox, RHFMultiCheckbox } from './rhf-checkbox';
import { RHFCode } from './rhf-code';
import { RHFCountrySelect } from './rhf-country-select';
import { RHFDatePicker, RHFMobileDateTimePicker } from './rhf-date-picker';
import { RHFEditor } from './rhf-editor';
import { RHFNumberInput } from './rhf-number-input';
import { RHFPhoneInput } from './rhf-phone-input';
import { RHFRadioGroup } from './rhf-radio-group';
import { RHFRating } from './rhf-rating';
import { RHFMultiSelect, RHFSelect } from './rhf-select';
import { RHFSlider } from './rhf-slider';
import { RHFMultiSwitch, RHFSwitch } from './rhf-switch';
import { RHFTextField } from './rhf-text-field';
import { RHFUpload } from './rhf-upload';
import { RHFUploadAvatar } from './rhf-upload-avatar';
import { RHFUploadBox } from './rhf-upload-box';
// ----------------------------------------------------------------------

View File

@@ -1,7 +1,9 @@
import type { BoxProps } from '@mui/material/Box';
import Box from '@mui/material/Box';
import { Controller, useFormContext } from 'react-hook-form';
import { Upload } from '../upload';
import { Upload, UploadAvatar, UploadBox } from '../upload';
import type { UploadProps } from '../upload';
import { HelperText } from './help-text';
// ----------------------------------------------------------------------
@@ -12,6 +14,48 @@ export type RHFUploadProps = UploadProps & {
};
};
export function RHFUploadAvatar({ name, slotProps, ...other }: RHFUploadProps) {
const { control, setValue } = useFormContext();
return (
<Controller
name={name}
control={control}
render={({ field, fieldState: { error } }) => {
const onDrop = (acceptedFiles: File[]) => {
const value = acceptedFiles[0];
setValue(name, value, { shouldValidate: true });
};
return (
<Box {...slotProps?.wrapper}>
<UploadAvatar value={field.value} error={!!error} onDrop={onDrop} {...other} />
<HelperText errorMessage={error?.message} sx={{ textAlign: 'center' }} />
</Box>
);
}}
/>
);
}
// ----------------------------------------------------------------------
export function RHFUploadBox({ name, ...other }: RHFUploadProps) {
const { control } = useFormContext();
return (
<Controller
name={name}
control={control}
render={({ field, fieldState: { error } }) => (
<UploadBox value={field.value} error={!!error} {...other} />
)}
/>
);
}
// ----------------------------------------------------------------------
export function RHFUpload({ name, multiple, helperText, ...other }: RHFUploadProps) {
@@ -35,8 +79,6 @@ export function RHFUpload({ name, multiple, helperText, ...other }: RHFUploadPro
setValue(name, value, { shouldValidate: true });
};
// return <>{JSON.stringify({ t: field.value })}</>;
return <Upload {...uploadProps} value={field.value} onDrop={onDrop} {...other} />;
}}
/>

View File

@@ -1,17 +1,13 @@
import { isEqualPath } from 'minimal-shared/utils';
import Link from '@mui/material/Link';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import { usePathname } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';
import { megaMenuClasses } from '../styles';
import { NavUl, NavLi } from './nav-elements';
import type { NavSubItemProps, NavSubListProps } from '../types';
import { isEqualPath } from 'minimal-shared/utils';
import { useTranslation } from 'react-i18next';
import { RouterLink } from 'src/routes/components';
import { usePathname } from 'src/routes/hooks';
import { megaMenuClasses } from '../styles';
import type { NavSubItemProps, NavSubListProps } from '../types';
import { NavLi, NavUl } from './nav-elements';
// ----------------------------------------------------------------------
@@ -24,7 +20,13 @@ export function NavSubList({ data, slotProps, ...other }: NavSubListProps) {
{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

@@ -1,20 +1,25 @@
import type { ListSubheaderProps } from '@mui/material/ListSubheader';
import { mergeClasses } from 'minimal-shared/utils';
import { styled } from '@mui/material/styles';
import ListSubheader from '@mui/material/ListSubheader';
import { navSectionClasses } from '../styles';
import { styled } from '@mui/material/styles';
import { mergeClasses } from 'minimal-shared/utils';
import { Iconify, iconifyClasses } from '../../iconify';
import { navSectionClasses } from '../styles';
// ----------------------------------------------------------------------
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

@@ -2,11 +2,11 @@ import Collapse from '@mui/material/Collapse';
import { useTheme } from '@mui/material/styles';
import { useBoolean } from 'minimal-shared/hooks';
import { mergeClasses } from 'minimal-shared/utils';
import { useTranslation } from 'react-i18next';
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';
// ----------------------------------------------------------------------
@@ -26,7 +26,11 @@ 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
@@ -46,7 +50,14 @@ 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();
@@ -70,9 +81,15 @@ function Group({ items, render, subheader, slotProps, checkPermissions, enabledR
<NavLi>
{subheader ? (
<>
<NavSubheader data-title={subheader} open={groupOpen.value} onClick={groupOpen.onToggle} sx={slotProps?.subheader}>
{t(subheader)}
<NavSubheader
data-title={subheader}
open={groupOpen.value}
onClick={groupOpen.onToggle}
sx={slotProps?.subheader}
>
{subheader}
</NavSubheader>
<Collapse in={groupOpen.value}>{renderContent()}</Collapse>
</>
) : (

View File

@@ -54,6 +54,10 @@ export const endpoints = {
list: '/api/product/list',
details: '/api/product/details',
search: '/api/product/search',
save: '/api/product/saveProduct',
create: '/api/product/create',
update: '/api/product/update',
delete: '/api/product/delete',
},
user: {
list: '/api/user/list',

View File

@@ -1,10 +1,8 @@
// src/pages/dashboard/product/details.tsx
import { useParams } from 'src/routes/hooks';
import { CONFIG } from 'src/global-config';
import { useGetProduct } from 'src/actions/product';
import { CONFIG } from 'src/global-config';
import { useParams } from 'src/routes/hooks';
import { ProductDetailsView } from 'src/sections/product/view';
// ----------------------------------------------------------------------
@@ -14,7 +12,7 @@ const metadata = { title: `Product details | Dashboard - ${CONFIG.appName}` };
export default function Page() {
const { id = '' } = useParams();
const { currentProduct: product, productLoading, productError } = useGetProduct(id);
const { product, productLoading, productError } = useGetProduct(id);
return (
<>

View File

@@ -1,8 +1,6 @@
import { useParams } from 'src/routes/hooks';
import { CONFIG } from 'src/global-config';
import { useGetProduct } from 'src/actions/product';
import { CONFIG } from 'src/global-config';
import { useParams } from 'src/routes/hooks';
import { ProductEditView } from 'src/sections/product/view';
// ----------------------------------------------------------------------
@@ -12,13 +10,13 @@ const metadata = { title: `Product edit | Dashboard - ${CONFIG.appName}` };
export default function Page() {
const { id = '' } = useParams();
const { currentProduct } = useGetProduct(id);
const { product } = useGetProduct(id);
return (
<>
<title>{metadata.title}</title>
<ProductEditView product={currentProduct} />
<ProductEditView product={product} />
</>
);
}

View File

@@ -1,5 +1,5 @@
// src/pages/dashboard/product/list.tsx
//
import { CONFIG } from 'src/global-config';
import { ProductListView } from 'src/sections/product/view';

View File

@@ -12,7 +12,7 @@ const metadata = { title: `Product details - ${CONFIG.appName}` };
export default function Page() {
const { id = '' } = useParams();
const { currentProduct: product, productLoading, productError } = useGetProduct(id);
const { product, productLoading, productError } = useGetProduct(id);
return (
<>

View File

@@ -0,0 +1,5 @@
function Helloworld() {
return <>helloworld</>;
}
export default Helloworld;

View File

@@ -1,6 +1,5 @@
import { CONFIG } from 'src/global-config';
import { useGetProducts } from 'src/actions/product';
import { CONFIG } from 'src/global-config';
import { ProductShopView } from 'src/sections/product/view';
// ----------------------------------------------------------------------

View File

@@ -1,21 +1,16 @@
import type { IProductItem } from 'src/types/product';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Card from '@mui/material/Card';
import Fab, { fabClasses } from '@mui/material/Fab';
import Link from '@mui/material/Link';
import Stack from '@mui/material/Stack';
import Tooltip from '@mui/material/Tooltip';
import Fab, { fabClasses } from '@mui/material/Fab';
import { RouterLink } from 'src/routes/components';
import { fCurrency } from 'src/utils/format-number';
import { Label } from 'src/components/label';
import { Image } from 'src/components/image';
import { Iconify } from 'src/components/iconify';
import { ColorPreview } from 'src/components/color-utils';
import { Iconify } from 'src/components/iconify';
import { Image } from 'src/components/image';
import { Label } from 'src/components/label';
import { RouterLink } from 'src/routes/components';
import type { IProductItem } from 'src/types/product';
import { fCurrency } from 'src/utils/format-number';
import { useCheckoutContext } from '../checkout/context';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,8 @@
import type { BoxProps } from '@mui/material/Box';
import type { IProductItem } from 'src/types/product';
import Box from '@mui/material/Box';
import Pagination, { paginationClasses } from '@mui/material/Pagination';
import { paths } from 'src/routes/paths';
import type { IProductItem } from 'src/types/product';
import { ProductItem } from './product-item';
import { ProductItemSkeleton } from './product-skeleton';

View File

@@ -21,7 +21,7 @@ import {
PRODUCT_COLOR_NAME_OPTIONS,
PRODUCT_SIZE_OPTIONS,
} from 'src/_mock';
import { createProduct, saveProduct } from 'src/actions/product';
import { createProduct, updateProduct } from 'src/actions/product';
import { Field, Form, schemaHelper } from 'src/components/hook-form';
import { Iconify } from 'src/components/iconify';
import { toast } from 'src/components/snackbar';
@@ -194,9 +194,6 @@ export function ProductNewEditForm({ currentProduct }: Props) {
};
try {
// await new Promise((resolve) => setTimeout(resolve, 500));
// reset();
// sanitize file field
for (let i = 0; i < values.images.length; i++) {
const temp: any = values.images[i];
@@ -205,12 +202,14 @@ export function ProductNewEditForm({ currentProduct }: Props) {
}
}
const sanitizedValues: IProductItem = values as unknown as IProductItem;
if (currentProduct) {
// perform save
await saveProduct(currentProduct.id, values);
updateProduct(sanitizedValues);
} else {
// perform create
await createProduct(values);
createProduct(sanitizedValues);
}
toast.success(currentProduct ? 'Update success!' : 'Create success!');

View File

@@ -1,18 +1,14 @@
// src/sections/product/product-table-row.tsx
import type { GridCellParams } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Avatar from '@mui/material/Avatar';
import ListItemText from '@mui/material/ListItemText';
import Box from '@mui/material/Box';
import LinearProgress from '@mui/material/LinearProgress';
import { RouterLink } from 'src/routes/components';
import { fCurrency } from 'src/utils/format-number';
import { fTime, fDate } from 'src/utils/format-time';
import Link from '@mui/material/Link';
import ListItemText from '@mui/material/ListItemText';
import type { GridCellParams } from '@mui/x-data-grid';
import { Label } from 'src/components/label';
import { RouterLink } from 'src/routes/components';
import { fCurrency } from 'src/utils/format-number';
import { fDate, fTime } from 'src/utils/format-time';
// ----------------------------------------------------------------------

View File

@@ -1,9 +1,6 @@
import { paths } from 'src/routes/paths';
import { DashboardContent } from 'src/layouts/dashboard';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { paths } from 'src/routes/paths';
import { ProductNewEditForm } from '../product-new-edit-form';
// ----------------------------------------------------------------------

View File

@@ -1,11 +1,7 @@
import type { IProductItem } from 'src/types/product';
import { paths } from 'src/routes/paths';
import { DashboardContent } from 'src/layouts/dashboard';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { paths } from 'src/routes/paths';
import type { IProductItem } from 'src/types/product';
import { ProductNewEditForm } from '../product-new-edit-form';
// ----------------------------------------------------------------------

View File

@@ -35,9 +35,11 @@ import { EmptyContent } from 'src/components/empty-content';
import { Iconify } from 'src/components/iconify';
import { toast } from 'src/components/snackbar';
import { DashboardContent } from 'src/layouts/dashboard';
import { endpoints } from 'src/lib/axios';
import { RouterLink } from 'src/routes/components';
import { paths } from 'src/routes/paths';
import type { IProductItem, IProductTableFilters } from 'src/types/product';
import { mutate } from 'swr';
import { ProductTableFiltersResult } from '../product-table-filters-result';
import {
RenderCellCreatedAt,
@@ -59,6 +61,8 @@ const HIDE_COLUMNS_TOGGLABLE = ['category', 'actions'];
export function ProductListView() {
const { t } = useTranslation();
const confirmDialog = useBoolean();
const PRODUCT_STOCK_OPTIONS = [
{ value: 'in stock', label: t('In stock') },
{ value: 'low stock', label: t('Low stock') },
@@ -75,7 +79,7 @@ export function ProductListView() {
const confirmDeleteSingleItemDialog = useBoolean();
const [idToDelete, setIdToDelete] = useState<string | null>(null);
const { products, productsLoading, mutate } = useGetProducts();
const { products, productsLoading } = useGetProducts();
const [tableData, setTableData] = useState<IProductItem[]>(products);
const [selectedRowIds, setSelectedRowIds] = useState<GridRowSelectionModel>([]);
@@ -113,13 +117,29 @@ export function ProductListView() {
toast.error('Delete failed!');
}
// TODO: reload table here
mutate();
// setTableData(deleteRow);
setDeleteInProgress(false);
}, [idToDelete, mutate]);
// NOTE: this is working using example from calendar
const handleDeleteRow = useCallback(
async (id: string) => {
try {
await deleteProduct(id);
// invalidate cache to reload list
await mutate(endpoints.product.list);
toast.success('Delete success!');
} catch (error) {
console.error(error);
toast.error('Delete error!');
}
},
[tableData]
);
const handleDeleteRows = useCallback(() => {
const deleteRows = tableData.filter((row) => !selectedRowIds.includes(row.id));

View File

@@ -1,33 +1,28 @@
import type { IProductItem } from 'src/types/product';
import type { Theme, SxProps } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import type { SxProps, Theme } from '@mui/material/styles';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Typography from '@mui/material/Typography';
import { useTabs } from 'minimal-shared/hooks';
import { varAlpha } from 'minimal-shared/utils';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import Tabs from '@mui/material/Tabs';
import Card from '@mui/material/Card';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import { paths } from 'src/routes/paths';
import { RouterLink } from 'src/routes/components';
import { Iconify } from 'src/components/iconify';
import { EmptyContent } from 'src/components/empty-content';
import { useTranslation } from 'react-i18next';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { CartIcon } from '../cart-icon';
import { EmptyContent } from 'src/components/empty-content';
import { Iconify } from 'src/components/iconify';
import { RouterLink } from 'src/routes/components';
import { paths } from 'src/routes/paths';
import type { IProductItem } from 'src/types/product';
import { useCheckoutContext } from '../../checkout/context';
import { ProductDetailsSkeleton } from '../product-skeleton';
import { ProductDetailsReview } from '../product-details-review';
import { ProductDetailsSummary } from '../product-details-summary';
import { CartIcon } from '../cart-icon';
import { ProductDetailsCarousel } from '../product-details-carousel';
import { ProductDetailsDescription } from '../product-details-description';
import { useTranslation } from 'react-i18next';
import { ProductDetailsReview } from '../product-details-review';
import { ProductDetailsSummary } from '../product-details-summary';
import { ProductDetailsSkeleton } from '../product-skeleton';
// ----------------------------------------------------------------------

View File

@@ -11,6 +11,7 @@ import TableCell from '@mui/material/TableCell';
import TableRow from '@mui/material/TableRow';
import Tooltip from '@mui/material/Tooltip';
import { useBoolean, usePopover } from 'minimal-shared/hooks';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ConfirmDialog } from 'src/components/custom-dialog';
import { CustomPopover } from 'src/components/custom-popover';
@@ -19,7 +20,6 @@ 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';
// ----------------------------------------------------------------------

View File

@@ -29,41 +29,32 @@ export type IProductReview = {
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;
createdAt: IDateValue;
//
available: number;
totalSold: number;
category: string;
code: string;
colors: string[];
coverUrl: string;
description: string;
gender: string[];
images: string[];
inventoryType: string;
name: string;
newLabel: { content: string; enabled: boolean };
price: number;
priceSale: number | null;
publish: string;
quantity: number;
ratings: { name: string; starCount: number; reviewCount: number }[];
reviews: IProductReview[];
saleLabel: { content: string; enabled: boolean };
sizes: string[];
sku: string;
subDescription: string;
tags: string[];
taxes: number;
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;
}[];
totalSold: number;
};

View File

@@ -1,29 +1,32 @@
{
"compilerOptions": {
"allowJs": true,
/* Bundler */
"baseUrl": ".",
"esModuleInterop": true,
"incremental": true,
"isolatedModules": true,
"module": "ESNext",
"jsx": "react-jsx",
"allowJs": true,
"resolveJsonModule": true,
/* Build */
"target": "ES2020",
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"moduleResolution": "bundler",
"noEmit": true,
"resolveJsonModule": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"incremental": true,
"skipLibCheck": true,
"esModuleInterop": true,
"isolatedModules": true,
/* Linting */
"strict": true,
"strictNullChecks": true,
/* Build */
"target": "ES2020",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
"noEmit": true,
"strictNullChecks": true
},
"include": [
"src"
],
"exclude": [
"node_modules",
".next",
@@ -39,12 +42,9 @@
"**/*.tmp",
"**/*del"
],
"include": [
"src"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
],
}

View File

@@ -16,8 +16,5 @@
"**/*.log",
"**/*.tmp",
"**/*del"
],
"include": [
"vite.config.ts"
]
], "include": ["vite.config.ts"]
}

View File

@@ -1604,6 +1604,11 @@
resolved "https://registry.npmjs.org/@fontsource-variable/nunito-sans/-/nunito-sans-5.2.5.tgz"
integrity sha512-J8Bi9OBUQvXwDvt9QofXD4joorYy3O9+4AU7cPx/ioa+xlH4HjAJNhA/N+nCu7IOMjFsbEbM2ZZCWQrsmQMsQw==
"@fontsource-variable/public-sans@^5.2.5":
version "5.2.6"
resolved "https://registry.yarnpkg.com/@fontsource-variable/public-sans/-/public-sans-5.2.6.tgz#bd000ef86cdcdb60abd42b71050dc32cab83f04d"
integrity sha512-NXUIBhVuxk0n0S5ZUQvEJNw6k2vtgh4GIHHGMNm1hPt2dyyl7ScsDoygzUi1Q/LD4+nj6mlb1qjITzNcBAo4dw==
"@fontsource/barlow@^5.2.5":
version "5.2.5"
resolved "https://registry.npmjs.org/@fontsource/barlow/-/barlow-5.2.5.tgz"
@@ -1716,10 +1721,10 @@
resolved "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.2.tgz"
integrity sha512-xeO57FpIu4p1Ri3Jq/EXq4ClRm86dVF2z/+kvFnyqVYRavTZmaFaUBbWCOuuTh0o/g7DSsk6kc2vrS4Vl5oPOQ==
"@ianvs/prettier-plugin-sort-imports@^4.4.1":
version "4.4.1"
resolved "https://registry.yarnpkg.com/@ianvs/prettier-plugin-sort-imports/-/prettier-plugin-sort-imports-4.4.1.tgz#d8a182fc1a74d687df335b2b17b347e232b6f495"
integrity sha512-F0/Hrcfpy8WuxlQyAWJTEren/uxKhYonOGY4OyWmwRdeTvkh9mMSCxowZLjNkhwi/2ipqCgtXwwOk7tW0mWXkA==
"@ianvs/prettier-plugin-sort-imports@^4.4.2":
version "4.4.2"
resolved "https://registry.yarnpkg.com/@ianvs/prettier-plugin-sort-imports/-/prettier-plugin-sort-imports-4.4.2.tgz#b4e0fa40249ffe5b80a3d65b294b1c49f0a7757e"
integrity sha512-KkVFy3TLh0OFzimbZglMmORi+vL/i2OFhEs5M07R9w0IwWAGpsNNyE4CY/2u0YoMF5bawKC2+8/fUH60nnNtjw==
dependencies:
"@babel/generator" "^7.26.2"
"@babel/parser" "^7.26.2"

View File

@@ -0,0 +1,2 @@
VITE_API_ENDPOINT=//localhost:7272
VITE_PROD_API_ENDPOINT=//www.example.com

View File

@@ -1,7 +1,10 @@
#!/usr/bin/env bash
npm i -D
clear
while true; do
npm i -D
npm run dev