Compare commits

...

77 Commits

Author SHA1 Message Date
louiscklaw
37ace98e60 feat: add party payment flow with dummy pay page implementation and route configuration 2025-06-18 02:32:09 +08:00
louiscklaw
44091e0432 feat: add party user gender field to schema and implement event joining functionality with gender tracking 2025-06-18 02:28:29 +08:00
louiscklaw
279496ea38 feat: remove AppRoute component and adjust related route configurations 2025-06-18 02:18:18 +08:00
louiscklaw
a450747670 feat: add new pages for event detail, member profile and order detail with corresponding route configurations 2025-06-18 01:20:27 +08:00
louiscklaw
215476cfaa feat: add party user metadata storage and display support, including storage API, Redux actions, state management, and UI updates for profile page 2025-06-18 01:14:37 +08:00
louiscklaw
c93b31b2f6 feat: implement party user authentication system with signin/signup routes, JWT token validation, and frontend integration including mobile route configuration and API service updates 2025-06-18 01:14:05 +08:00
louiscklaw
4cf93f431e feat: refine Account model schema with consistent formatting and add default rank field to PartyUser model 2025-06-18 00:23:12 +08:00
louiscklaw
2b09261f0a feat: implement login and signup pages with shared authentication styles, including form validation and Redux integration for authentication state management 2025-06-17 23:47:18 +08:00
louiscklaw
1325a361dc feat: update requirement REQ0188 dependencies, add frontend/party-user-auth/trunk to development paths 2025-06-17 22:11:45 +08:00
louiscklaw
a4d0d8b746 feat: clarify FAQ guidance on updating git staged files, adding reference to sibling files in same directory 2025-06-17 20:15:57 +08:00
louiscklaw
f8919b8c84 feat: update FAQ with guidance on updating git staged files, specifying to preserve format and detail level while avoiding unintended code changes 2025-06-17 20:12:39 +08:00
louiscklaw
583e31fd4d feat: refactor party event action types and functions, update imports and naming conventions to use PartyEvent naming scheme, add createPartyUser function to party-user actions 2025-06-17 20:06:47 +08:00
louiscklaw
ae7f005236 feat: enhance party user schema with address fields, update frontend form and API calls to use PartyUser naming convention 2025-06-17 19:59:09 +08:00
louiscklaw
834f9360ba feat: update import path for UserCreateView to use party-user view module 2025-06-17 19:58:56 +08:00
louiscklaw
1cb018d4d5 "feat: simplify db push script by removing restart loop and directly executing db:push and seed" 2025-06-17 19:58:45 +08:00
louiscklaw
448825545e "feat: refactor party user data fetching to use new endpoint URL builder and implement 2025-06-17 19:18:21 +08:00
louiscklaw
7c7a532381 fix: disable i18n debug mode in production 2025-06-17 19:18:13 +08:00
louiscklaw
eb515dbe68 feat: enhance party user schema with company, status, role and verification fields, update seeding and frontend form 2025-06-17 18:31:20 +08:00
louiscklaw
7a793be610 feat: update imports and component structure in party-user list view 2025-06-17 18:31:07 +08:00
louiscklaw
1d89134ea2 fix: remove unused tax calculation code in product form 2025-06-17 18:30:30 +08:00
louiscklaw
44d324b40e feat: update frontend references from User to PartyUser for party user management module 2025-06-16 10:20:09 +08:00
louiscklaw
ee2a377bf6 feat: add frontend environment variables template with server URL, API keys and service configurations 2025-06-16 10:20:01 +08:00
louiscklaw
0941ab6dd1 feat: update frontend component names from User to PartyUser for consistency with party-user module 2025-06-16 10:08:43 +08:00
louiscklaw
e93c5dcf62 in the middle of party-user frontend, 2025-06-16 03:03:54 +08:00
louiscklaw
17aaf97722 feat: add REQ0188 frontend party-user CRUD functionality with backend API endpoints and database schema 2025-06-16 02:26:41 +08:00
louiscklaw
47660be0cd docs: update FAQ with question about introducing new format or ideas 2025-06-16 02:24:47 +08:00
louiscklaw
cf5cfb8d63 "feat: add mobile app support with Dockerfile and dev/build scripts, update all projects to use psmisc for process management" 2025-06-16 01:46:15 +08:00
louiscklaw
a686dd55dd feat: update REQ0187 requirements with TODO items for nav bar cleanup and status change implementation 2025-06-16 00:36:37 +08:00
louiscklaw
8d52be9b96 "fix: update party order details route variable naming and test case ID" 2025-06-16 00:35:17 +08:00
louiscklaw
db16b2d5dd party-order delete ok, 2025-06-16 00:07:22 +08:00
louiscklaw
7370316ea0 party-order list ok, 2025-06-16 00:01:36 +08:00
louiscklaw
77f7211317 feat: add REQ0189 frontend party-order list and details pages with mock data and API integration 2025-06-15 23:08:14 +08:00
louiscklaw
dfc9873815 feat: add REQ0187 frontend party-order CRUD functionality and backend API endpoints 2025-06-15 22:27:44 +08:00
louiscklaw
53b112e488 "docs: update FAQ with questions about modifying .tsx.draft files and replacement starting point" 2025-06-15 22:27:06 +08:00
louiscklaw
a9dd265658 update REQ0185 content, 2025-06-15 21:07:07 +08:00
louiscklaw
ae39b7ca67 refactor: rename product to partyEvent in frontend components and views 2025-06-15 18:06:17 +08:00
louiscklaw
4c2a06585d refactor: rename product to partyEvent in list page and view component 2025-06-15 17:53:47 +08:00
louiscklaw
816d88c2c1 refactor: rename eventId to partyEventId in delete API route and test case 2025-06-15 17:08:36 +08:00
louiscklaw
843e459527 "chore: add db:push and seed commands to dev script startup sequence" 2025-06-15 17:08:17 +08:00
louiscklaw
cd0ae5ba62 "chore: increase seed event items count from 2 to 5" 2025-06-15 17:07:56 +08:00
louiscklaw
ecdbc45c4a refactor: rename product to partyEvent in API route, types and frontend components 2025-06-15 16:44:27 +08:00
louiscklaw
4b64778b59 refactor: rename product to party-event across frontend modules and types 2025-06-15 16:33:50 +08:00
louiscklaw
a88de2f17f "add PartyEvent frontend module with mock data, API actions, UI components and routing configuration" 2025-06-15 16:13:09 +08:00
louiscklaw
d987b0fe36 "update AI workspace instructions and move setup steps to init_AI.md" 2025-06-15 16:13:02 +08:00
louiscklaw
0142c9ba24 update frontend requirement REQ0185 from product update to party-event and create new REQ0186 with product update content 2025-06-15 16:12:33 +08:00
louiscklaw
48e1f821ad "adjust nodemon delay timing for TypeScript watch scripts across all projects" 2025-06-15 16:12:02 +08:00
louiscklaw
9943283eff "add PartyEvent API endpoints with service layer and test cases" 2025-06-15 15:01:18 +08:00
louiscklaw
9ac13787aa "update FAQ with prisma schema file path clarification" 2025-06-15 13:55:13 +08:00
louiscklaw
c1b71fca64 add helloworld API endpoint for product module with test case 2025-06-15 13:54:35 +08:00
louiscklaw
08642a2bf6 "update EventItem model schema with reordered and reorganized fields" 2025-06-15 13:54:24 +08:00
louiscklaw
043d45862c update markdown files and instructions in AI workspace 2025-06-15 13:16:53 +08:00
louiscklaw
8444b947a4 "update product list rendering" 2025-06-15 13:07:47 +08:00
louiscklaw
e791b01160 update, 2025-06-15 12:56:29 +08:00
louiscklaw
8383be13bc update, 2025-06-15 12:44:58 +08:00
louiscklaw
d82afe5a5f update prisma search products, 2025-06-15 12:42:08 +08:00
louiscklaw
1216bef8f8 "update tsconfig patterns and compiler options across all projects" 2025-06-15 12:08:17 +08:00
louiscklaw
02058981bf update gitignore patterns, fix build scripts, update product API test files 2025-06-15 11:49:03 +08:00
louiscklaw
b7cd25b614 build ok, 2025-06-15 11:28:24 +08:00
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
1375 changed files with 18552 additions and 7841 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,18 @@
---
tags: frontend, party-event
---
# REQ0185 frontend party-event
frontend page to handle party-event (CRUD)
edit page T.B.A.
## sources
T.B.A.
## branch
develop/frontend/party-event/trunk
develop/requirements/REQ0185

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

@@ -0,0 +1,23 @@
---
tags: frontend, party-order
---
# REQ0185 frontend party-order
frontend page to handle party-order (CRUD)
edit page T.B.A.
## TODO
- remove detail in left nav bar
- implement `changeStatus`
## sources
T.B.A.
## branch
develop/frontend/party-order/trunk
develop/requirements/REQ0187

View File

@@ -0,0 +1,21 @@
---
tags: frontend, party-user
---
# REQ0188 frontend party-user
frontend page to handle party-user (CRUD)
edit page T.B.A.
## TODO
## sources
T.B.A.
## branch
develop/requirements/REQ0188
develop/frontend/party-user/trunk
develop/frontend/party-user-auth/trunk

View File

@@ -0,0 +1,20 @@
---
tags: mobile, payment
---
# REQ0189 party payment flow
frontend page to handle party-user pay join event
edit page T.B.A.
## TODO
## sources
T.B.A.
## branch
develop/requirements/REQ0189
develop/mobile/DummyPayPage/trunk

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

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

View File

@@ -6,6 +6,7 @@ RUN npm install -g pnpm
RUN apt-get update -y
RUN apt-get install -y openssl
RUN apt-get install -qqy psmisc
# Set working directory
WORKDIR /app

View File

@@ -5,6 +5,7 @@
"description": "Mock server & assets",
"private": true,
"scripts": {
"dev:check": "yarn tsc:w",
"dev": "next dev -p 7272 -H 0.0.0.0",
"start": "next start -p 7272 -H 0.0.0.0",
"build": "next build",
@@ -19,8 +20,10 @@
"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:print": "npx tsc --showConfig",
"tsc:w": "npx nodemon --delay 1 --ext ts,tsx --exec \"yarn tsc\"",
"tsc:watch": "tsc --noEmit --watch",
"tsc": "tsc --noEmit",
"migrate": "npx prisma migrate dev --skip-seed",
"seed": "tsx ./prisma/seed.ts",
"seed:w": "npx nodemon --ext \"ts,tsx,json\" -w prisma --exec \"yarn seed\"",
@@ -29,7 +32,9 @@
"db:push": "prisma db push --force-reset",
"db:push:w": "npx nodemon --delay 1 --watch prisma --ext \"ts,tsx,prisma\" --exec \"yarn db:push && yarn seed\"",
"db:studio": "prisma studio",
"db:studio:w": "npx nodemon --delay 1 --watch prisma --ext \"prisma\" --exec \"yarn db:studio\""
"db:studio:w": "npx nodemon --delay 1 --watch prisma --ext \"prisma\" --exec \"yarn db:studio\"",
"db:dev": "yarn db:push && yarn seed && yarn dev",
"db:dev:w": "npx nodemon --delay 3 --ext \"ts,tsx,prisma\" --exec \"yarn db:dev\""
},
"engines": {
"node": ">=20"
@@ -66,6 +71,7 @@
"@types/react": "^18.3.20",
"@types/react-dom": "^18.3.5",
"@typescript-eslint/parser": "^8.28.0",
"concurrently": "^9.1.2",
"eslint": "^9.23.0",
"eslint-import-resolver-typescript": "^4.2.2",
"eslint-plugin-import": "^2.31.0",

View File

@@ -16,11 +16,11 @@ model Helloworld {
}
model Account {
id String @id @default(cuid())
userId String @map("user_id")
id String @id @default(cuid())
userId String @map("user_id")
type String
provider String
providerAccountId String @map("provider_account_id")
providerAccountId String @map("provider_account_id")
refresh_token String?
access_token String?
expires_at Int?
@@ -30,18 +30,21 @@ model Account {
session_state String?
oauth_token_secret String?
oauth_token String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
PartyUser PartyUser? @relation(fields: [partyUserId], references: [id])
partyUserId String?
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique @map("session_token")
userId String @map("user_id")
id String @id @default(cuid())
sessionToken String @unique @map("session_token")
userId String @map("user_id")
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
PartyUser PartyUser? @relation(fields: [partyUserId], references: [id])
partyUserId String?
}
model User {
@@ -195,32 +198,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 {
@@ -1146,48 +1149,60 @@ model EventReview {
// NOTE: need to consider with Event
// mapped to IEventItem
// a.k.a. PartyEvent party-event
model EventItem {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(uuid())
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
description String
totalRatings Float
totalReviews Int
inventoryType String
subDescription String
priceSale Float?
newLabel Json
saleLabel Json
ratings Json[]
available Int @default(99)
category String
code String @default("")
colors String[]
coverUrl String
description String
gender String[]
images String[]
inventoryType String @default("")
name String @default("")
newLabel Json @default("{}")
price Float @default(999.9)
priceSale Float? @default(111.1)
publish String @default("")
quantity Int @default(99)
ratings Json[]
saleLabel Json @default("{}")
sizes String[] @default([""])
sku String @default("")
subDescription String @default("")
tags String[] @default([""])
taxes Float @default(5.0)
totalRatings Float @default(5.0)
totalReviews Int @default(10)
totalSold Int @default(10)
//
eventDate DateTime @default(now())
joinMembers Json[]
title String
currency String
duration_m Float
ageBottom Float
ageTop Float
location String
avatar String[]
ageBottom Float @default(-1)
ageTop Float @default(-1)
avatar String[] @default([""])
currency String @default("HKD")
capacity Int @default(10)
duration_m Float @default(180)
endDate String? @default("")
eventDate DateTime @default(now())
isFeatured Boolean @default(false)
joinMembers Json[] @default([])
location String @default("HK")
organizer String @default("")
registrationDeadline String @default("")
requirements String @default("")
schedule String @default("")
speakers String[] @default([])
sponsors String[] @default([])
startDate String? @default("")
status String? @default("")
title String @default("")
//
reviews EventReview[]
reviews EventReview[]
}
model AppLog {
@@ -1218,3 +1233,63 @@ model AccessLog {
@@index([timestamp])
@@index([userId])
}
model PartyOrderItem {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
taxes Float
status String
shipping Float
discount Float
subtotal Float
orderNumber String
totalAmount Float
totalQuantity Float
history Json
payment Json
customer Json
delivery Json
items Json[]
shippingAddress Json
// OrderProductItem OrderProductItem[]
// OrderHistory OrderHistory[]
// OrderDelivery OrderDelivery[]
// OrderCustomer OrderCustomer[]
// OrderPayment OrderPayment[]
// OrderShippingAddress OrderShippingAddress[]
}
model PartyUser {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
//
username String? @unique
password String?
//
name String?
email String @unique
emailVerified DateTime?
avatarUrl String?
bucketImage String?
admin Boolean @default(false)
accounts Account[]
sessions Session[]
info Json?
phoneNumber String @default("")
company String @default("")
status String @default("pending")
role String @default("")
isVerified Boolean @default(false)
//
country String @default("")
state String @default("")
city String @default("")
address String @default("")
zipCode String @default("")
//
rank String @default("user")
sex String @default("")
}

View File

@@ -31,6 +31,9 @@ import { EventReviewSeed } from './seeds/eventReview';
import { appLogSeed } from './seeds/AppLog';
import { accessLogSeed } from './seeds/AccessLog';
import { userMetaSeed } from './seeds/userMeta';
//
import { partyOrderItemSeed } from './seeds/partyOrderItem';
import { partyUserSeed } from './seeds/partyUser';
//
// import { Blog } from './seeds/blog';
@@ -59,6 +62,9 @@ import { userMetaSeed } from './seeds/userMeta';
//
await appLogSeed;
await accessLogSeed;
//
await partyOrderItemSeed;
await partyUserSeed;
// await Blog;
// await Mail;

View File

@@ -125,7 +125,7 @@ const generateRatings = () =>
const generateImages = () => Array.from({ length: 8 }, (_, index) => _mock.image.event(index));
const _events = () =>
Array.from({ length: 2 }, (_, index) => {
Array.from({ length: 5 }, (_, index) => {
const reviews = generateReviews();
const images = generateImages();
const ratings = generateRatings();

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 partyOrderItem() {
await prisma.partyOrderItem.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.partyOrderItem.upsert({
where: { id: index.toString() },
update: {},
create: {
id: _mock.id(index),
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 partyOrderItemSeed done');
}
const partyOrderItemSeed = partyOrderItem()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
export { partyOrderItemSeed };

View File

@@ -0,0 +1,135 @@
/**
* Party User seed data generator
* Creates initial user accounts for development and testing
* Includes:
* - Fixed demo accounts (alice, demo)
* - Randomly generated test accounts with CJK locale data
*/
import { faker as enFaker } from '@faker-js/faker/locale/en_US';
import { faker as zhFaker } from '@faker-js/faker/locale/zh_CN';
import { faker as jaFaker } from '@faker-js/faker/locale/ja';
import { faker as koFaker } from '@faker-js/faker/locale/ko';
import { faker as twFaker } from '@faker-js/faker/locale/zh_TW';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
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'];
async function partyUser() {
const alice = await prisma.partyUser.upsert({
where: { email: 'alice@prisma.io' },
update: {},
create: {
email: 'alice@prisma.io',
name: 'Alice',
username: 'pualice',
password: 'Aa12345678',
emailVerified: new Date(),
phoneNumber: '+85291234567',
company: 'helloworld company',
status: STATUS[0],
role: ROLE[0],
isVerified: true,
sex: 'F',
},
});
await prisma.partyUser.upsert({
where: { email: 'demo@minimals.cc' },
update: {},
create: {
email: 'demo@minimals.cc',
password: '@2Minimal',
//
username: 'pudemo',
name: 'Demo',
emailVerified: new Date(),
phoneNumber: '+85291234568',
company: 'helloworld company',
status: STATUS[1],
role: ROLE[1],
isVerified: true,
avatarUrl: 'https://images.unsplash.com/photo-1619970096024-c7b438a3b82a',
rank: 'user',
sex: 'M',
},
});
for (let i = 0; i < 5; i++) {
const CJK_LOCALES = {
en: enFaker,
zh: zhFaker,
ja: jaFaker,
ko: koFaker,
tw: twFaker,
};
function getRandomCJKFaker() {
const locales = Object.keys(CJK_LOCALES);
const randomKey = locales[Math.floor(Math.random() * locales.length)] as keyof typeof CJK_LOCALES;
return CJK_LOCALES[randomKey];
}
const randomFaker = getRandomCJKFaker();
await prisma.partyUser.upsert({
where: { email: `party_user${i}@prisma.io` },
update: {},
create: {
email: `party_user${i}@prisma.io`,
name: `Party Dummy ${i}`,
username: `pu${i.toString()}`,
password: 'Aa12345678',
emailVerified: new Date(),
phoneNumber: `+8529123456${i.toString()}`,
company: randomFaker.company.name(),
role: ROLE[Math.floor(Math.random() * ROLE.length)],
status: STATUS[Math.floor(Math.random() * STATUS.length)],
isVerified: true,
sex: i % 2 ? 'F' : 'M',
},
});
}
console.log('seed partyUser done');
}
const partyUserSeed = partyUser()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
export { partyUserSeed };

View File

@@ -1,8 +1,18 @@
#!/usr/bin/env bash
yarn --dev
clear
while true; do
yarn --dev
yarn dev
yarn db:studio &
npx nodemon --ext ts,tsx,prisma --exec "yarn dev"
# npx nodemon --ext ts,tsx,prisma --exec "yarn db:push && yarn seed && yarn dev"
# yarn dev
killall node
killall yarn
echo "restarting..."
sleep 1

View File

@@ -0,0 +1,9 @@
#!/usr/bin/env bash
yarn --dev
clear
yarn db:push && yarn seed
echo "done"

View File

@@ -2,11 +2,19 @@
set -x
yarn db:push
killall node
killall yarn
rm -rf ./**/*Zone.Identifier
npx nodemon --ext ts,tsx --exec "yarn tsc"
# yarn db:push
# npx nodemon --ext ts,tsx --exec "yarn tsc"
set -ex
yarn fm:fix
# yarn build
yarn tsc
yarn build
echo "done"

View File

@@ -16,11 +16,7 @@ export const _contacts = () =>
address: _mock.fullAddress(index),
avatarUrl: _mock.image.avatar(index),
phoneNumber: _mock.phoneNumber(index),
status:
([0, 1, 6, 12].includes(index) && 'online') ||
([3, 8, 14].includes(index) && 'offline') ||
([4, 10, 16].includes(index) && 'busy') ||
'always',
status: ([0, 1, 6, 12].includes(index) && 'online') || ([3, 8, 14].includes(index) && 'offline') || ([4, 10, 16].includes(index) && 'busy') || 'always',
}));
export const _conversations = () => {

View File

@@ -6,8 +6,7 @@ import { _tags } from './assets';
// ----------------------------------------------------------------------
const generateAttachments = () =>
Array.from({ length: 20 }, (_, index) => _mock.image.cover(index));
const generateAttachments = () => Array.from({ length: 20 }, (_, index) => _mock.image.cover(index));
const generateAssignees = () =>
Array.from({ length: 20 }, (_, index) => ({
@@ -68,24 +67,14 @@ const createTask = (index: number, status: string) => {
assignee: assignedUser.slice(0, index),
description: _mock.description(index),
due: [fAdd({ days: index + 1 }), fAdd({ days: index + 2 })],
priority:
([1, 3].includes(index) && PRIORITY_LEVEL.hight) ||
([2, 4].includes(index) && PRIORITY_LEVEL.medium) ||
PRIORITY_LEVEL.low,
attachments:
(index === 1 && attachmentList.slice(11, 15)) ||
(index === 5 && attachmentList.slice(4, 9)) ||
[],
priority: ([1, 3].includes(index) && PRIORITY_LEVEL.hight) || ([2, 4].includes(index) && PRIORITY_LEVEL.medium) || PRIORITY_LEVEL.low,
attachments: (index === 1 && attachmentList.slice(11, 15)) || (index === 5 && attachmentList.slice(4, 9)) || [],
status,
};
};
const tasks = () => ({
[COLUMN_IDS.id1]: [
createTask(1, COLUMN_NAMES.name1),
createTask(2, COLUMN_NAMES.name1),
createTask(3, COLUMN_NAMES.name1),
],
[COLUMN_IDS.id1]: [createTask(1, COLUMN_NAMES.name1), createTask(2, COLUMN_NAMES.name1), createTask(3, COLUMN_NAMES.name1)],
[COLUMN_IDS.id2]: [createTask(4, COLUMN_NAMES.name2), createTask(5, COLUMN_NAMES.name2)],
[COLUMN_IDS.id3]: [],
[COLUMN_IDS.id4]: [createTask(6, COLUMN_NAMES.name4)],

View File

@@ -28,20 +28,11 @@ export const _mails = () =>
Array.from({ length: 9 }, (_, index) => {
const files = _files();
const attachments =
(index === 1 && files.slice(0, 2)) ||
(index === 2 && files.slice(0, 4)) ||
(index === 5 && files.slice(4, 10)) ||
[];
const attachments = (index === 1 && files.slice(0, 2)) || (index === 2 && files.slice(0, 4)) || (index === 5 && files.slice(4, 10)) || [];
const folder =
([1, 2].includes(index) && 'spam') || ([3, 4].includes(index) && 'sent') || 'inbox';
const folder = ([1, 2].includes(index) && 'spam') || ([3, 4].includes(index) && 'sent') || 'inbox';
const labelIds =
(index === 1 && ['promotions', 'forums']) ||
(index === 2 && ['forums']) ||
(index === 5 && ['social']) ||
[];
const labelIds = (index === 1 && ['promotions', 'forums']) || (index === 2 && ['forums']) || (index === 5 && ['social']) || [];
const from = {
name: _mock.fullName(index),

View File

@@ -78,11 +78,8 @@ export const _mock = {
avatar: (index: number) => `${CONFIG.basePath}/assets/images/avatar/avatar-${index + 1}.webp`,
travel: (index: number) => `${CONFIG.basePath}/assets/images/travel/travel-${index + 1}.webp`,
course: (index: number) => `${CONFIG.basePath}/assets/images/course/course-${index + 1}.webp`,
company: (index: number) =>
`${CONFIG.basePath}/assets/images/company/company-${index + 1}.webp`,
product: (index: number) =>
`${CONFIG.basePath}/assets/images/m-product/product-${index + 1}.webp`,
portrait: (index: number) =>
`${CONFIG.basePath}/assets/images/portrait/portrait-${index + 1}.webp`,
company: (index: number) => `${CONFIG.basePath}/assets/images/company/company-${index + 1}.webp`,
product: (index: number) => `${CONFIG.basePath}/assets/images/m-product/product-${index + 1}.webp`,
portrait: (index: number) => `${CONFIG.basePath}/assets/images/portrait/portrait-${index + 1}.webp`,
},
};

View File

@@ -3,16 +3,7 @@ import { _tags } from './assets';
// ----------------------------------------------------------------------
const COLORS = [
'#FF4842',
'#1890FF',
'#FFC0CB',
'#00AB55',
'#FFC107',
'#7F00FF',
'#000000',
'#FFFFFF',
];
const COLORS = ['#FF4842', '#1890FF', '#FFC0CB', '#00AB55', '#FFC107', '#7F00FF', '#000000', '#FFFFFF'];
const DESCRIPTION = `
<h6>Specifications</h6>
@@ -93,8 +84,7 @@ const DESCRIPTION = `
`;
const generateAttachments = () =>
Array.from({ length: 20 }, (_, index) => _mock.image.product(index));
const generateAttachments = () => Array.from({ length: 20 }, (_, index) => _mock.image.product(index));
const generateReviews = () => {
const attachments = generateAttachments();
@@ -108,11 +98,7 @@ const generateReviews = () => {
rating: _mock.number.rating(index),
avatarUrl: _mock.image.avatar(index),
helpful: _mock.number.nativeL(index),
attachments:
(index === 1 && attachments.slice(0, 1)) ||
(index === 3 && attachments.slice(2, 4)) ||
(index === 5 && attachments.slice(5, 8)) ||
[],
attachments: (index === 1 && attachments.slice(0, 1)) || (index === 3 && attachments.slice(2, 4)) || (index === 5 && attachments.slice(5, 8)) || [],
}));
};
@@ -192,7 +178,6 @@ export const _products = () =>
newLabel: { enabled: [1, 2, 3].includes(index), content: 'NEW' },
saleLabel: { enabled: [4, 5].includes(index), content: 'SALE' },
sizes: ['6', '7', '8', '8.5', '9', '9.5', '10', '10.5', '11', '11.5', '12', '13'],
subDescription:
'Featuring the original ripple design inspired by Japanese bullet trains, the Nike Air Max 97 lets you push your style full-speed ahead.',
subDescription: 'Featuring the original ripple design inspired by Japanese bullet trains, the Nike Air Max 97 lets you push your style full-speed ahead.',
};
});

View File

@@ -1,9 +1,6 @@
// ----------------------------------------------------------------------
export const _id = Array.from(
{ length: 40 },
(_, index) => `e99f09a7-dd88-49d5-b1c8-1daf80c2d7b${index + 1}`
);
export const _id = Array.from({ length: 40 }, (_, index) => `e99f09a7-dd88-49d5-b1c8-1daf80c2d7b${index + 1}`);
// ----------------------------------------------------------------------
@@ -37,36 +34,24 @@ export const _booleans = [
// ----------------------------------------------------------------------
export const _prices = [
83.74, 97.14, 68.71, 85.21, 52.17, 25.18, 43.84, 60.98, 98.42, 53.37, 72.75, 56.61, 64.55, 77.32,
60.62, 79.81, 93.68, 47.44, 76.24, 92.87, 72.91, 20.54, 94.25, 37.51,
83.74, 97.14, 68.71, 85.21, 52.17, 25.18, 43.84, 60.98, 98.42, 53.37, 72.75, 56.61, 64.55, 77.32, 60.62, 79.81, 93.68, 47.44, 76.24, 92.87, 72.91, 20.54,
94.25, 37.51,
];
export const _ratings = [
4.2, 3.7, 4.5, 3.5, 0.5, 3.0, 2.5, 2.8, 4.9, 3.6, 2.5, 1.7, 3.9, 2.8, 4.1, 4.5, 2.2, 3.2, 0.6,
1.3, 3.8, 3.8, 3.8, 2.0,
];
export const _ratings = [4.2, 3.7, 4.5, 3.5, 0.5, 3.0, 2.5, 2.8, 4.9, 3.6, 2.5, 1.7, 3.9, 2.8, 4.1, 4.5, 2.2, 3.2, 0.6, 1.3, 3.8, 3.8, 3.8, 2.0];
export const _ages = [
30, 26, 59, 47, 29, 46, 18, 56, 39, 19, 45, 18, 46, 56, 38, 41, 44, 48, 32, 45, 42, 60, 33, 57,
];
export const _ages = [30, 26, 59, 47, 29, 46, 18, 56, 39, 19, 45, 18, 46, 56, 38, 41, 44, 48, 32, 45, 42, 60, 33, 57];
export const _percents = [
10.1, 13.6, 28.2, 42.1, 37.2, 18.5, 40.1, 94.8, 91.4, 53.0, 25.4, 62.9, 86.6, 62.4, 35.4, 17.6,
52.0, 6.8, 95.3, 26.6, 69.9, 92.1, 46.2, 85.6,
10.1, 13.6, 28.2, 42.1, 37.2, 18.5, 40.1, 94.8, 91.4, 53.0, 25.4, 62.9, 86.6, 62.4, 35.4, 17.6, 52.0, 6.8, 95.3, 26.6, 69.9, 92.1, 46.2, 85.6,
];
export const _nativeS = [
11, 10, 7, 10, 12, 5, 10, 1, 8, 8, 10, 11, 12, 8, 4, 11, 8, 9, 4, 9, 2, 6, 3, 7,
];
export const _nativeS = [11, 10, 7, 10, 12, 5, 10, 1, 8, 8, 10, 11, 12, 8, 4, 11, 8, 9, 4, 9, 2, 6, 3, 7];
export const _nativeM = [
497, 763, 684, 451, 433, 463, 951, 194, 425, 435, 807, 521, 538, 839, 394, 269, 453, 821, 364,
849, 804, 776, 263, 239,
];
export const _nativeM = [497, 763, 684, 451, 433, 463, 951, 194, 425, 435, 807, 521, 538, 839, 394, 269, 453, 821, 364, 849, 804, 776, 263, 239];
export const _nativeL = [
9911, 1947, 9124, 6984, 8488, 2034, 3364, 8401, 8996, 5271, 8478, 1139, 8061, 3035, 6733, 3952,
2405, 3127, 6843, 4672, 6995, 6053, 5192, 9686,
9911, 1947, 9124, 6984, 8488, 2034, 3364, 8401, 8996, 5271, 8478, 1139, 8061, 3035, 6733, 3952, 2405, 3127, 6843, 4672, 6995, 6053, 5192, 9686,
];
export const _fullAddress = [

View File

@@ -11,7 +11,7 @@ import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
// import { AccessLogService } from '../../../../modules/AccessLog/AccessLog.service';
import { getAccessLogById } from 'src/app/services/AccessLog.service';
import { getAccessLogById } from 'src/app/services/access-log.service';
// ----------------------------------------------------------------------

View File

@@ -2,7 +2,7 @@ import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { listAccessLogs } from 'src/app/services/AccessLog.service';
import { listAccessLogs } from 'src/app/services/access-log.service';
// import prisma from '../../lib/prisma';

View File

@@ -2,7 +2,7 @@ import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { listAppLogs, deleteAppLog, createNewAppLog } from 'src/app/services/AppLog.service';
import { listAppLogs, deleteAppLog, createNewAppLog } from 'src/app/services/app-log.service';
// import prisma from '../../lib/prisma';

View File

@@ -0,0 +1,14 @@
Hi,
i copied from
`03_source/cms_backend/src/app/api/party-event`
to
`03_source/cms_backend/src/app/api/party-order`
with knowledge in `schema.prisma` file, and take a look into the sibling files in the same directory.
i want you to update `03_source/cms_backend/src/app/api/party-order` content to handle `party-order` (the purchase order of the party)
`party-order.service.ts` is already prepared and you can use it
please maintain same format and level of detail when you edit.
thanks.

View File

@@ -8,7 +8,7 @@ import { STATUS, response, handleError } from 'src/utils/response';
import { JWT_SECRET } from 'src/_mock/_auth';
import { getUserById } from 'src/app/services/user.service';
import { createAccessLog } from 'src/app/services/AccessLog.service';
import { createAccessLog } from 'src/app/services/access-log.service';
import { flattenNextjsRequest } from '../sign-in/flattenNextjsRequest';

View File

@@ -4,7 +4,7 @@ import { sign } from 'src/utils/jwt';
import { STATUS, response, handleError } from 'src/utils/response';
import { JWT_SECRET, JWT_EXPIRES_IN } from 'src/_mock/_auth';
import { createAccessLog } from 'src/app/services/AccessLog.service';
import { createAccessLog } from 'src/app/services/access-log.service';
import prisma from '../../../lib/prisma';
import { flattenNextjsRequest } from './flattenNextjsRequest';

View File

@@ -1,5 +1,7 @@
###
# username and password ok
POST http://localhost:7272/api/auth/sign-in
content-type: application/json
@@ -9,7 +11,9 @@ content-type: application/json
}
###
# There is no user corresponding to the email address.
POST http://localhost:7272/api/auth/sign-in
content-type: application/json
@@ -19,7 +23,9 @@ content-type: application/json
}
###
# Wrong password
POST http://localhost:7272/api/auth/sign-in
content-type: application/json

View File

@@ -12,7 +12,7 @@ import { STATUS, response, handleError } from 'src/utils/response';
import { L_INFO, L_ERROR } from 'src/constants';
import { getEvent } from 'src/app/services/eventItem.service';
import { createAppLog } from 'src/app/services/AppLog.service';
import { createAppLog } from 'src/app/services/app-log.service';
// ----------------------------------------------------------------------

View File

@@ -0,0 +1,58 @@
// src/app/api/product/createEvent/route.ts
//
// PURPOSE:
// create product to db
//
// RULES:
// T.B.A.
//
import type { NextRequest } from 'next/server';
import _ from 'lodash';
import { STATUS, response, handleError } from 'src/utils/response';
import { getEventItemById } from 'src/app/services/eventItem.service';
import { getPartyUserByEmail } from 'src/app/services/party-user.service';
// ----------------------------------------------------------------------
/**
***************************************
* POST - Events
***************************************
*/
export async function POST(req: NextRequest) {
// logger('[Event] list', events.length);
const { data } = await req.json();
const { eventItemId, email } = data;
try {
const eventItem = await getEventItemById(eventItemId);
const partyUser = await getPartyUserByEmail(email);
if (partyUser) {
if (eventItem && eventItem?.joinMembers) {
const foundJoined = _.find(eventItem.joinMembers, { email });
if (foundJoined) {
console.log('user joined event already, skipping');
} else {
const { sex } = partyUser;
eventItem.joinMembers.push({ email, sex });
await prisma?.eventItem.update({
where: { id: eventItem.id },
data: { joinMembers: JSON.parse(JSON.stringify(eventItem.joinMembers)) },
});
}
}
}
return response({ result: 'joined' }, STATUS.OK);
} catch (error) {
console.log({ hello: 'world', data });
return handleError('Event - Create', error);
}
}

View File

@@ -0,0 +1,13 @@
###
# username and password ok
POST http://localhost:7272/api/event/partyUserJoinEvent
content-type: application/json
{
"data": {
"eventItemId": "e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01",
"email": "alice@prisma.io"
}
}

View File

@@ -11,7 +11,7 @@ import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { L_INFO, L_ERROR } from 'src/constants';
import { createAppLog } from 'src/app/services/AppLog.service';
import { createAppLog } from 'src/app/services/app-log.service';
import prisma from '../../../lib/prisma';
import { flattenNextjsRequest } from '../../auth/sign-in/flattenNextjsRequest';

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

@@ -25,13 +25,8 @@ const ENDPOINTS = {
};
function loggerData(action?: string, value?: unknown) {
const columnsWithTasks = boardData.columns.map(
(col) => `${col.name} (${boardData.tasks[col.id].length} tasks)`
);
logger(
'[Kanban] get-board',
`columns (${boardData.columns.length}): ${JSON.stringify(columnsWithTasks, null, 2)}`
);
const columnsWithTasks = boardData.columns.map((col) => `${col.name} (${boardData.tasks[col.id].length} tasks)`);
logger('[Kanban] get-board', `columns (${boardData.columns.length}): ${JSON.stringify(columnsWithTasks, null, 2)}`);
if (value || action) {
logger(`[Kanban] ${action}`, value);
}
@@ -126,9 +121,7 @@ async function updateColumn(req: NextRequest) {
// Find and update the specified column.
updateBoardData({
columns: boardData.columns.map((col) =>
col.id === columnId ? { ...col, name: columnName } : col
),
columns: boardData.columns.map((col) => (col.id === columnId ? { ...col, name: columnName } : col)),
});
loggerData('updated-column', columnName);
@@ -222,9 +215,7 @@ async function updateTask(req: NextRequest) {
updateBoardData({
tasks: {
...boardData.tasks,
[columnId]: boardData.tasks[columnId].map((task) =>
task.id === taskData.id ? { ...task, ...taskData } : task
),
[columnId]: boardData.tasks[columnId].map((task) => (task.id === taskData.id ? { ...task, ...taskData } : task)),
},
});

View File

@@ -31,10 +31,7 @@ export async function GET(req: NextRequest) {
}
// Get filtered mails
const filteredMails =
label.type === 'custom'
? mails.filter((mail) => mail.labelIds.includes(labelId!))
: filterMailsByLabelId(mails, labelId);
const filteredMails = label.type === 'custom' ? mails.filter((mail) => mail.labelIds.includes(labelId!)) : filterMailsByLabelId(mails, labelId);
logger(`[Mail] label-[${labelId}]`, filteredMails.length);

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

@@ -47,9 +47,7 @@ export async function GET(req: NextRequest) {
products: paginatedProducts,
totalPages,
totalItems,
categoryOptions: Array.from(
new Set(_products.map(({ category: c_category }) => c_category))
), // Remove duplicate categories
categoryOptions: Array.from(new Set(_products.map(({ category: c_category }) => c_category))), // Remove duplicate categories
},
STATUS.OK
);
@@ -70,9 +68,7 @@ function paginateProducts(products: Products, page: number, perPage: number) {
function filterProducts(products: Products, searchQuery: string, category: string) {
return products.filter(({ id, name, category: prodCategory }) => {
// Accept search by id or name
const matchesSearch = searchQuery
? id.includes(searchQuery) || name.toLowerCase().includes(searchQuery)
: true;
const matchesSearch = searchQuery ? id.includes(searchQuery) || name.toLowerCase().includes(searchQuery) : true;
const matchesCategory = category ? prodCategory === category : true;
return matchesSearch && matchesCategory;

View File

@@ -0,0 +1,35 @@
<!-- AI: please maintain same format and level of detail when edit this file -->
# GUIDELINE
- Party Event API endpoint for managing party events
- Handles CRUD operations for party events
- Follows single file for single db table/collection pattern
## `route.ts`
Handles HTTP methods:
- `GET` - Retrieve party events
- `POST` - Create new party event
- `PUT` - Update existing party event
- `DELETE` - Remove party event
## `test.http`
Contains test requests for:
- Listing all party events
- Creating new party event
- Updating existing party event
- Deleting party event
## `../../services/party-event.service.ts`
Party Event CRUD operations:
`listPartyEvents` - List all party events with optional filters
`getPartyEvent` - Get single party event by ID
`createNewPartyEvent` - Create new party event record
`updatePartyEvent` - Update existing party event by ID
`deletePartyEvent` - Delete party event by ID

View File

@@ -0,0 +1,40 @@
// src/app/api/party-event/create/route.ts
//
// PURPOSE:
// Create new party event in 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 { createEvent } from 'src/app/services/party-event.service';
// ----------------------------------------------------------------------
/** **************************************
* POST - Create PartyEvent
*************************************** */
export async function POST(req: NextRequest) {
const { partyEventData } = await req.json();
try {
if (isDev) {
console.log({ partyEventData });
}
const created = await createEvent(partyEventData);
if (isDev) {
console.log('Event created successfully');
}
return response(created, STATUS.OK);
} catch (error) {
console.error('Error creating event:', { partyEventData });
return handleError('PartyEvent - Create', error);
}
}

View File

@@ -0,0 +1,34 @@
###
POST http://localhost:7272/api/party-event/create
Content-Type: application/json
{
"partyEventData": {
"title": "Summer Music Festival",
"description": "Annual summer music festival featuring local bands and artists",
"startDate": "2024-07-15T18:00:00Z",
"endDate": "2024-07-15T23:00:00Z",
"location": "Central Park, Hong Kong",
"coverUrl": "",
"images": [
"data:image/png;base64,C",
"data:image/png;base64,C"
],
"tags": [
"Music",
"Festival"
],
"status": "upcoming",
"capacity": 500,
"price": 150.00,
"organizer": "HK Music Society",
"category": "Music",
"isFeatured": true,
"registrationDeadline": "2024-07-10T00:00:00Z",
"requirements": "Age 18+",
"schedule": "18:00 Doors open\n19:00 First performance\n21:00 Main act",
"speakers": ["DJ Lee", "Band XYZ"],
"sponsors": ["HK Radio", "Music Magazine"]
}
}

View File

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

View File

@@ -0,0 +1,8 @@
###
PATCH http://localhost:7272/api/party-event/delete
Content-Type: application/json
{
"partyEventId": "e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01"
}

View File

@@ -0,0 +1,56 @@
// src/app/api/party-event/details/route.ts
//
// PURPOSE:
// Get party event 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 { L_INFO, L_ERROR } from 'src/constants';
import { getEvent } from 'src/app/services/party-event.service';
import { createAppLog } from 'src/app/services/app-log.service';
import { flattenNextjsRequest } from '../../auth/sign-in/flattenNextjsRequest';
// ----------------------------------------------------------------------
/**
**************************************
* GET PartyEvent detail
***************************************
*/
export async function GET(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const { searchParams } = req.nextUrl;
// RULES: eventId must exist
const partyEventId = searchParams.get('partyEventId');
if (!partyEventId) {
return response({ message: 'PartyEvent ID is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: eventId confirmed exist, run below
const partyEvent = await getEvent(partyEventId);
if (!partyEvent) {
return response({ message: 'PartyEvent not found!' }, STATUS.NOT_FOUND);
}
logger('[PartyEvent] details', partyEvent.id);
createAppLog(L_INFO, 'Get event detail OK', debug);
return response({ partyEvent }, STATUS.OK);
} catch (error) {
createAppLog(L_ERROR, 'event detail error', debug);
return handleError('PartyEvent - Get details', error);
}
}

View File

@@ -0,0 +1,9 @@
###
# Get details for a specific party event
GET http://localhost:7272/api/party-event/details?partyEventId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01
###
# Alternative format with different ID
GET http://localhost:7272/api/party-event/details?eventId=evt_987654321

View File

@@ -0,0 +1,16 @@
import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
/**
***************************************
* GET - helloworld
***************************************
*/
export async function GET(req: NextRequest, res: NextResponse) {
try {
return response({ helloworld: 'party-event' }, STATUS.OK);
} catch (error) {
return handleError('Helloworld - Get all', error);
}
}

View File

@@ -0,0 +1,4 @@
###
GET /api/party-event/helloworld HTTP/1.1
Host: localhost:7272

View File

@@ -0,0 +1,38 @@
// src/app/api/party-event/list/route.ts
//
// PURPOSE:
// List all party events from db
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { L_INFO, L_ERROR } from 'src/constants';
import { createAppLog } from 'src/app/services/app-log.service';
import { listEvents } from 'src/app/services/party-event.service';
import { flattenNextjsRequest } from '../../auth/sign-in/flattenNextjsRequest';
// ----------------------------------------------------------------------
/** **************************************
* GET - PartyEvents list
*************************************** */
export async function GET(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const partyEvents = await listEvents();
createAppLog(L_INFO, 'party-event list ok', {});
return response({ partyEvents }, STATUS.OK);
} catch (error) {
createAppLog(L_ERROR, 'party-event list error', debug);
return handleError('PartyEvent - Get list', error);
}
}

View File

@@ -0,0 +1,14 @@
###
# Basic list all party events
GET http://localhost:7272/api/party-event/list
###
# List upcoming party events
GET http://localhost:7272/api/party-event/list?status=upcoming
###
# List featured party events
GET http://localhost:7272/api/party-event/list?isFeatured=true

View File

@@ -0,0 +1,75 @@
import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { listEvents, deleteEvent, updateEvent, createEvent } from 'src/app/services/party-event.service';
/**
**************************************
* GET - PartyEvent
***************************************
*/
export async function GET(req: NextRequest, res: NextResponse) {
try {
const events = await listEvents();
return response(events, STATUS.OK);
} catch (error) {
return handleError('PartyEvent - Get list', error);
}
}
/**
***************************************
* POST - Create PartyEvent
***************************************
*/
export async function POST(req: NextRequest) {
const OPERATION = 'PartyEvent - Create';
const { data } = await req.json();
try {
const event = await createEvent(data);
return response(OPERATION, STATUS.OK);
} catch (error) {
return handleError(OPERATION, error);
}
}
/**
***************************************
* PUT - Update PartyEvent
***************************************
*/
export async function PUT(req: NextRequest) {
const { searchParams } = req.nextUrl;
const eventId = searchParams.get('eventId');
const { data } = await req.json();
try {
if (!eventId) throw new Error('eventId cannot be null');
const result = await updateEvent(eventId, data);
return response(result, STATUS.OK);
} catch (error) {
return handleError('PartyEvent - Update', error);
}
}
/**
***************************************
* DELETE - Delete PartyEvent
***************************************
*/
export async function DELETE(req: NextRequest) {
const { searchParams } = req.nextUrl;
const eventId = searchParams.get('eventId');
try {
if (!eventId) throw new Error('eventId cannot be null');
await deleteEvent(eventId);
return response({ success: true }, STATUS.OK);
} catch (error) {
return handleError('PartyEvent - Delete', error);
}
}

View File

@@ -0,0 +1,34 @@
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import { IEventItem } from '../update/route';
// import { searchEvents } from 'src/app/services/party-event.service';
// ----------------------------------------------------------------------
/** **************************************
* GET - Search PartyEvents
*************************************** */
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 results: IEventItem[] = [];
// TODO: search party event not implemented
console.log('search party event not implemented');
// const results = await searchEvents(query);
logger('[PartyEvent] search-results', results?.length);
return response({ results }, STATUS.OK);
} catch (error) {
return handleError('PartyEvent - Get search', error);
}
}

View File

@@ -0,0 +1,24 @@
###
# Search party events by title
GET http://localhost:7272/api/party-event/search?query=Music
###
# Search party events by location
GET http://localhost:7272/api/party-event/search?query=Central+Park
###
# Search party events by tag
GET http://localhost:7272/api/party-event/search?query=Festival
###
# Combined search with multiple parameters
GET http://localhost:7272/api/party-event/search?query=Summer&location=Hong+Kong&category=Music
###
# No results expected
GET http://localhost:7272/api/party-event/search?query=zzzzzz

View File

@@ -0,0 +1,57 @@
// src/app/api/party-event/update/route.ts
//
// PURPOSE:
// Update party event in db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { updateEvent } from 'src/app/services/party-event.service';
// ----------------------------------------------------------------------
/** **************************************
* PUT - Update PartyEvent
*************************************** */
export async function PUT(req: NextRequest) {
const { partyEventData } = await req.json();
const { id } = partyEventData;
if (!id) return response({ message: 'id not found' }, STATUS.ERROR);
try {
const result = await updateEvent(id, partyEventData);
return response({ result }, STATUS.OK);
} catch (error) {
console.error('Error updating event:', { partyEventData });
return handleError('PartyEvent - Update', error);
}
}
export type IEventItem = {
id: string;
title: string;
description: string;
startDate: Date;
endDate: Date;
location: string;
coverUrl: string;
images: string[];
tags: string[];
status: string;
capacity: number;
price: number;
organizer: string;
category: string;
isFeatured: boolean;
registrationDeadline: Date;
requirements: string[];
schedule: string;
speakers: string[];
sponsors: string[];
};

View File

@@ -0,0 +1,31 @@
###
PUT http://localhost:7272/api/party-event/update
Content-Type: application/json
{
"partyEventData": {
"id":"e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01",
"title": "Summer Music Festival 111",
"name": "Summer Music Festival 111",
"description": "Annual summer music festival featuring local bands and artists",
"startDate": "2024-07-15T18:00:00Z",
"endDate": "2024-07-15T23:00:00Z",
"location": "Central Park, Hong Kong",
"coverUrl": "",
"images": [ "data:image/png;base64,C", "data:image/png;base64,C" ],
"tags": [ "Music", "Festival" ],
"status": "upcoming",
"capacity": 500,
"price": 150.00,
"organizer": "HK Music Society",
"category": "Music",
"isFeatured": true,
"registrationDeadline": "2024-07-10T00:00:00Z",
"requirements": "Age 18+",
"schedule": "18:00 Doors open\n19:00 First performance\n21:00 Main act",
"speakers": ["DJ Lee", "Band XYZ"],
"sponsors": ["HK Radio", "Music Magazine"],
"reviews":[]
}
}

View File

@@ -0,0 +1,35 @@
<!-- AI: please maintain same format and level of detail when edit this file -->
# GUIDELINE
- Party Order API endpoint for managing party orders
- Handles CRUD operations for party orders
- Follows single file for single db table/collection pattern
## `route.ts`
Handles HTTP methods:
- `GET` - Retrieve party orders
- `POST` - Create new party order
- `PUT` - Update existing party order
- `DELETE` - Remove party order
## `test.http`
Contains test requests for:
- Listing all party orders
- Creating new party order
- Updating existing party order
- Deleting party order
## `../../services/party-order.service.ts`
Party Order CRUD operations:
`listPartyOrders` - List all party orders with optional filters
`getPartyOrder` - Get single party order by ID
`createNewPartyOrder` - Create new party order record
`updatePartyOrder` - Update existing party order by ID
`deletePartyOrder` - Delete party order by ID

View File

@@ -0,0 +1,40 @@
// src/app/api/party-order/create/route.ts
//
// PURPOSE:
// Create new party order in 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 { createOrder } from 'src/app/services/party-order.service';
// ----------------------------------------------------------------------
/** **************************************
* POST - Create PartyOrder
*************************************** */
export async function POST(req: NextRequest) {
const { partyOrderData } = await req.json();
try {
if (isDev) {
console.log({ partyOrderData });
}
const created = await createOrder(partyOrderData);
if (isDev) {
console.log('Order created successfully');
}
return response(created, STATUS.OK);
} catch (error) {
console.error('Error creating order:', { partyOrderData });
return handleError('PartyOrder - Create', error);
}
}

View File

@@ -0,0 +1,31 @@
###
POST http://localhost:7272/api/party-order/create
Content-Type: application/json
{
"partyOrderData": {
"taxes": 15.00,
"status": "pending",
"shipping": 10.00,
"discount": 20.00,
"subtotal": 290.00,
"orderNumber": "ORD_20231115001",
"totalAmount": 300.00,
"totalQuantity": 2.0,
"history": "{\"actions\":[{\"timestamp\":\"2023-11-15T10:00:00Z\",\"action\":\"order_created\"}]}",
"payment": "{\"method\":\"credit_card\",\"status\":\"unpaid\",\"transaction_id\":\"txn_123456\"}",
"customer": "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\",\"phone\":\"+1234567890\"}",
"delivery": "{\"method\":\"courier\",\"estimated_delivery\":\"2023-11-18\"}",
"items": [
{
"id": "ticket_001",
"name": "General Admission",
"quantity": 2,
"price": 150.00
}
],
"shippingAddress": "{\"street\":\"123 Main St\",\"city\":\"New York\",\"state\":\"NY\",\"zip\":\"10001\",\"country\":\"USA\"}"
}
}

View File

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

View File

@@ -0,0 +1,8 @@
###
PATCH http://localhost:7272/api/party-order/delete
Content-Type: application/json
{
"partyOrderId": "e99f09a7-dd88-49d5-b1c8-1daf80c2d7b02"
}

View File

@@ -0,0 +1,56 @@
// src/app/api/party-order/details/route.ts
//
// PURPOSE:
// Get party order from db by id
//
// RULES:
// Do not modify the format and level of details thanks.
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import { L_INFO, L_ERROR } from 'src/constants';
import { getOrder } from 'src/app/services/party-order.service';
import { createAppLog } from 'src/app/services/app-log.service';
import { flattenNextjsRequest } from '../../auth/sign-in/flattenNextjsRequest';
// ----------------------------------------------------------------------
/**
**************************************
* GET PartyOrder detail
***************************************
*/
export async function GET(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const { searchParams } = req.nextUrl;
// RULES: partyOrderId must exist
const partyOrderId = searchParams.get('partyOrderId');
if (!partyOrderId) {
return response({ message: 'Order ID is required!' }, STATUS.BAD_REQUEST);
}
// NOTE: partyOrderId confirmed exist, run below
const partyOrder = await getOrder(partyOrderId);
if (!partyOrder) {
return response({ message: 'Order not found!' }, STATUS.NOT_FOUND);
}
logger('[PartyOrder] details', partyOrder.id);
createAppLog(L_INFO, 'Get order detail OK', debug);
return response({ partyOrder }, STATUS.OK);
} catch (error) {
createAppLog(L_ERROR, 'order detail error', debug);
return handleError('PartyOrder - Get details', error);
}
}

View File

@@ -0,0 +1,9 @@
###
# Get details for a specific party order
GET http://localhost:7272/api/party-order/details?partyOrderId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b13
###
# Alternative format with different ID
GET http://localhost:7272/api/party-order/details?id=ord_987654321

View File

@@ -0,0 +1,16 @@
import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
/**
***************************************
* GET - helloworld
***************************************
*/
export async function GET(req: NextRequest, res: NextResponse) {
try {
return response({ helloworld: 'party-order' }, STATUS.OK);
} catch (error) {
return handleError('Helloworld - Get all', error);
}
}

View File

@@ -0,0 +1,2 @@
###
GET http://localhost:7272/api/party-order/helloworld

View File

@@ -0,0 +1,38 @@
// src/app/api/party-order/list/route.ts
//
// PURPOSE:
// List all party orders from db
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { L_INFO, L_ERROR } from 'src/constants';
import { createAppLog } from 'src/app/services/app-log.service';
import { listPartyOrders } from 'src/app/services/party-order.service';
import { flattenNextjsRequest } from '../../auth/sign-in/flattenNextjsRequest';
// ----------------------------------------------------------------------
/** **************************************
* GET - PartyOrders list
*************************************** */
export async function GET(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const partyOrders = await listPartyOrders();
createAppLog(L_INFO, 'party-order list ok', {});
return response({ partyOrders }, STATUS.OK);
} catch (error) {
createAppLog(L_ERROR, 'party-order list error', debug);
return handleError('PartyOrder - Get list', error);
}
}

View File

@@ -0,0 +1,19 @@
###
# Basic list all orders
GET http://localhost:7272/api/party-order/list
###
# List orders by status
GET http://localhost:7272/api/party-order/list?status=completed
###
# List orders by user
GET http://localhost:7272/api/party-order/list?userId=usr_987654321
###
# List orders by payment status
GET http://localhost:7272/api/party-order/list?paymentStatus=paid

View File

@@ -0,0 +1,75 @@
import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { listPartyOrders, deleteOrder, updateOrder, createOrder } from 'src/app/services/party-order.service';
/**
**************************************
* GET - PartyOrder
***************************************
*/
export async function GET(req: NextRequest, res: NextResponse) {
try {
const orders = await listPartyOrders();
return response(orders, STATUS.OK);
} catch (error) {
return handleError('PartyOrder - Get list', error);
}
}
/**
***************************************
* POST - Create PartyOrder
***************************************
*/
export async function POST(req: NextRequest) {
const OPERATION = 'PartyOrder - Create';
const { data } = await req.json();
try {
const order = await createOrder(data);
return response(OPERATION, STATUS.OK);
} catch (error) {
return handleError(OPERATION, error);
}
}
/**
***************************************
* PUT - Update PartyOrder
***************************************
*/
export async function PUT(req: NextRequest) {
const { searchParams } = req.nextUrl;
const orderId = searchParams.get('orderId');
const { data } = await req.json();
try {
if (!orderId) throw new Error('orderId cannot be null');
const result = await updateOrder(orderId, data);
return response(result, STATUS.OK);
} catch (error) {
return handleError('PartyOrder - Update', error);
}
}
/**
***************************************
* DELETE - Delete PartyOrder
***************************************
*/
export async function DELETE(req: NextRequest) {
const { searchParams } = req.nextUrl;
const orderId = searchParams.get('orderId');
try {
if (!orderId) throw new Error('orderId cannot be null');
await deleteOrder(orderId);
return response({ success: true }, STATUS.OK);
} catch (error) {
return handleError('PartyOrder - Delete', error);
}
}

View File

@@ -0,0 +1,35 @@
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import type { IOrderItem } from '../update/route';
// import { searchEvents } from 'src/app/services/party-event.service';
// ----------------------------------------------------------------------
/** **************************************
* GET - Search PartyEvents
*************************************** */
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 results: IOrderItem[] = [];
// TODO: search party event not implemented
console.log('search party event not implemented');
// const results = await searchEvents(query);
logger('[PartyEvent] search-results', results?.length);
return response({ results }, STATUS.OK);
} catch (error) {
return handleError('PartyEvent - Get search', error);
}
}

View File

@@ -0,0 +1,24 @@
###
# Search party events by title
GET http://localhost:7272/api/party-event/search?query=Music
###
# Search party events by location
GET http://localhost:7272/api/party-event/search?query=Central+Park
###
# Search party events by tag
GET http://localhost:7272/api/party-event/search?query=Festival
###
# Combined search with multiple parameters
GET http://localhost:7272/api/party-event/search?query=Summer&location=Hong+Kong&category=Music
###
# No results expected
GET http://localhost:7272/api/party-event/search?query=zzzzzz

View File

@@ -0,0 +1,51 @@
// src/app/api/party-order/update/route.ts
//
// PURPOSE:
// Update party order in db by id
//
// RULES:
// T.B.A.
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { updateOrder } from 'src/app/services/party-order.service';
// ----------------------------------------------------------------------
/** **************************************
* PUT - Update PartyOrder
*************************************** */
export async function PUT(req: NextRequest) {
const { orderData } = await req.json();
const { id } = orderData;
if (!id) return response({ message: 'id not found' }, STATUS.ERROR);
try {
const result = await updateOrder(id, orderData);
return response({ result }, STATUS.OK);
} catch (error) {
console.error('Error updating order:', { orderData });
return handleError('PartyOrder - Update', error);
}
}
export type IOrderItem = {
id: string;
eventId: string;
userId: string;
status: string;
paymentStatus: string;
totalAmount: number;
items: {
id: string;
name: string;
quantity: number;
price: number;
}[];
createdAt: Date;
updatedAt: Date;
};

View File

@@ -0,0 +1,51 @@
###
PUT http://localhost:7272/api/party-order/update
Content-Type: application/json
{
"orderData": {
"id":"e99f09a7-dd88-49d5-b1c8-1daf80c2d7b02",
"taxes": 10.50,
"status": "completed",
"shipping": 5.00,
"discount": 20.00,
"subtotal": 290.00,
"orderNumber": "ORD-2023-001",
"totalAmount": 300.00,
"totalQuantity": 2,
"history": {
"payment": "2023-01-01",
"status_changes": [
"pending",
"paid"
]
},
"payment": {
"method": "credit_card",
"card_last4": "4321"
},
"customer": {
"name": "John Doe",
"email": "john@example.com"
},
"delivery": {
"method": "express",
"tracking_number": "TRK123456"
},
"items": [
{
"id": "ticket_001",
"name": "General Admission",
"quantity": 2,
"price": 150.00,
"status": "used"
}
],
"shippingAddress": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}
}

View File

@@ -0,0 +1,68 @@
import type { User } from '@prisma/client';
import type { NextRequest } from 'next/server';
import { headers } from 'next/headers';
import { verify } from 'src/utils/jwt';
import { STATUS, response, handleError } from 'src/utils/response';
import { JWT_SECRET } from 'src/_mock/_auth';
import { getUserById } from 'src/app/services/user.service';
import { createAccessLog } from 'src/app/services/access-log.service';
import { flattenNextjsRequest } from '../sign-in/flattenNextjsRequest';
// ----------------------------------------------------------------------
// export const runtime = 'edge';
/**
* This API is used for demo purpose only
* You should use a real database
* You should hash the password before saving to database
* You should not save the password in the database
* You should not expose the JWT_SECRET in the client side
*/
const USER_TOKEN_CHECK_FAILED = 'user token check failed';
const INVALID_AUTH_TOKEN = 'Invalid authorization token';
const USER_ID_NOT_FOUND = 'userId not found';
const USER_TOKEN_OK = 'user token check ok';
const AUTHORIZATION_TOKEN_MISSING_OR_INVALID = 'Authorization token missing or invalid';
export async function GET(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const headersList = headers();
const authorization = headersList.get('authorization');
if (!authorization || !authorization.startsWith('Bearer ')) {
return response({ message: AUTHORIZATION_TOKEN_MISSING_OR_INVALID }, STATUS.UNAUTHORIZED);
}
const accessToken = `${authorization}`.split(' ')[1];
const data = await verify(accessToken, JWT_SECRET);
console.log(data.userId);
if (data.userId) {
// TODO: remove me
// const currentUser = _users.find((user) => user.id === data.userId);
const currentUser: User | null = await getUserById(data.userId);
if (!currentUser) {
createAccessLog('', USER_TOKEN_CHECK_FAILED, debug);
return response({ message: INVALID_AUTH_TOKEN }, STATUS.UNAUTHORIZED);
}
createAccessLog(currentUser.id, USER_TOKEN_OK, debug);
return response({ user: currentUser }, STATUS.OK);
} else {
return response({ message: USER_ID_NOT_FOUND }, STATUS.ERROR);
}
} catch (error) {
return handleError('[Auth] - Me', error);
}
}

View File

@@ -0,0 +1,25 @@
###
# username and password ok
GET http://localhost:7272/api/auth/me
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjbWJnbnUyengwMDBjaHEzaGZ3dmtjejlvIiwiaWF0IjoxNzQ4OTY0ODkyLCJleHAiOjE3NTAxNzQ0OTJ9.lo04laCxtm0IVeYaETEV3hXKyDmXPEn7SyWtY2VR4dI
###
# There is no user corresponding to the email address.
POST http://localhost:7272/api/auth/sign-in
content-type: application/json
{
"email": "demo@minimals1.cc",
"password": "@2Minimal"
}
###
# Wrong password
POST http://localhost:7272/api/auth/sign-in
content-type: application/json
{
"email": "demo@minimals.cc",
"password": "@2Min111imal"
}

View File

@@ -0,0 +1,10 @@
import type { NextRequest } from 'next/server';
/**
* Flattens a Next.js request object into a plain object of headers
* @param {NextRequest} req - The Next.js request object
* @returns {Record<string, string>} An object containing all request headers
*/
export function flattenNextjsRequest(req: NextRequest) {
return Object.fromEntries(req.headers.entries());
}

View File

@@ -0,0 +1,56 @@
// src/app/api/party-user-auth/sign-in/route1.ts
//
import type { NextRequest } from 'next/server';
import { sign } from 'src/utils/jwt';
import { STATUS, response, handleError } from 'src/utils/response';
import { JWT_SECRET, JWT_EXPIRES_IN } from 'src/_mock/_auth';
import { createAccessLog } from 'src/app/services/access-log.service';
import prisma from '../../../lib/prisma';
import { flattenNextjsRequest } from './flattenNextjsRequest';
// ----------------------------------------------------------------------
/**
* This API is used for demo purpose only
* You should use a real database
* You should hash the password before saving to database
* You should not save the password in the database
* You should not expose the JWT_SECRET in the client side
*/
const ERR_USER_NOT_FOUND = 'There is no user corresponding to the email address.';
const ERR_WRONG_PASSWORD = 'Wrong password';
export async function POST(req: NextRequest) {
const debug = { 'req.headers': flattenNextjsRequest(req) };
try {
const { email, password } = await req.json();
const currentUser = await prisma.partyUser.findFirst({ where: { email } });
if (!currentUser) {
await createAccessLog('', `user tried login with email ${email}`, { debug });
return response({ message: ERR_USER_NOT_FOUND }, STATUS.UNAUTHORIZED);
}
if (currentUser?.password !== password) {
await createAccessLog(currentUser.id, 'user logged with wrong password', { debug });
return response({ message: ERR_WRONG_PASSWORD }, STATUS.UNAUTHORIZED);
}
const accessToken = await sign({ userId: currentUser?.id }, JWT_SECRET, {
expiresIn: JWT_EXPIRES_IN,
});
await createAccessLog(currentUser.id, 'access granted', { debug });
return response({ user: currentUser, accessToken }, STATUS.OK);
} catch (error) {
await createAccessLog('', 'attempted login but failed', { debug, error });
return handleError('Auth - Sign in', error);
}
}

View File

@@ -0,0 +1,37 @@
# REQ0188 frontend party-user
###
# username and password ok
POST http://localhost:7272/api/party-user-auth/sign-in
content-type: application/json
{
"email": "demo@minimals.cc",
"password": "@2Minimal"
}
###
# There is no user corresponding to the email address.
POST http://localhost:7272/api/party-user-auth/sign-in
content-type: application/json
{
"email": "demo@minimals1.cc",
"password": "@2Minimal"
}
###
# Wrong password
POST http://localhost:7272/api/party-user-auth/sign-in
content-type: application/json
{
"email": "demo@minimals.cc",
"password": "@2Min111imal"
}

View File

@@ -0,0 +1,58 @@
import type { NextRequest } from 'next/server';
import { sign } from 'src/utils/jwt';
import { STATUS, response, handleError } from 'src/utils/response';
import { _users, JWT_SECRET, JWT_EXPIRES_IN } from 'src/_mock/_auth';
// ----------------------------------------------------------------------
/**
* This API is used for demo purpose only
* You should use a real database
* You should hash the password before saving to database
* You should not save the password in the database
* You should not expose the JWT_SECRET in the client side
*/
export const runtime = 'edge';
export async function POST(req: NextRequest) {
try {
const { email, password, firstName, lastName } = await req.json();
const userExists = _users.find((user) => user.email === email);
if (userExists) {
return response({ message: 'There already exists an account with the given email address.' }, STATUS.CONFLICT);
}
const newUser = {
id: _users[0].id,
displayName: `${firstName} ${lastName}`,
email,
password,
photoURL: '',
phoneNumber: '',
country: '',
address: '',
state: '',
city: '',
zipCode: '',
about: '',
role: 'user',
isPublic: true,
};
const accessToken = await sign({ userId: newUser.id }, JWT_SECRET, {
expiresIn: JWT_EXPIRES_IN,
});
// Push new user to database
_users.push(newUser);
return response({ user: newUser, accessToken }, STATUS.OK);
} catch (error) {
return handleError('Auth - Sign up', error);
}
}

View File

@@ -0,0 +1,60 @@
<!-- NOTES to AI: please maintain same format and level of detail when edit this file -->
# GUIDELINE
- Party-user Management API endpoint for managing party-user accounts
- Handles party-user CRUD operations and profile updates
- Follows Next.js API route conventions
## Endpoints
### `create/route.ts`
Creates new party-user account with required details
### `delete/route.ts`
Deletes party-user account by ID
### `details/route.ts`
Gets detailed party-user information
### `helloworld/route.ts`
Simple test endpoint returning "Hello World"
### `list/route.ts`
Lists all party-users with pagination support
### `search/route.ts`
Searches party-users by name or email
### `update/route.ts`
Updates party-user profile information
## Testing
Test files are available per endpoint in their respective directories:
- `create/test.http`
- `delete/test.http`
- `details/test.http`
- `helloworld/test.http`
- `list/test.http`
- `update/test.http`
## Related Services
`../../services/party-user.service.ts` (assumed) would handle:
`createUser` - Register new party-user account
`updateUser` - Update party-user profile
`deleteUser` - Remove party-user account
`listUsers` - Get paginated party-user list
`searchUsers` - Search party-users by criteria
`changeUserRole` - Modify party-user permissions
`uploadUserImage` - Handle profile picture uploads

View File

@@ -0,0 +1,34 @@
// src/app/api/party-user/create/route.ts
//
// PURPOSE:
// create new party user in db
//
// RULES:
// 1. Validates input data shape
// 2. Returns created party user data
//
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { createPartyUser } from 'src/app/services/party-user.service';
// ----------------------------------------------------------------------
/**
***************************************
* POST - create PartyUser
***************************************
*/
export async function POST(req: NextRequest) {
const { partyUserData } = await req.json();
try {
const partyUser = await createPartyUser(partyUserData);
return response({ partyUser }, STATUS.OK);
} catch (error) {
return handleError('PartyUser - Create', error);
}
}

View File

@@ -0,0 +1,19 @@
###
POST http://localhost:7272/api/party-user/create
Content-Type: application/json
{
"partyUserData": {
"name": "Alice 123321",
"username": null,
"email": "alice@123111321.io",
"emailVerified": "2025-06-15T17:47:23.919Z",
"password": "Aa12345678",
"bucketImage": null,
"admin": false,
"info": null,
"phoneNumber": "+85291234567",
"avatarUrl": ""
}
}

View File

@@ -0,0 +1,35 @@
// src/app/api/party-user/delete/route.ts
//
// PURPOSE:
// delete party user from db by id
//
// RULES:
// 1. Requires valid party user ID
// 2. Returns deleted party user ID
// 3. Handles errors appropriately
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { deletePartyUser } from 'src/app/services/party-user.service';
/**
**************************************
* PATCH - Delete party user
***************************************
*/
export async function PATCH(req: NextRequest) {
try {
const { partyUserId } = await req.json();
if (!partyUserId) throw new Error('partyUserId cannot be null');
await deletePartyUser(partyUserId);
return response({ partyUserId }, STATUS.OK);
} catch (error) {
return handleError('PartyUser - Delete', error);
}
}

View File

@@ -0,0 +1,8 @@
###
PATCH http://localhost:7272/api/party-user/delete
Content-Type: application/json
{
"partyUserId": "cmbxz8t2b000oiigxib3o4jla"
}

View File

@@ -0,0 +1,43 @@
// src/app/api/party-user/details/route.ts
//
// PURPOSE:
// get party user details from db by id
//
// RULES:
// 1. Requires valid partyUserId parameter
// 2. Returns party user details if found
// 3. Handles not found case appropriately
// 4. Logs the operation
import type { NextRequest } from 'next/server';
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import { getPartyUser } from 'src/app/services/party-user.service';
// ----------------------------------------------------------------------
/** **************************************
* GET PartyUser detail
*************************************** */
export async function GET(req: NextRequest) {
try {
const { searchParams } = req.nextUrl;
// RULES: userId must exist
const partyUserId = searchParams.get('partyUserId');
if (!partyUserId) return response({ message: 'partyUserId is required!' }, STATUS.BAD_REQUEST);
// NOTE: userId confirmed exist, run below
const partyUser = await getPartyUser(partyUserId);
if (!partyUser) return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
logger('[User] details', partyUser.id);
return response({ partyUser }, STATUS.OK);
} catch (error) {
return handleError('PartyUser - Get details', error);
}
}

View File

@@ -0,0 +1,4 @@
###
GET http://localhost:7272/api/party-user/details?partyUserId=cmbxziat6000b715hmhrnwlx2

View File

@@ -0,0 +1,11 @@
import type { NextRequest, NextResponse } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
export async function GET(req: NextRequest, res: NextResponse) {
try {
return response({ helloworld: 'party-user' }, STATUS.OK);
} catch (error) {
return handleError('GET - helloworld', error);
}
}

View File

@@ -0,0 +1,3 @@
###
GET http://localhost:7272/api/party-user/helloworld

View File

@@ -0,0 +1,33 @@
// src/app/api/party-user/update/route.ts
//
// PURPOSE:
// update existing party user in db
//
// RULES:
// 1. Requires valid party user ID
// 2. Validates input data shape
//
import { logger } from 'src/utils/logger';
import { STATUS, response, handleError } from 'src/utils/response';
import { listPartyUsers } from 'src/app/services/party-user.service';
// ----------------------------------------------------------------------
/**
***************************************
* GET - Products
***************************************
*/
export async function GET() {
try {
const partyUsers = await listPartyUsers();
logger('[User] list', partyUsers.length);
return response({ partyUsers }, STATUS.OK);
} catch (error) {
return handleError('Product - Get list', error);
}
}

View File

@@ -0,0 +1,2 @@
###
GET http://localhost:7272/api/party-user/list

View File

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

@@ -0,0 +1,88 @@
// src/app/api/party-user/update/route.ts
//
// PURPOSE:
// update existing party user in db
//
// RULES:
// 1. Requires valid party user ID
// 2. Validates input data shape
// 3. Returns updated party user data
// 4. Handles errors appropriately
import type { NextRequest } from 'next/server';
import { STATUS, response, handleError } from 'src/utils/response';
import { updatePartyUser } from 'src/app/services/party-user.service';
// ----------------------------------------------------------------------
/** **************************************
* PUT - Update PartyUser
*************************************** */
export async function PUT(req: NextRequest) {
// logger('[Product] list', products.length);
const { partyUserData } = await req.json();
try {
await updatePartyUser(partyUserData.id, partyUserData);
return response({ partyUserData }, STATUS.OK);
} catch (error) {
return handleError('PartyUser - Update', 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,22 @@
###
PUT http://localhost:7272/api/party-user/update
Content-Type: application/json
{
"partyUserData": {
"id": "cmc0cedkx000boln3viy77598",
"createdAt": "2025-06-15T17:47:24.547Z",
"updatedAt": "2025-06-15T17:47:24.547Z",
"name": "Alice 123321",
"username": null,
"email": "alice@prisma.io",
"emailVerified": "2025-06-15T17:47:23.919Z",
"password": "Aa12345678",
"image": null,
"bucketImage": null,
"admin": false,
"info": null,
"phoneNumber": "+85291234567"
}
}

View File

@@ -24,10 +24,7 @@ export async function GET(req: NextRequest) {
const posts = _posts();
// Accept search by title or description
const results = posts.filter(
({ title, description }) =>
title.toLowerCase().includes(query) || description?.toLowerCase().includes(query)
);
const results = posts.filter(({ title, description }) => title.toLowerCase().includes(query) || description?.toLowerCase().includes(query));
logger('[Post] search-results', results.length);

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 { createProduct } from 'src/app/services/product.service';
// ----------------------------------------------------------------------
/** **************************************
* POST - Products
*************************************** */
export async function POST(req: NextRequest) {
const { productData } = await req.json();
try {
if (isDev) {
console.log({ productData });
}
const created = await createProduct(productData);
// const created = await prisma.productItem.create({ data: productData });
if (isDev) {
console.log('create done');
}
return response(created, 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/create
Content-Type: application/json
{
"productData": {
"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,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,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);
}
}

Some files were not shown because too many files have changed in this diff Show More