Compare commits
5 Commits
develop/in
...
develop/cm
Author | SHA1 | Date | |
---|---|---|---|
![]() |
24920fb313 | ||
![]() |
a0a4ffcb4e | ||
![]() |
5480b62131 | ||
![]() |
fc6ed533e2 | ||
![]() |
8b73b583cd |
@@ -46,6 +46,9 @@ model Session {
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
//
|
||||
name String?
|
||||
username String? @unique
|
||||
email String @unique
|
||||
@@ -54,8 +57,6 @@ model User {
|
||||
image String?
|
||||
bucketImage String?
|
||||
admin Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
info Json?
|
||||
@@ -70,6 +71,9 @@ model VerificationToken {
|
||||
@@unique([identifier, token])
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// frontend/src/_mock/_user.ts
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// REQ0044/near_by_page
|
||||
@@ -99,6 +103,9 @@ model Member {
|
||||
music String[] @default([])
|
||||
pets String[] @default([])
|
||||
character String[] @default([])
|
||||
//
|
||||
avatar String @default("")
|
||||
sex String @default("")
|
||||
}
|
||||
|
||||
model Order {
|
||||
@@ -118,7 +125,7 @@ model Event {
|
||||
id Int @id @default(autoincrement())
|
||||
eventDate DateTime
|
||||
title String
|
||||
joinMembers Member[] // Assuming Member model exists
|
||||
joinMembers Json[] // Assuming Member model exists
|
||||
price Float
|
||||
currency String
|
||||
duration_m Int
|
||||
@@ -127,6 +134,8 @@ model Event {
|
||||
location String
|
||||
avatar String // Assuming avatar is stored as a file path or URL
|
||||
Order Order[]
|
||||
Member Member? @relation(fields: [memberId], references: [id])
|
||||
memberId Int?
|
||||
}
|
||||
|
||||
// cms_backend
|
||||
@@ -537,6 +546,8 @@ model UserItem {
|
||||
//
|
||||
username String
|
||||
password String
|
||||
//
|
||||
isAdmin Boolean @default(false)
|
||||
}
|
||||
|
||||
model UserAccountBillingHistory {
|
||||
@@ -903,7 +914,7 @@ model InvoiceItem {
|
||||
invoiceTo Json
|
||||
sent Float
|
||||
dueDate DateTime @default(now())
|
||||
createdDate DateTime @default(now())
|
||||
createDate DateTime @default(now())
|
||||
}
|
||||
|
||||
// model Invoice {
|
||||
@@ -1078,3 +1089,96 @@ model Kanban {
|
||||
columns KanbanColumn[]
|
||||
tasks KanbanTask[]
|
||||
}
|
||||
|
||||
// mapped to IEventReview
|
||||
model EventReview {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
//
|
||||
name String
|
||||
rating Float
|
||||
comment String
|
||||
helpful Float
|
||||
avatarUrl String
|
||||
postedAt DateTime @default(now()) // Assuming IDateValue maps to DateTime
|
||||
isPurchased Boolean
|
||||
attachments String[]
|
||||
//
|
||||
EventItem EventItem? @relation(fields: [eventItemId], references: [id])
|
||||
eventItemId String?
|
||||
}
|
||||
|
||||
// mapped to IEventItem
|
||||
model EventItem {
|
||||
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[]
|
||||
//
|
||||
eventDate DateTime @default(now())
|
||||
joinMembers Json[]
|
||||
title String
|
||||
currency String
|
||||
duration_m Float
|
||||
ageBottom Float
|
||||
ageTop Float
|
||||
location String
|
||||
avatar String[]
|
||||
//
|
||||
reviews EventReview[]
|
||||
}
|
||||
|
||||
model AppLog {
|
||||
id String @id @default(uuid())
|
||||
timestamp DateTime @default(now())
|
||||
//
|
||||
level Int? @default(1)
|
||||
message String? @default("")
|
||||
//
|
||||
module String?
|
||||
userId String?
|
||||
metadata Json?
|
||||
|
||||
@@index([timestamp])
|
||||
@@index([level])
|
||||
@@index([module])
|
||||
}
|
||||
|
||||
model AccessLog {
|
||||
id String @id @default(uuid())
|
||||
timestamp DateTime @default(now())
|
||||
//
|
||||
userId String? @default("")
|
||||
message String? @default("")
|
||||
//
|
||||
metadata Json?
|
||||
|
||||
@@index([timestamp])
|
||||
@@index([userId])
|
||||
}
|
||||
|
@@ -25,6 +25,11 @@ import { FileStore } from './seeds/fileStore';
|
||||
import { userItemSeed } from './seeds/userItem';
|
||||
import { orderItemSeed } from './seeds/orderItem';
|
||||
import { invoiceItemSeed } from './seeds/invoiceItem';
|
||||
//
|
||||
import { EventItemSeed } from './seeds/eventItem';
|
||||
import { EventReviewSeed } from './seeds/eventReview';
|
||||
import { appLogSeed } from './seeds/AppLog';
|
||||
import { accessLogSeed } from './seeds/AccessLog';
|
||||
|
||||
//
|
||||
// import { Blog } from './seeds/blog';
|
||||
@@ -44,8 +49,16 @@ import { invoiceItemSeed } from './seeds/invoiceItem';
|
||||
await userItemSeed;
|
||||
await orderItemSeed;
|
||||
await invoiceItemSeed;
|
||||
//
|
||||
await EventReviewSeed;
|
||||
await EventItemSeed;
|
||||
//
|
||||
await appLogSeed;
|
||||
await accessLogSeed;
|
||||
|
||||
// await Blog;
|
||||
// await Mail;
|
||||
// await File;
|
||||
// await Chat;
|
||||
console.log('seed done');
|
||||
})();
|
||||
|
36
03_source/cms_backend/prisma/seeds/AccessLog.ts
Normal file
36
03_source/cms_backend/prisma/seeds/AccessLog.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
|
||||
const L_ERROR = 0;
|
||||
const L_WARN = 1;
|
||||
const L_INFO = 2;
|
||||
const L_DEBUG = 3;
|
||||
const L_TRACE = 4;
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function accessLog() {
|
||||
await prisma.accessLog.upsert({
|
||||
where: { id: '0' },
|
||||
update: {},
|
||||
create: {
|
||||
userId: '0',
|
||||
message: 'helloworld',
|
||||
metadata: { hello: 'world' },
|
||||
},
|
||||
});
|
||||
|
||||
console.log('seed AccessLog done');
|
||||
}
|
||||
|
||||
const accessLogSeed = accessLog()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
export { accessLogSeed };
|
71
03_source/cms_backend/prisma/seeds/AppLog.ts
Normal file
71
03_source/cms_backend/prisma/seeds/AppLog.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
|
||||
const L_ERROR = 0;
|
||||
const L_WARN = 1;
|
||||
const L_INFO = 2;
|
||||
const L_DEBUG = 3;
|
||||
const L_TRACE = 4;
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function appLog() {
|
||||
await prisma.appLog.upsert({
|
||||
where: { id: '0' },
|
||||
update: {},
|
||||
create: {
|
||||
message: 'helloworld',
|
||||
level: L_ERROR,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.appLog.upsert({
|
||||
where: { id: '1' },
|
||||
update: {},
|
||||
create: {
|
||||
message: 'warning message',
|
||||
level: L_WARN,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.appLog.upsert({
|
||||
where: { id: '2' },
|
||||
update: {},
|
||||
create: {
|
||||
message: 'info message',
|
||||
level: L_INFO,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.appLog.upsert({
|
||||
where: { id: '3' },
|
||||
update: {},
|
||||
create: {
|
||||
message: 'debug message',
|
||||
level: L_DEBUG,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.appLog.upsert({
|
||||
where: { id: '4' },
|
||||
update: {},
|
||||
create: {
|
||||
message: 'trace message',
|
||||
level: L_TRACE,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('seed AppLog done');
|
||||
}
|
||||
|
||||
const appLogSeed = appLog()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
export { appLogSeed };
|
@@ -2,12 +2,43 @@ import { PrismaClient } from '@prisma/client';
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function member() {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
[
|
||||
{
|
||||
email: 'tom@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1671656349322-41de944d259b`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'may@exampl.com',
|
||||
avatar: `https://images.unsplash.com/photo-1522075469751-3a6694fb2f61`,
|
||||
sex: 'F',
|
||||
},
|
||||
{
|
||||
email: 'june@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1723867331866-e112500178a4`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'april@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1682089894837-e01e5cb8e471`,
|
||||
sex: 'F',
|
||||
},
|
||||
{
|
||||
email: 'susan@exampl.com',
|
||||
avatar: `https://images.unsplash.com/photo-1485893086445-ed75865251e0`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'peter@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1722945763962-305a5a769cc8`,
|
||||
sex: 'F',
|
||||
},
|
||||
].forEach(async (m, i) => {
|
||||
const john = await prisma.member.upsert({
|
||||
where: { email: `member${i}@example.com` },
|
||||
where: { email: m.email },
|
||||
update: {},
|
||||
create: {
|
||||
email: `member${i}@example.com`,
|
||||
email: m.email,
|
||||
name: `member_${i}`,
|
||||
age: 20 + i,
|
||||
rank: i % 2 ? 'VIP' : 'NON_VIP',
|
||||
@@ -25,11 +56,42 @@ async function member() {
|
||||
self_introduction: 'Get me know me before you love me. Get me know me before you love me.',
|
||||
music: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
pets: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
character: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic']
|
||||
}
|
||||
character: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
avatar: m.avatar,
|
||||
sex: m.sex,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const john = await prisma.member.upsert({
|
||||
where: { email: `member${i}@example.com` },
|
||||
update: {},
|
||||
create: {
|
||||
email: `member${i}@example.com`,
|
||||
name: `member_${i}`,
|
||||
age: 20 + i,
|
||||
rank: i % 2 ? 'VIP' : 'NON_VIP',
|
||||
verified: i % 3 ? 'NOT_VERIFIED' : 'VERIFIED',
|
||||
hobbies: ['fishing', 'basketball', 'piano'],
|
||||
distance: `${40 + Math.random() * 40}km`,
|
||||
location_area: 'Sai Kung',
|
||||
greetings: 'Hi, I am ',
|
||||
gender: 'man',
|
||||
tall_cm: 172 + Math.random() * 10,
|
||||
weight_kg: 60 + Math.random() * 50,
|
||||
occupation: 'doctor',
|
||||
language: ['English', 'French', 'Chinese'],
|
||||
education: ['Degree of Computer'],
|
||||
self_introduction: 'Get me know me before you love me. Get me know me before you love me.',
|
||||
music: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
pets: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
character: ['Classic', 'Classic', 'Classic', 'Classic', 'Classic', 'Classic'],
|
||||
avatar: '',
|
||||
sex: i % 2 ? 'M' : 'F',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log('seed member done');
|
||||
}
|
||||
|
||||
|
@@ -78,11 +78,12 @@ 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`,
|
||||
//
|
||||
event: (index: number) => `${CONFIG.basePath}/assets/images/m-product/product-${index + 1}.webp`,
|
||||
},
|
||||
//
|
||||
eventName: (index: number) => _eventNames[index],
|
||||
};
|
||||
|
277
03_source/cms_backend/prisma/seeds/eventItem.ts
Normal file
277
03_source/cms_backend/prisma/seeds/eventItem.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
import { _mock } from './_mock';
|
||||
import { _tags } from './assets';
|
||||
|
||||
import { PrismaClient, EventReview } from '@prisma/client';
|
||||
import { _eventsReview } from './eventReview';
|
||||
import { CONFIG } from './global-config';
|
||||
|
||||
import _ from 'lodash';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const COLORS = ['#FF4842', '#1890FF', '#FFC0CB', '#00AB55', '#FFC107', '#7F00FF', '#000000', '#FFFFFF'];
|
||||
|
||||
const DESCRIPTION = `
|
||||
<h6>Specifications</h6>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Category</td>
|
||||
<td>Mobile</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Manufacturer</td>
|
||||
<td>Apple</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Warranty</td>
|
||||
<td>12 Months</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Serial number</td>
|
||||
<td>358607726380311</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Ships from</td>
|
||||
<td>United States</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h6>Event details</h6>
|
||||
<ul>
|
||||
<li>
|
||||
<p>The foam sockliner feels soft and comfortable</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Pull tab</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Not intended for use as Personal Protective Equipment</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Colour Shown: White/Black/Oxygen Purple/Action Grape</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Style: 921826-109</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Country/Region of Origin: China</p>
|
||||
</li>
|
||||
</ul>
|
||||
<h6>Benefits</h6>
|
||||
<ul>
|
||||
<li>
|
||||
<p>Mesh and synthetic materials on the upper keep the fluid look of the OG while adding comfort</p>
|
||||
and durability.
|
||||
</li>
|
||||
<li>
|
||||
<p>Originally designed for performance running, the full-length Max Air unit adds soft, comfortable cushio</p>
|
||||
ning underfoot.
|
||||
</li>
|
||||
<li>
|
||||
<p>The foam midsole feels springy and soft.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>The rubber outsole adds traction and durability.</p>
|
||||
</li>
|
||||
</ul>
|
||||
<h6>Delivery and returns</h6>
|
||||
<p>Your order of $200 or more gets free standard delivery.</p>
|
||||
<ul>
|
||||
<li>
|
||||
<p>Standard delivered 4-5 Business Days</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Express delivered 2-4 Business Days</p>
|
||||
</li>
|
||||
</ul>
|
||||
<p>Orders are processed and delivered Monday-Friday (excluding public holidays)</p>
|
||||
|
||||
`;
|
||||
|
||||
const getColorSliceForIndex = (index: number) => {
|
||||
if (index === 0) return COLORS.slice(0, 2);
|
||||
if (index === 1) return COLORS.slice(1, 3);
|
||||
if (index === 2) return COLORS.slice(2, 4);
|
||||
if (index === 3) return COLORS.slice(3, 6);
|
||||
if (index === 4 || index === 16 || index === 19) return COLORS.slice(4, 6);
|
||||
if (index === 5 || index === 17) return COLORS.slice(5, 6);
|
||||
if (index === 6 || index === 18) return COLORS.slice(0, 2);
|
||||
if (index === 7) return COLORS.slice(4, 6);
|
||||
if (index === 8) return COLORS.slice(2, 4);
|
||||
if (index === 9 || index === 11) return COLORS.slice(2, 6);
|
||||
if (index === 10) return COLORS.slice(3, 6);
|
||||
if (index === 12) return COLORS.slice(2, 7);
|
||||
if (index === 13) return COLORS.slice(4, 7);
|
||||
if (index === 14) return COLORS.slice(0, 2);
|
||||
if (index === 15) return COLORS.slice(5, 8);
|
||||
return COLORS.slice(2, 6); // Default case
|
||||
};
|
||||
|
||||
const generateAttachments = () => Array.from({ length: 20 }, (_, index) => _mock.image.event(index));
|
||||
|
||||
const generateReviews = () => {
|
||||
const attachments = generateAttachments();
|
||||
};
|
||||
|
||||
const generateRatings = () =>
|
||||
Array.from({ length: 5 }, (_, index) => ({
|
||||
name: `${index + 1} Star`,
|
||||
starCount: _mock.number.nativeL(index),
|
||||
reviewCount: _mock.number.nativeL(index + 1),
|
||||
}));
|
||||
|
||||
const generateImages = () => Array.from({ length: 8 }, (_, index) => _mock.image.event(index));
|
||||
|
||||
const _events = () =>
|
||||
Array.from({ length: 2 }, (_, index) => {
|
||||
const reviews = generateReviews();
|
||||
const images = generateImages();
|
||||
const ratings = generateRatings();
|
||||
//
|
||||
const publish = index % 3 ? 'published' : 'draft';
|
||||
|
||||
const category = (index % 2 && 'Shose') || (index % 3 && 'Apparel') || 'Accessories';
|
||||
|
||||
const gender = (index % 2 && ['Men']) || (index % 3 && ['Women', 'Kids']) || ['Kids'];
|
||||
|
||||
const available = (index % 2 && 72) || (index % 3 && 10) || 0;
|
||||
|
||||
const inventoryType = (index % 2 && 'in stock') || (index % 3 && 'low stock') || 'out of stock';
|
||||
|
||||
const priceSale = index % 3 ? undefined : _mock.number.price(index);
|
||||
|
||||
return {
|
||||
id: _mock.id(index).toString(),
|
||||
sku: `WW75K521${index}YW/SV`,
|
||||
name: _mock.eventName(index),
|
||||
gender,
|
||||
images,
|
||||
reviews,
|
||||
publish,
|
||||
ratings,
|
||||
category,
|
||||
available,
|
||||
priceSale,
|
||||
taxes: 10,
|
||||
quantity: 80,
|
||||
inventoryType,
|
||||
tags: _tags.slice(0, 5),
|
||||
code: `38BEE27${index}`,
|
||||
description: DESCRIPTION,
|
||||
createdAt: _mock.time(index),
|
||||
price: _mock.number.price(index),
|
||||
coverUrl: _mock.image.event(index),
|
||||
colors: getColorSliceForIndex(index),
|
||||
totalRatings: _mock.number.rating(index),
|
||||
totalSold: _mock.number.nativeM(index + 1),
|
||||
totalReviews: _mock.number.nativeL(index + 1),
|
||||
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.',
|
||||
};
|
||||
});
|
||||
|
||||
const memberList = (num_of_member: number) =>
|
||||
_.shuffle([
|
||||
{
|
||||
email: 'tom@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1671656349322-41de944d259b`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'may@exampl.com',
|
||||
avatar: `https://images.unsplash.com/photo-1522075469751-3a6694fb2f61`,
|
||||
sex: 'F',
|
||||
},
|
||||
{
|
||||
email: 'june@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1723867331866-e112500178a4`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'april@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1682089894837-e01e5cb8e471`,
|
||||
sex: 'F',
|
||||
},
|
||||
{
|
||||
email: 'susan@exampl.com',
|
||||
avatar: `https://images.unsplash.com/photo-1485893086445-ed75865251e0`,
|
||||
sex: 'M',
|
||||
},
|
||||
{
|
||||
email: 'peter@exampl.com',
|
||||
avatar: `https://plus.unsplash.com/premium_photo-1722945763962-305a5a769cc8`,
|
||||
sex: 'F',
|
||||
},
|
||||
]).slice(0, num_of_member);
|
||||
|
||||
async function eventItem() {
|
||||
const temp_events = _events();
|
||||
|
||||
for (let i = 0; i < temp_events.length; i++) {
|
||||
const temp_pr = _eventsReview();
|
||||
|
||||
const temp = await prisma.eventItem.upsert({
|
||||
where: { id: temp_events[i].id.toString() },
|
||||
update: {},
|
||||
create: {
|
||||
id: temp_events[i].id,
|
||||
//
|
||||
name: temp_events[i].name,
|
||||
code: temp_events[i].code,
|
||||
price: temp_events[i].price,
|
||||
taxes: temp_events[i].taxes,
|
||||
tags: temp_events[i].tags,
|
||||
sizes: temp_events[i].sizes,
|
||||
publish: temp_events[i].publish,
|
||||
gender: temp_events[i].gender,
|
||||
coverUrl: temp_events[i].coverUrl,
|
||||
images: temp_events[i].images,
|
||||
colors: temp_events[i].colors,
|
||||
quantity: temp_events[i].quantity,
|
||||
category: temp_events[i].category,
|
||||
available: temp_events[i].available,
|
||||
totalSold: temp_events[i].totalSold,
|
||||
description: temp_events[i].description,
|
||||
totalRatings: temp_events[i].totalRatings,
|
||||
totalReviews: temp_events[i].totalReviews,
|
||||
inventoryType: temp_events[i].inventoryType,
|
||||
subDescription: temp_events[i].subDescription,
|
||||
priceSale: temp_events[i].priceSale,
|
||||
newLabel: temp_events[i].newLabel,
|
||||
saleLabel: temp_events[i].saleLabel,
|
||||
ratings: temp_events[i].ratings,
|
||||
// review: { create: temp_pr },
|
||||
reviews: { create: temp_pr },
|
||||
sku: temp_events[i].sku,
|
||||
//
|
||||
eventDate: new Date(_mock.time(i)),
|
||||
title: temp_events[i].name,
|
||||
currency: 'HKD',
|
||||
duration_m: 120,
|
||||
ageBottom: 18,
|
||||
ageTop: 60,
|
||||
location: 'Hong Kong',
|
||||
avatar: temp_events[i].images,
|
||||
//
|
||||
joinMembers: memberList(5 - i),
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log('seed eventItem done');
|
||||
}
|
||||
|
||||
const EventItem = eventItem()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
export { EventItem as EventItemSeed };
|
61
03_source/cms_backend/prisma/seeds/eventReview.ts
Normal file
61
03_source/cms_backend/prisma/seeds/eventReview.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { _mock } from './_mock';
|
||||
import { _tags } from './assets';
|
||||
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const generateAttachments = () => Array.from({ length: 20 }, (_, index) => _mock.image.event(index));
|
||||
|
||||
const generateReviews = () => {
|
||||
const attachments = generateAttachments();
|
||||
|
||||
return Array.from({ length: 8 }, (_, index) => ({
|
||||
// id: _mock.id(index),
|
||||
name: _mock.fullName(index),
|
||||
postedAt: _mock.time(index),
|
||||
comment: _mock.sentence(index),
|
||||
isPurchased: _mock.boolean(index),
|
||||
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)) || [],
|
||||
}));
|
||||
};
|
||||
|
||||
export const _eventsReview = () => {
|
||||
return generateReviews();
|
||||
};
|
||||
|
||||
async function eventReview() {
|
||||
const temp_pr = _eventsReview();
|
||||
|
||||
for (let i = 0; i < temp_pr.length; i++) {
|
||||
const temp = await prisma.eventReview.upsert({
|
||||
where: { id: i.toString() },
|
||||
update: {},
|
||||
create: {
|
||||
name: temp_pr[i].name,
|
||||
rating: temp_pr[i].rating,
|
||||
comment: temp_pr[i].comment,
|
||||
helpful: temp_pr[i].helpful,
|
||||
avatarUrl: temp_pr[i].avatarUrl,
|
||||
isPurchased: temp_pr[i].isPurchased,
|
||||
attachments: temp_pr[i].attachments,
|
||||
postedAt: temp_pr[i].postedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log('seed eventReview done');
|
||||
}
|
||||
|
||||
const EventReview = eventReview()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
export { EventReview as EventReviewSeed };
|
@@ -55,7 +55,7 @@ async function invoiceItem() {
|
||||
invoiceTo: _addressBooks[index + 1],
|
||||
sent: _mock.number.nativeS(index),
|
||||
dueDate: new Date(fAdd({ days: index + 15, hours: index })),
|
||||
createdDate: new Date(fAdd({ days: index + 15, hours: index })),
|
||||
createDate: new Date(fAdd({ days: index + 15, hours: index })),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
@@ -4,16 +4,7 @@ import { _tags } from './assets';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
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>
|
||||
@@ -113,8 +104,7 @@ const getColorSliceForIndex = (index: number) => {
|
||||
return COLORS.slice(2, 6); // Default case
|
||||
};
|
||||
|
||||
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();
|
||||
@@ -128,11 +118,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)) || [],
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -140,7 +126,7 @@ const generateRatings = () =>
|
||||
Array.from({ length: 5 }, (_, index) => ({
|
||||
name: `${index + 1} Star`,
|
||||
starCount: _mock.number.nativeL(index),
|
||||
reviewCount: _mock.number.nativeL(index + 1)
|
||||
reviewCount: _mock.number.nativeL(index + 1),
|
||||
}));
|
||||
|
||||
const generateImages = () => Array.from({ length: 8 }, (_, index) => _mock.image.product(index));
|
||||
@@ -164,8 +150,8 @@ async function productReview() {
|
||||
avatarUrl: temp_pr[i].avatarUrl,
|
||||
isPurchased: temp_pr[i].isPurchased,
|
||||
attachments: temp_pr[i].attachments,
|
||||
postedAt: temp_pr[i].postedAt
|
||||
}
|
||||
postedAt: temp_pr[i].postedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
console.log('seed productReview done');
|
||||
|
@@ -8,8 +8,9 @@ async function superuser() {
|
||||
create: {
|
||||
email: 'admin1@123.com',
|
||||
name: 'Admin1',
|
||||
password: 'Aa12345678'
|
||||
}
|
||||
password: 'Aa12345678',
|
||||
admin: true,
|
||||
},
|
||||
});
|
||||
|
||||
// swagger test
|
||||
@@ -19,8 +20,9 @@ async function superuser() {
|
||||
create: {
|
||||
email: 'fake@example.com',
|
||||
name: 'swagger user',
|
||||
password: 'password1'
|
||||
}
|
||||
password: 'password1',
|
||||
admin: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('seed superuser done');
|
||||
|
@@ -9,16 +9,29 @@ async function user() {
|
||||
email: 'alice@prisma.io',
|
||||
name: 'Alice',
|
||||
password: 'Aa12345678',
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
const bob = await prisma.user.upsert({
|
||||
await prisma.user.upsert({
|
||||
where: { email: 'demo@minimals.cc' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'demo@minimals.cc',
|
||||
name: 'Demo',
|
||||
password: '@2Minimal',
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.user.upsert({
|
||||
where: { email: 'bob@prisma.io' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'bob@prisma.io',
|
||||
name: 'Bob',
|
||||
password: 'Aa12345678',
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
console.log('seed user done');
|
||||
|
@@ -39,10 +39,12 @@ async function userItem() {
|
||||
//
|
||||
username: 'admin@123.com',
|
||||
password: await generateHash('Aa1234567'),
|
||||
//
|
||||
isAdmin: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (let i = 1; i < 20; i++) {
|
||||
for (let i = 1; i < 3; i++) {
|
||||
const CJK_LOCALES = {
|
||||
en: enFaker,
|
||||
zh: zhFaker,
|
||||
@@ -77,6 +79,8 @@ async function userItem() {
|
||||
//
|
||||
username: randomFaker.internet.username(),
|
||||
password: await generateHash('Abc1234!'),
|
||||
//
|
||||
isAdmin: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ import { _mock } from 'src/_mock';
|
||||
|
||||
export const JWT_SECRET = 'minimal-secret-key';
|
||||
|
||||
export const JWT_EXPIRES_IN = '3 days';
|
||||
export const JWT_EXPIRES_IN = '14 days';
|
||||
|
||||
export const _users = [
|
||||
{
|
||||
|
24
03_source/cms_backend/src/app/api/AccessLog/_GUIDELINES.md
Normal file
24
03_source/cms_backend/src/app/api/AccessLog/_GUIDELINES.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# GUIDELINE
|
||||
|
||||
- this is a AppLog api endpoint
|
||||
- this is a demo to handle AppLog record
|
||||
- use single file for single db table/collection only
|
||||
|
||||
## `route.ts`
|
||||
|
||||
`route.ts` - handle `GET`, `POST`, `PUT`, `DELETE`
|
||||
`detail/route.ts` - handle `GET` request of specific `AppLog` by id
|
||||
|
||||
## `test.http`
|
||||
|
||||
store test request
|
||||
|
||||
## `../../services/AppLog.service.ts`
|
||||
|
||||
AppLog schema CRUD handler
|
||||
|
||||
`listAppLogs` - list AppLog record
|
||||
`getAppLog` - get AppLog record by id
|
||||
`createNewAppLog` - create AppLog record
|
||||
`updateAppLog` - update AppLog record by id
|
||||
`deleteAppLog` - delete AppLog record by id
|
38
03_source/cms_backend/src/app/api/AccessLog/detail/route.ts
Normal file
38
03_source/cms_backend/src/app/api/AccessLog/detail/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
// src/app/api/AccessLog/detail/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// Get single AccessLog record detail
|
||||
//
|
||||
// RULES:
|
||||
// - Return complete AccessLog details
|
||||
//
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { AccessLogService } from '../../../../modules/AccessLog/AccessLog.service';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
**************************************
|
||||
* GET - Get AccessLog details
|
||||
**************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// RULES: accessLogId must exist
|
||||
const accessLogId = searchParams.get('accessLogId');
|
||||
if (!accessLogId) return response({ message: 'accessLogId is required!' }, STATUS.BAD_REQUEST);
|
||||
|
||||
const accessLog = await AccessLogService.findById(accessLogId);
|
||||
|
||||
if (!accessLog) return response({ message: 'AccessLog not found!' }, STATUS.NOT_FOUND);
|
||||
|
||||
return response({ accessLog }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AccessLog - Get details', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,7 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/AppLog/detail?appLogId=e1bb8e4a-da37-4dbc-b8f2-9ad233a102ad
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/AppLog/detail?start=2025-01-01&end=2025-12-31
|
76
03_source/cms_backend/src/app/api/AccessLog/route.ts
Normal file
76
03_source/cms_backend/src/app/api/AccessLog/route.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { listAccessLogs } from 'src/app/services/AccessLog.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const result = await listAccessLogs();
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AccessLog - Get all', error);
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// ***************************************
|
||||
// * POST - create AccessLog
|
||||
// ***************************************
|
||||
// */
|
||||
// export async function POST(req: NextRequest) {
|
||||
// const { data } = await req.json();
|
||||
|
||||
// try {
|
||||
// const createResult = await AccessLogService.create(data);
|
||||
|
||||
// return response(createResult, STATUS.OK);
|
||||
// } catch (error) {
|
||||
// return handleError('AccessLog - Create', error);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// ***************************************
|
||||
// * PUT - update AccessLog
|
||||
// ***************************************
|
||||
// */
|
||||
// export async function PUT(req: NextRequest) {
|
||||
// const { searchParams } = req.nextUrl;
|
||||
// const accessLogId = searchParams.get('accessLogId');
|
||||
|
||||
// const { data } = await req.json();
|
||||
|
||||
// try {
|
||||
// if (!accessLogId) throw new Error('accessLogId cannot be null');
|
||||
|
||||
// const updateResult = await AccessLogService.update(accessLogId, data);
|
||||
|
||||
// return response(updateResult, STATUS.OK);
|
||||
// } catch (error) {
|
||||
// return handleError('AccessLog - Update', error);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// ***************************************
|
||||
// * DELETE - delete AccessLog
|
||||
// ***************************************
|
||||
// */
|
||||
// export async function DELETE(req: NextRequest) {
|
||||
// const { searchParams } = req.nextUrl;
|
||||
// const accessLogId = searchParams.get('accessLogId');
|
||||
|
||||
// try {
|
||||
// if (!accessLogId) throw new Error('accessLogId cannot be null');
|
||||
|
||||
// const deleteResult = await AccessLogService.delete(accessLogId);
|
||||
|
||||
// return response(deleteResult, STATUS.OK);
|
||||
// } catch (error) {
|
||||
// return handleError('AccessLog - Delete', error);
|
||||
// }
|
||||
// }
|
33
03_source/cms_backend/src/app/api/AccessLog/test.http
Normal file
33
03_source/cms_backend/src/app/api/AccessLog/test.http
Normal file
@@ -0,0 +1,33 @@
|
||||
###
|
||||
GET http://localhost:7272/api/AccessLog
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/AccessLog?accessLogId=51f2f5dd-78be-4069-ba29-09d2a5026191
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/AccessLog
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"userId": "user123",
|
||||
"ipAddress": "192.168.1.1",
|
||||
"userAgent": "Mozilla/5.0",
|
||||
"action": "LOGIN",
|
||||
"path": "/api/auth/login",
|
||||
"status": 200
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/AccessLog?accessLogId=51f2f5dd-78be-4069-ba29-09d2a5026191
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"status": 404
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/AccessLog?accessLogId=51f2f5dd-78be-4069-ba29-09d2a5026191
|
24
03_source/cms_backend/src/app/api/AppLog/_GUIDELINES.md
Normal file
24
03_source/cms_backend/src/app/api/AppLog/_GUIDELINES.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# GUIDELINE
|
||||
|
||||
- this is a AppLog api endpoint
|
||||
- this is a demo to handle AppLog record
|
||||
- use single file for single db table/collection only
|
||||
|
||||
## `route.ts`
|
||||
|
||||
`route.ts` - handle `GET`, `POST`, `PUT`, `DELETE`
|
||||
`detail/route.ts` - handle `GET` request of specific `AppLog` by id
|
||||
|
||||
## `test.http`
|
||||
|
||||
store test request
|
||||
|
||||
## `../../services/AppLog.service.ts`
|
||||
|
||||
AppLog schema CRUD handler
|
||||
|
||||
`listAppLogs` - list AppLog record
|
||||
`getAppLog` - get AppLog record by id
|
||||
`createNewAppLog` - create AppLog record
|
||||
`updateAppLog` - update AppLog record by id
|
||||
`deleteAppLog` - delete AppLog record by id
|
39
03_source/cms_backend/src/app/api/AppLog/detail/route.ts
Normal file
39
03_source/cms_backend/src/app/api/AppLog/detail/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
// src/app/api/AppLog/detail/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// Get single AppLog record detail
|
||||
//
|
||||
// RULES:
|
||||
// - Return complete AppLog details
|
||||
//
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
**************************************
|
||||
* GET - Get AppLog details
|
||||
**************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
// Original user details functionality
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// RULES: appLogId must exist
|
||||
const appLogId = searchParams.get('appLogId');
|
||||
if (!appLogId) return response({ message: 'appLogId is required!' }, STATUS.BAD_REQUEST);
|
||||
|
||||
const appLog = await prisma.appLog.findFirst({ where: { id: appLogId } });
|
||||
|
||||
if (!appLog) return response({ message: 'AppLog not found!' }, STATUS.NOT_FOUND);
|
||||
|
||||
return response({ appLog }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AppLog - Get details', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,7 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/AppLog/detail?appLogId=e1bb8e4a-da37-4dbc-b8f2-9ad233a102ad
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/AppLog/detail?start=2025-01-01&end=2025-12-31
|
80
03_source/cms_backend/src/app/api/AppLog/route.ts
Normal file
80
03_source/cms_backend/src/app/api/AppLog/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { listAppLogs, deleteAppLog, updateAppLog, createNewAppLog } from 'src/app/services/AppLog.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const result = await listAppLogs();
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Post - Get latest', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* POST - create AppLog
|
||||
***************************************
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const createResult = await createNewAppLog(data);
|
||||
|
||||
return response(createResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AppLog - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - update AppLog
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const appLogId = searchParams.get('appLogId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!appLogId) throw new Error('appLogId cannot null');
|
||||
const id: number = parseInt(appLogId);
|
||||
|
||||
const updateResult = await updateAppLog(id, data);
|
||||
|
||||
return response(updateResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AppLog - Update', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* DELETE - update AppLog
|
||||
***************************************
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const appLogId = searchParams.get('appLogId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!appLogId) throw new Error('appLogId cannot null');
|
||||
const id: number = parseInt(appLogId);
|
||||
|
||||
const deleteResult = await deleteAppLog(id);
|
||||
|
||||
return response(deleteResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('AppLog - Update', error);
|
||||
}
|
||||
}
|
25
03_source/cms_backend/src/app/api/AppLog/test.http
Normal file
25
03_source/cms_backend/src/app/api/AppLog/test.http
Normal file
@@ -0,0 +1,25 @@
|
||||
###
|
||||
GET http://localhost:7272/api/AppLog
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/AppLog?appLogId=51f2f5dd-78be-4069-ba29-09d2a5026191
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/AppLog?appLogId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data":{"hello": "test"}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/AppLog?appLogId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"hello": "test"}
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/AppLog?appLogId=1
|
@@ -3,12 +3,13 @@ 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';
|
||||
import { JWT_SECRET, JWT_EXPIRES_IN } from 'src/_mock/_auth';
|
||||
import { createAccessLog } from 'src/app/services/AccessLog.service';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* This API is used for demo purpose only
|
||||
* You should use a real database
|
||||
@@ -17,29 +18,36 @@ export const runtime = 'edge';
|
||||
* 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': Object.fromEntries(req.headers.entries()) };
|
||||
|
||||
try {
|
||||
const { email, password } = await req.json();
|
||||
|
||||
const currentUser = _users.find((user) => user.email === email);
|
||||
|
||||
const currentUser = await prisma.user.findFirst({ where: { email } });
|
||||
if (!currentUser) {
|
||||
return response(
|
||||
{ message: 'There is no user corresponding to the email address.' },
|
||||
STATUS.UNAUTHORIZED
|
||||
);
|
||||
await createAccessLog('', `user tried login with email ${email}`, { debug });
|
||||
return response({ message: ERR_USER_NOT_FOUND }, STATUS.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (currentUser?.password !== password) {
|
||||
return response({ message: 'Wrong password' }, STATUS.UNAUTHORIZED);
|
||||
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,
|
||||
});
|
||||
|
||||
return response({ user: currentUser, accessToken }, 200);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
29
03_source/cms_backend/src/app/api/auth/sign-in/test.http
Normal file
29
03_source/cms_backend/src/app/api/auth/sign-in/test.http
Normal file
@@ -0,0 +1,29 @@
|
||||
###
|
||||
# username and password ok
|
||||
POST http://localhost:7272/api/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/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"
|
||||
}
|
@@ -24,10 +24,7 @@ export async function POST(req: NextRequest) {
|
||||
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
|
||||
);
|
||||
return response({ message: 'There already exists an account with the given email address.' }, STATUS.CONFLICT);
|
||||
}
|
||||
|
||||
const newUser = {
|
||||
|
75
03_source/cms_backend/src/app/api/event/createEvent/route.ts
Normal file
75
03_source/cms_backend/src/app/api/event/createEvent/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
// src/app/api/product/createEvent/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 - Events
|
||||
*************************************** */
|
||||
export async function POST(req: NextRequest) {
|
||||
// logger('[Event] list', events.length);
|
||||
const { data } = await req.json();
|
||||
const createForm: CreateEventData = data as unknown as CreateEventData;
|
||||
|
||||
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('Event - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
type CreateEventData = {
|
||||
// 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;
|
||||
// }[];
|
||||
};
|
44
03_source/cms_backend/src/app/api/event/deleteEvent/route.ts
Normal file
44
03_source/cms_backend/src/app/api/event/deleteEvent/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// src/app/api/event/deleteEvent/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// delete 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 prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** **************************************
|
||||
* handle Delete Events
|
||||
*************************************** */
|
||||
export async function DELETE(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// RULES: eventId must exist
|
||||
const eventId = searchParams.get('eventId');
|
||||
if (!eventId) {
|
||||
return response({ message: 'Event ID is required!' }, STATUS.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// NOTE: eventId confirmed exist, run below
|
||||
const event = await prisma.eventItem.delete({ where: { id: eventId } });
|
||||
|
||||
if (!event) {
|
||||
return response({ message: 'Event not found!' }, STATUS.NOT_FOUND);
|
||||
}
|
||||
|
||||
logger('[Event] details', event.id);
|
||||
|
||||
return response({ event }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Event - Get details', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,3 @@
|
||||
###
|
||||
|
||||
DELETE http://localhost:7272/api/event/deleteEvent?eventId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b06
|
47
03_source/cms_backend/src/app/api/event/details/route.ts
Normal file
47
03_source/cms_backend/src/app/api/event/details/route.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
// src/app/api/event/details/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// save event to db by id
|
||||
//
|
||||
// RULES:
|
||||
// T.B.A.
|
||||
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { logger } from 'src/utils/logger';
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** **************************************
|
||||
* GET Event detail
|
||||
*************************************** */
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// RULES: eventId must exist
|
||||
const eventId = searchParams.get('eventId');
|
||||
if (!eventId) {
|
||||
return response({ message: 'Event ID is required!' }, STATUS.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// NOTE: eventId confirmed exist, run below
|
||||
const event = await prisma.eventItem.findFirst({
|
||||
include: { reviews: true },
|
||||
where: { id: eventId },
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
return response({ message: 'Event not found!' }, STATUS.NOT_FOUND);
|
||||
}
|
||||
|
||||
logger('[Event] details', event.id);
|
||||
|
||||
return response({ event }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Event - Get details', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,3 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/event/details?eventId=e99f09a7-dd88-49d5-b1c8-1daf80c2d7b01
|
@@ -0,0 +1,30 @@
|
||||
// src/app/api/event/image/upload/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// handle upload event image
|
||||
//
|
||||
// RULES:
|
||||
// T.B.A.
|
||||
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
// import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** **************************************
|
||||
* GET - Events
|
||||
*************************************** */
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { data } = await req.json();
|
||||
console.log('helloworld');
|
||||
|
||||
return response({ hello: 'world' }, STATUS.OK);
|
||||
} catch (error) {
|
||||
console.log({ hello: 'world' });
|
||||
return handleError('Event - store event image', error);
|
||||
}
|
||||
}
|
22
03_source/cms_backend/src/app/api/event/list/route.ts
Normal file
22
03_source/cms_backend/src/app/api/event/list/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// src/app/api/event/list/route.ts
|
||||
import { logger } from 'src/utils/logger';
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** **************************************
|
||||
* GET - Events
|
||||
*************************************** */
|
||||
export async function GET() {
|
||||
try {
|
||||
const events = await prisma.eventItem.findMany();
|
||||
|
||||
logger('[Event] list', events.length);
|
||||
|
||||
return response({ events }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Event - Get list', error);
|
||||
}
|
||||
}
|
3
03_source/cms_backend/src/app/api/event/list/test.http
Normal file
3
03_source/cms_backend/src/app/api/event/list/test.http
Normal file
@@ -0,0 +1,3 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/event/list
|
129
03_source/cms_backend/src/app/api/event/saveEvent/route.ts
Normal file
129
03_source/cms_backend/src/app/api/event/saveEvent/route.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
// src/app/api/event/saveEvent/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// save event 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 - Events
|
||||
*************************************** */
|
||||
export async function POST(req: NextRequest) {
|
||||
// logger('[Event] list', events.length);
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const events = await prisma.eventItem.updateMany({
|
||||
data: {
|
||||
name: data.name,
|
||||
sku: data.sku,
|
||||
code: data.code,
|
||||
price: data.price,
|
||||
taxes: data.taxes,
|
||||
tags: data.tags,
|
||||
sizes: data.sizes,
|
||||
publish: data.publish,
|
||||
gender: data.gender,
|
||||
coverUrl: data.coverUrl,
|
||||
images: data.images,
|
||||
colors: data.colors,
|
||||
quantity: data.quantity,
|
||||
category: data.category,
|
||||
available: data.available,
|
||||
totalSold: data.totalSold,
|
||||
description: data.description,
|
||||
totalRatings: data.totalRatings,
|
||||
totalReviews: data.totalReviews,
|
||||
inventoryType: data.inventoryType,
|
||||
subDescription: data.subDescription,
|
||||
priceSale: data.priceSale,
|
||||
//
|
||||
newLabel: {
|
||||
content: data.newLabel?.content || '',
|
||||
enabled: data.newLabel?.enabled ?? false,
|
||||
},
|
||||
saleLabel: {
|
||||
content: data.saleLabel?.content || '',
|
||||
enabled: data.saleLabel?.enabled ?? false,
|
||||
},
|
||||
ratings: {
|
||||
set: data.ratings.map((rating: { name: string; starCount: number; reviewCount: number }) => ({
|
||||
name: rating.name,
|
||||
starCount: rating.starCount,
|
||||
reviewCount: rating.reviewCount,
|
||||
})),
|
||||
},
|
||||
},
|
||||
where: { id: data.id },
|
||||
});
|
||||
|
||||
return response({ data }, STATUS.OK);
|
||||
} catch (error) {
|
||||
console.log({ data });
|
||||
return handleError('Event - Get list', error);
|
||||
}
|
||||
}
|
||||
|
||||
export type IEventItem = {
|
||||
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: IEventReview[];
|
||||
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 IEventReview = {
|
||||
id: string;
|
||||
name: string;
|
||||
rating: number;
|
||||
comment: string;
|
||||
helpful: number;
|
||||
avatarUrl: string;
|
||||
postedAt: IDateValue;
|
||||
isPurchased: boolean;
|
||||
attachments?: string[];
|
||||
};
|
35
03_source/cms_backend/src/app/api/event/search/route.ts
Normal file
35
03_source/cms_backend/src/app/api/event/search/route.ts
Normal 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 { _events } from 'src/_mock/_event';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/** **************************************
|
||||
* GET - Search events
|
||||
*************************************** */
|
||||
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 events = _events();
|
||||
|
||||
// Accept search by name or sku
|
||||
const results = events.filter(({ name, sku }) => name.toLowerCase().includes(query) || sku?.toLowerCase().includes(query));
|
||||
|
||||
logger('[Event] search-results', results.length);
|
||||
|
||||
return response({ results }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Event - Get search', error);
|
||||
}
|
||||
}
|
23
03_source/cms_backend/src/app/api/helloworld/_GUIDELINES.md
Normal file
23
03_source/cms_backend/src/app/api/helloworld/_GUIDELINES.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# GUIDELINE
|
||||
|
||||
- this is a helloworld api endpoint
|
||||
- this is a demo to handle helloworld record
|
||||
- use single file for single db table/collection only
|
||||
|
||||
## `route.ts`
|
||||
|
||||
handle `GET`, `POST`, `PUT`, `DELETE`
|
||||
|
||||
## `test.http`
|
||||
|
||||
store test request
|
||||
|
||||
## `../../services/helloworld.service.ts`
|
||||
|
||||
helloworld schema CRUD handler
|
||||
|
||||
`listHelloworlds` - list helloworld record
|
||||
`getHelloworld` - get helloworld record by id
|
||||
`createNewHelloworld` - create helloworld record
|
||||
`updateHelloworld` - update helloworld record by id
|
||||
`deleteHelloworld` - delete helloworld record by id
|
39
03_source/cms_backend/src/app/api/helloworld/detail/route.ts
Normal file
39
03_source/cms_backend/src/app/api/helloworld/detail/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
// src/app/api/helloworld/detail/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// Get single helloworld record detail
|
||||
//
|
||||
// RULES:
|
||||
// - For helloworld requests, return simple response
|
||||
//
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
**************************************
|
||||
* GET - Handle both helloworld and user details
|
||||
**************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
// Original user details functionality
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// RULES: helloworldId must exist
|
||||
const helloworldId = searchParams.get('helloworldId');
|
||||
if (!helloworldId) return response({ message: 'helloworldId is required!' }, STATUS.BAD_REQUEST);
|
||||
|
||||
const helloworld = await prisma.userItem.findFirst({ where: { id: helloworldId } });
|
||||
|
||||
if (!helloworld) return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
|
||||
|
||||
return response({ helloworld }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Product - Get details', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,4 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/helloworld/details?helloworldId=1165ce3a-29b8-4e1a-9148-1ae08d7e8e01
|
||||
|
@@ -1,16 +0,0 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const products = await prisma.productItem.findMany();
|
||||
console.log({ products });
|
||||
|
||||
return response({ products }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Post - Get latest', error);
|
||||
}
|
||||
}
|
@@ -2,14 +2,84 @@ import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../lib/prisma';
|
||||
import { listHelloworlds, deleteHelloworld, updateHelloworld, createNewHelloworld } from 'src/app/services/helloworld.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* GET - list all Helloworlds
|
||||
***************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const users = await prisma.user.findMany();
|
||||
const result = await listHelloworlds();
|
||||
|
||||
return response({ users }, STATUS.OK);
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Post - Get latest', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* POST - create Helloworld
|
||||
***************************************
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const createResult = await createNewHelloworld(data);
|
||||
|
||||
return response(createResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Helloworld - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - update Helloworld
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const helloworldId = searchParams.get('helloworldId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!helloworldId) throw new Error('helloworldId cannot null');
|
||||
const id: number = parseInt(helloworldId);
|
||||
|
||||
const updateResult = await updateHelloworld(id, data);
|
||||
|
||||
return response(updateResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Helloworld - Update', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* DELETE - update Helloworld
|
||||
***************************************
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const helloworldId = searchParams.get('helloworldId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!helloworldId) throw new Error('helloworldId cannot null');
|
||||
const id: number = parseInt(helloworldId);
|
||||
|
||||
const deleteResult = await deleteHelloworld(id);
|
||||
|
||||
return response(deleteResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Helloworld - Update', error);
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,25 @@
|
||||
###
|
||||
|
||||
GET http://localhost:7272/api/helloworld
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/helloworld?helloworldId=1
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/helloworld?helloworldId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data":{"hello": "hell"}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/helloworld?helloworldId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"hello": "hell"}
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/helloworld?helloworldId=1
|
||||
|
@@ -52,7 +52,7 @@ content-type: application/json
|
||||
"phoneNumber": "+44 20 7946 0958"
|
||||
},
|
||||
"sent": 10,
|
||||
"createdDate": "2025-06-15T17:07:24+08:00",
|
||||
"createDate": "2025-06-15T17:07:24+08:00",
|
||||
"dueDate": "2025-06-15T17:07:24+08:00"
|
||||
}
|
||||
}
|
||||
|
23
03_source/cms_backend/src/app/api/order/_GUIDELINES.md
Normal file
23
03_source/cms_backend/src/app/api/order/_GUIDELINES.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# GUIDELINE
|
||||
|
||||
- this is a helloworld api endpoint
|
||||
- this is a demo to handle helloworld record
|
||||
- use single file for single db table/collection only
|
||||
|
||||
## `route.ts`
|
||||
|
||||
handle `GET`, `POST`, `PUT`, `DELETE`
|
||||
|
||||
## `test.http`
|
||||
|
||||
store test request
|
||||
|
||||
## `../../services/helloworld.service.ts`
|
||||
|
||||
helloworld schema CRUD handler
|
||||
|
||||
`listHelloworlds` - list helloworld record
|
||||
`getHelloworld` - get helloworld record by id
|
||||
`createNewHelloworld` - create helloworld record
|
||||
`updateHelloworld` - update helloworld record by id
|
||||
`deleteHelloworld` - delete helloworld record by id
|
76
03_source/cms_backend/src/app/api/order/route.ts
Normal file
76
03_source/cms_backend/src/app/api/order/route.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { listOrders, deleteOrder, updateOrder, createOrder } from 'src/app/services/order.service';
|
||||
|
||||
/**
|
||||
**************************************
|
||||
* GET - Order
|
||||
***************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const orders = await listOrders();
|
||||
return response(orders, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Order - Get list', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* POST - Create Order
|
||||
***************************************
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const order = await createOrder(data);
|
||||
return response(order, STATUS.CREATED);
|
||||
} catch (error) {
|
||||
return handleError('Order - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - Update Order
|
||||
***************************************
|
||||
*/
|
||||
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 id: number = parseInt(orderId);
|
||||
|
||||
const updatedOrder = await updateOrder(id, data);
|
||||
return response(updatedOrder, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Order - Update', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* DELETE - Delete Order
|
||||
***************************************
|
||||
*/
|
||||
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');
|
||||
const id: number = parseInt(orderId);
|
||||
|
||||
await deleteOrder(id);
|
||||
return response({ success: true }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Order - Delete', error);
|
||||
}
|
||||
}
|
32
03_source/cms_backend/src/app/api/order/test.http
Normal file
32
03_source/cms_backend/src/app/api/order/test.http
Normal file
@@ -0,0 +1,32 @@
|
||||
###
|
||||
GET http://localhost:7272/api/order
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/order?orderId=1
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/order
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"product": "Sample Product",
|
||||
"quantity": 1,
|
||||
"price": 99.99
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/order?orderId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"product": "Updated Product",
|
||||
"quantity": 2,
|
||||
"price": 199.98
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/order?orderId=1
|
74
03_source/cms_backend/src/app/api/product/route.ts
Normal file
74
03_source/cms_backend/src/app/api/product/route.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { listProducts, deleteProduct, updateProduct, createProduct } from 'src/app/services/product.service';
|
||||
|
||||
/**
|
||||
**************************************
|
||||
* GET - Product
|
||||
***************************************
|
||||
*/
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const products = await listProducts();
|
||||
return response(products, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Product - Get list', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* POST - Create Product
|
||||
***************************************
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const product = await createProduct(data);
|
||||
return response(product, STATUS.CREATED);
|
||||
} catch (error) {
|
||||
return handleError('Product - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - Update Product
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const productId = searchParams.get('productId');
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!productId) throw new Error('productId cannot be null');
|
||||
|
||||
const result = await updateProduct(productId, data);
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Product - Update', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* DELETE - Delete Product
|
||||
***************************************
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const productId = searchParams.get('productId');
|
||||
|
||||
try {
|
||||
if (!productId) throw new Error('productId cannot be null');
|
||||
|
||||
await deleteProduct(productId);
|
||||
return response({ success: true }, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Product - Delete', error);
|
||||
}
|
||||
}
|
33
03_source/cms_backend/src/app/api/product/test.http
Normal file
33
03_source/cms_backend/src/app/api/product/test.http
Normal file
@@ -0,0 +1,33 @@
|
||||
###
|
||||
GET http://localhost:7272/api/product
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/product?productId=1
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/product
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"sku": "PROD-001",
|
||||
"name": "Premium Product",
|
||||
"price": 99.99,
|
||||
"quantity": 100,
|
||||
"category": "Electronics",
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/product?productId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {
|
||||
"price": 89.99,
|
||||
"quantity": 95
|
||||
}
|
||||
}
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/product?productId=1
|
@@ -0,0 +1,36 @@
|
||||
// src/app/api/user/promoteToAdmin/route.ts
|
||||
//
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { changeToAdmin } from 'src/app/services/userItem.service';
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - promote user to admin
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// userId, the userId going to be admin
|
||||
// {data: requestUserId}, the userId sending request to promote admin
|
||||
// the requestUserId should be a admin admin already
|
||||
|
||||
const userId = searchParams.get('userId');
|
||||
const {
|
||||
data: { requestUserId },
|
||||
} = await req.json();
|
||||
|
||||
try {
|
||||
if (!userId) return response('userId cannot be null', STATUS.BAD_REQUEST);
|
||||
if (!requestUserId) return response('requestUserId cannot be null', STATUS.BAD_REQUEST);
|
||||
|
||||
const result = await changeToAdmin(userId, requestUserId);
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('promote to admin', JSON.stringify(error));
|
||||
}
|
||||
}
|
@@ -0,0 +1,33 @@
|
||||
# step 1 check not a admin
|
||||
###
|
||||
GET http://localhost:7272/api/user/details?userId=00b8b53b-dfe6-4b07-8d23-0dc9f75e7a2c
|
||||
|
||||
# step 1 check not a admin
|
||||
###
|
||||
GET http://localhost:7272/api/user/details?userId=5e072d02-919c-49c4-98b4-9659b8eff231
|
||||
|
||||
|
||||
# step 2 request to change admin
|
||||
###
|
||||
PUT http://localhost:7272/api/user/changeToAdmin?userId=00b8b53b-dfe6-4b07-8d23-0dc9f75e7a2c
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"requestUserId": "5e072d02-919c-49c4-98b4-9659b8eff231"}
|
||||
}
|
||||
|
||||
|
||||
|
||||
# step 2 request to change user
|
||||
###
|
||||
PUT http://localhost:7272/api/user/changeToUser?userId=00b8b53b-dfe6-4b07-8d23-0dc9f75e7a2c
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"requestUserId": "5e072d02-919c-49c4-98b4-9659b8eff231"}
|
||||
}
|
||||
|
||||
|
||||
# step 3 it is now admin
|
||||
###
|
||||
GET http://localhost:7272/api/user/details?userId=00b8b53b-dfe6-4b07-8d23-0dc9f75e7a2c
|
36
03_source/cms_backend/src/app/api/user/changeToUser/route.ts
Normal file
36
03_source/cms_backend/src/app/api/user/changeToUser/route.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
// src/app/api/user/changeToUser/route.ts
|
||||
//
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { changeToUser } from 'src/app/services/userItem.service';
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - change admin back to regular user
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
|
||||
// userId, the userId going to be changed to regular user
|
||||
// {data: requestUserId}, the userId sending request to change role
|
||||
// the requestUserId should be an admin
|
||||
|
||||
const userId = searchParams.get('userId');
|
||||
const {
|
||||
data: { requestUserId },
|
||||
} = await req.json();
|
||||
|
||||
try {
|
||||
if (!userId) throw new Error('userId cannot be null');
|
||||
if (!requestUserId) throw new Error('requestUserId cannot be null');
|
||||
|
||||
const result = await changeToUser(userId, requestUserId);
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('change to regular user', JSON.stringify(error));
|
||||
}
|
||||
}
|
@@ -0,0 +1,17 @@
|
||||
###
|
||||
PUT http://localhost:7272/api/user/changeToUser?userId=cmbfx38e30000ssek6ufjewcp
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"requestUserId": "cmbfx38kk000esseka9qo8lpt"}
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user/changeToUser?userId=
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user?userId=cmbfx38e30000ssek6ufjewcp
|
21
03_source/cms_backend/src/app/api/user/checkAdmin/route.ts
Normal file
21
03_source/cms_backend/src/app/api/user/checkAdmin/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { isAdmin } from 'src/app/services/userItem.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const userId = searchParams.get('userId');
|
||||
|
||||
try {
|
||||
if (!userId) throw new Error('userId cannot be null');
|
||||
const result = await isAdmin(userId);
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Post - Get latest', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,9 @@
|
||||
###
|
||||
GET http://localhost:7272/api/user/checkAdmin?userId=cmbfx38ey0001ssek5pr05o70
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user/checkAdmin?userId=cmbfvonkx000411ykuah8pp8s
|
||||
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user/checkAdmin
|
@@ -1,4 +1,4 @@
|
||||
// src/app/api/product/details/route.ts
|
||||
// src/app/api/user/details/route.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// read user from db by id
|
||||
@@ -24,9 +24,7 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
// RULES: userId must exist
|
||||
const userId = searchParams.get('userId');
|
||||
if (!userId) {
|
||||
return response({ message: 'userId is required!' }, STATUS.BAD_REQUEST);
|
||||
}
|
||||
if (!userId) return response({ message: 'userId is required!' }, STATUS.BAD_REQUEST);
|
||||
|
||||
// NOTE: userId confirmed exist, run below
|
||||
const user = await prisma.userItem.findFirst({
|
||||
@@ -34,9 +32,7 @@ export async function GET(req: NextRequest) {
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
|
||||
}
|
||||
if (!user) return response({ message: 'User not found!' }, STATUS.NOT_FOUND);
|
||||
|
||||
logger('[User] details', user.id);
|
||||
|
||||
|
21
03_source/cms_backend/src/app/api/user/helloworld/route.ts
Normal file
21
03_source/cms_backend/src/app/api/user/helloworld/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { isAdmin } from 'src/app/services/userItem.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const userId = searchParams.get('userId');
|
||||
|
||||
try {
|
||||
if (!userId) throw new Error('userId cannot be null');
|
||||
const result = await isAdmin(userId);
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('Post - Get latest', error);
|
||||
}
|
||||
}
|
@@ -0,0 +1,2 @@
|
||||
###
|
||||
GET http://localhost:7272/api/user
|
@@ -1,17 +1,20 @@
|
||||
// src/app/api/product/list/route.ts
|
||||
//
|
||||
import { logger } from 'src/utils/logger';
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { listUsers } from 'src/app/services/userItem.service';
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** **************************************
|
||||
/**
|
||||
***************************************
|
||||
* GET - Products
|
||||
*************************************** */
|
||||
***************************************
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const users = await prisma.userItem.findMany();
|
||||
const users = await listUsers();
|
||||
|
||||
logger('[User] list', users.length);
|
||||
|
||||
|
80
03_source/cms_backend/src/app/api/user/route.ts
Normal file
80
03_source/cms_backend/src/app/api/user/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { STATUS, response, handleError } from 'src/utils/response';
|
||||
|
||||
import { listUsers, deleteUser, updateUser, createNewUser } from 'src/app/services/userItem.service';
|
||||
|
||||
// import prisma from '../../lib/prisma';
|
||||
|
||||
export async function GET(req: NextRequest, res: NextResponse) {
|
||||
try {
|
||||
const result = await listUsers();
|
||||
|
||||
return response(result, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('User - Get latest', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* POST - create User
|
||||
***************************************
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
const createResult = await createNewUser(data);
|
||||
|
||||
return response(createResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('User - Create', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* PUT - update User
|
||||
***************************************
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const userId = searchParams.get('userId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!userId) throw new Error('userId cannot null');
|
||||
const id: number = parseInt(userId);
|
||||
|
||||
const updateResult = await updateUser(id, data);
|
||||
|
||||
return response(updateResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('User - Update', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
***************************************
|
||||
* DELETE - update User
|
||||
***************************************
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const userId = searchParams.get('userId');
|
||||
|
||||
const { data } = await req.json();
|
||||
|
||||
try {
|
||||
if (!userId) throw new Error('userId cannot null');
|
||||
const id: number = parseInt(userId);
|
||||
|
||||
const deleteResult = await deleteUser(id);
|
||||
|
||||
return response(deleteResult, STATUS.OK);
|
||||
} catch (error) {
|
||||
return handleError('User - Update', error);
|
||||
}
|
||||
}
|
26
03_source/cms_backend/src/app/api/user/test.http
Normal file
26
03_source/cms_backend/src/app/api/user/test.http
Normal file
@@ -0,0 +1,26 @@
|
||||
###
|
||||
GET http://localhost:7272/api/user
|
||||
|
||||
###
|
||||
GET http://localhost:7272/api/user?userId=cmbfvonhl000011ykdi345yc9
|
||||
|
||||
###
|
||||
POST http://localhost:7272/api/user?userId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data":{"name": "John Doe"}
|
||||
}
|
||||
|
||||
###
|
||||
PUT http://localhost:7272/api/user?userId=1
|
||||
content-type: application/json
|
||||
|
||||
{
|
||||
"data": {"name": "John Doe"}
|
||||
}
|
||||
|
||||
|
||||
###
|
||||
DELETE http://localhost:7272/api/user?userId=1
|
||||
|
66
03_source/cms_backend/src/app/services/AccessLog.service.ts
Normal file
66
03_source/cms_backend/src/app/services/AccessLog.service.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
// src/app/services/AccessLog.service.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// Service for handling AccessLog records
|
||||
//
|
||||
// RULES:
|
||||
// - All methods return Promises
|
||||
// - Input validation should be done at controller level
|
||||
// - Errors should be propagated to caller
|
||||
|
||||
import type { AccessLog } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
// type CreateAccessLog = {
|
||||
// userId?: string;
|
||||
// message?: string;
|
||||
// metadata?: Record<string, any>;
|
||||
// };
|
||||
|
||||
// type UpdateAccessLog = {
|
||||
// status?: number;
|
||||
// metadata?: object;
|
||||
// };
|
||||
|
||||
async function listAccessLogs(): Promise<AccessLog[]> {
|
||||
return prisma.accessLog.findMany({
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: 100,
|
||||
});
|
||||
}
|
||||
|
||||
async function getAccessLog(id: string): Promise<AccessLog | null> {
|
||||
return prisma.accessLog.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
async function createAccessLog(userId?: string, message?: string, metadata?: Record<string, any>): Promise<AccessLog> {
|
||||
return prisma.accessLog.create({
|
||||
data: {
|
||||
userId,
|
||||
message,
|
||||
metadata,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// async function update(id: string, data: UpdateAccessLog): Promise<AccessLog> {
|
||||
// return prisma.accessLog.update({
|
||||
// where: { id },
|
||||
// data: {
|
||||
// ...data,
|
||||
// metadata: data.metadata || {},
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
// async function deleteAccessLog(id: string): Promise<AccessLog> {
|
||||
// return prisma.accessLog.delete({ where: { id } });
|
||||
// }
|
||||
|
||||
export {
|
||||
//
|
||||
getAccessLog,
|
||||
listAccessLogs,
|
||||
createAccessLog,
|
||||
};
|
52
03_source/cms_backend/src/app/services/AppLog.service.ts
Normal file
52
03_source/cms_backend/src/app/services/AppLog.service.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
// src/app/services/AppLog.service.ts
|
||||
//
|
||||
// REQ0047/T.B.A.
|
||||
//
|
||||
// PURPOSE:
|
||||
// - AppLog example for handling AppLog Record
|
||||
//
|
||||
// RULES:
|
||||
// - T.B.A.
|
||||
//
|
||||
|
||||
import type { AppLog } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateAppLog = {
|
||||
level: number;
|
||||
message: string;
|
||||
};
|
||||
|
||||
// type UpdateAppLog = {
|
||||
// level: number;
|
||||
// message: string;
|
||||
// };
|
||||
|
||||
async function listAppLogs(): Promise<AppLog[]> {
|
||||
return prisma.appLog.findMany();
|
||||
}
|
||||
|
||||
async function getAppLog(appLogId: string) {
|
||||
return prisma.appLog.findFirst({ where: { id: appLogId } });
|
||||
}
|
||||
|
||||
async function createNewAppLog(createForm: CreateAppLog) {
|
||||
return prisma.appLog.create({ data: createForm });
|
||||
}
|
||||
|
||||
// async function updateAppLog(appLogId: string, updateForm: UpdateAppLog) {
|
||||
// return prisma.appLog.update({ where: { id: appLogId }, data: updateForm });
|
||||
// }
|
||||
|
||||
async function deleteAppLog(appLogId: string) {
|
||||
return prisma.appLog.delete({ where: { id: appLogId } });
|
||||
}
|
||||
|
||||
export {
|
||||
getAppLog,
|
||||
listAppLogs,
|
||||
// updateAppLog,
|
||||
deleteAppLog,
|
||||
createNewAppLog,
|
||||
};
|
@@ -0,0 +1,7 @@
|
||||
with knowledge in schema.prisma file,
|
||||
please refer the below helloworld example `helloworld.service.ts`
|
||||
and create `user.service.ts` to cover user record
|
||||
|
||||
thanks
|
||||
|
||||
`/home/logic/_wsl_workspace/001_github_ws/HKSingleParty-ws/HKSingleParty/03_source/cms_backend/src/app/services/helloworld.service.ts`
|
65
03_source/cms_backend/src/app/services/event.service.ts
Normal file
65
03_source/cms_backend/src/app/services/event.service.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
// src/app/services/event.service.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// - Service for handling Event records
|
||||
//
|
||||
// RULES:
|
||||
// - Follows same pattern as helloworld.service.ts
|
||||
//
|
||||
|
||||
import type { Event } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateEvent = {
|
||||
eventDate: DateTime;
|
||||
title: string;
|
||||
joinMembers?: Json[];
|
||||
price: number;
|
||||
currency: string;
|
||||
duration_m: number;
|
||||
ageBottom: number;
|
||||
ageTop: number;
|
||||
location: string;
|
||||
avatar?: string;
|
||||
memberId?: number;
|
||||
};
|
||||
|
||||
type UpdateEvent = {
|
||||
eventDate?: DateTime;
|
||||
title?: string;
|
||||
joinMembers?: Json[];
|
||||
price?: number;
|
||||
currency?: string;
|
||||
duration_m?: number;
|
||||
ageBottom?: number;
|
||||
ageTop?: number;
|
||||
location?: string;
|
||||
avatar?: string;
|
||||
memberId?: number;
|
||||
};
|
||||
|
||||
async function listEvents(): Promise<Event[]> {
|
||||
return prisma.event.findMany();
|
||||
}
|
||||
|
||||
async function getEvent(eventId: number) {
|
||||
return prisma.event.findFirst({ where: { id: eventId } });
|
||||
}
|
||||
|
||||
async function createNewEvent(createForm: CreateEvent) {
|
||||
return prisma.event.create({ data: createForm });
|
||||
}
|
||||
|
||||
async function updateEvent(eventId: number, updateForm: UpdateEvent) {
|
||||
return prisma.event.update({
|
||||
where: { id: eventId },
|
||||
data: updateForm,
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteEvent(eventId: number) {
|
||||
return prisma.event.delete({ where: { id: eventId } });
|
||||
}
|
||||
|
||||
export { getEvent, listEvents, updateEvent, deleteEvent, createNewEvent };
|
44
03_source/cms_backend/src/app/services/helloworld.service.ts
Normal file
44
03_source/cms_backend/src/app/services/helloworld.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// src/app/services/helloworld.service.ts
|
||||
//
|
||||
// REQ0047/T.B.A.
|
||||
//
|
||||
// PURPOSE:
|
||||
// - helloworld example for handling helloworld Record
|
||||
//
|
||||
// RULES:
|
||||
// - T.B.A.
|
||||
//
|
||||
|
||||
import type { Helloworld } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateHelloworld = {
|
||||
hello: string;
|
||||
};
|
||||
|
||||
type UpdateHelloworld = {
|
||||
hello: string;
|
||||
};
|
||||
|
||||
async function listHelloworlds(): Promise<Helloworld[]> {
|
||||
return prisma.helloworld.findMany();
|
||||
}
|
||||
|
||||
async function getHelloworld(helloworldId: number) {
|
||||
return prisma.helloworld.findFirst({ where: { id: helloworldId } });
|
||||
}
|
||||
|
||||
async function createNewHelloworld(createForm: CreateHelloworld) {
|
||||
return prisma.helloworld.create({ data: createForm });
|
||||
}
|
||||
|
||||
async function updateHelloworld(helloworldId: number, updateForm: UpdateHelloworld) {
|
||||
return prisma.helloworld.update({ where: { id: helloworldId }, data: updateForm });
|
||||
}
|
||||
|
||||
async function deleteHelloworld(helloworldId: number) {
|
||||
return prisma.helloworld.delete({ where: { id: helloworldId } });
|
||||
}
|
||||
|
||||
export { getHelloworld, listHelloworlds, updateHelloworld, deleteHelloworld, createNewHelloworld };
|
70
03_source/cms_backend/src/app/services/order.service.ts
Normal file
70
03_source/cms_backend/src/app/services/order.service.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
// src/app/services/order.service.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// - Handle Order Record CRUD operations
|
||||
// - Manage order status transitions
|
||||
// - Handle order-event relationships
|
||||
//
|
||||
|
||||
import type { OrderItem } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateOrderItem = {
|
||||
orderNumber?: string;
|
||||
// status?: string;
|
||||
// eventIds?: number[];
|
||||
};
|
||||
|
||||
type UpdateOrderItem = {
|
||||
orderNumber?: string;
|
||||
// status?: string;
|
||||
// last_payment_date?: Date;
|
||||
// eventIds?: number[];
|
||||
};
|
||||
|
||||
async function listOrders(): Promise<OrderItem[]> {
|
||||
return prisma.orderItem.findMany();
|
||||
}
|
||||
|
||||
async function getOrder(orderId: string): Promise<OrderItem | null> {
|
||||
return prisma.orderItem.findFirst({
|
||||
where: { id: orderId },
|
||||
});
|
||||
}
|
||||
|
||||
async function createOrder(createForm: CreateOrderItem): Promise<OrderItem> {
|
||||
return prisma.orderItem.create({
|
||||
data: createForm,
|
||||
});
|
||||
}
|
||||
|
||||
async function updateOrder(orderId: string, updateForm: UpdateOrderItem): Promise<OrderItem> {
|
||||
return prisma.orderItem.update({
|
||||
where: { id: orderId },
|
||||
data: updateForm,
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteOrder(orderId: string): Promise<OrderItem> {
|
||||
return prisma.orderItem.delete({
|
||||
where: { id: orderId },
|
||||
});
|
||||
}
|
||||
|
||||
async function getOrdersByStatus(status: string): Promise<OrderItem[]> {
|
||||
return prisma.orderItem.findMany({
|
||||
where: { status },
|
||||
});
|
||||
}
|
||||
|
||||
export {
|
||||
getOrder,
|
||||
listOrders,
|
||||
createOrder,
|
||||
updateOrder,
|
||||
deleteOrder,
|
||||
getOrdersByStatus,
|
||||
type CreateOrderItem as CreateOrder,
|
||||
type UpdateOrderItem as UpdateOrder,
|
||||
};
|
114
03_source/cms_backend/src/app/services/product.service.ts
Normal file
114
03_source/cms_backend/src/app/services/product.service.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// src/app/services/product.service.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// - Service for handling ProductItem Record
|
||||
//
|
||||
|
||||
import type { ProductItem } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateProduct = {
|
||||
sku: string;
|
||||
name: string;
|
||||
// price: number;
|
||||
// code?: string;
|
||||
// taxes?: number;
|
||||
// tags?: string[];
|
||||
// sizes?: string[];
|
||||
// gender?: string[];
|
||||
// colors?: string[];
|
||||
// category?: string;
|
||||
// quantity?: number;
|
||||
// available?: number;
|
||||
// coverUrl?: string;
|
||||
// images?: string[];
|
||||
// description?: string;
|
||||
// subDescription?: string;
|
||||
// publish?: string;
|
||||
// totalSold?: number;
|
||||
// totalRatings?: number;
|
||||
// totalReviews?: number;
|
||||
// inventoryType?: string;
|
||||
// ratings?: number[];
|
||||
// reviews?: string[];
|
||||
// result?: string;
|
||||
// thanks?: string;
|
||||
};
|
||||
|
||||
type UpdateProduct = {
|
||||
sku?: string;
|
||||
name?: string;
|
||||
// price?: number;
|
||||
// code?: string;
|
||||
// taxes?: number;
|
||||
// tags?: string[];
|
||||
// sizes?: string[];
|
||||
// gender?: string[];
|
||||
// colors?: string[];
|
||||
// category?: string;
|
||||
// quantity?: number;
|
||||
// available?: number;
|
||||
// coverUrl?: string;
|
||||
// images?: string[];
|
||||
// description?: string;
|
||||
// subDescription?: string;
|
||||
// publish?: string;
|
||||
// totalSold?: number;
|
||||
// totalRatings?: number;
|
||||
// totalReviews?: number;
|
||||
// inventoryType?: string;
|
||||
// ratings?: number[];
|
||||
// reviews?: string[];
|
||||
// result?: string;
|
||||
// thanks?: string;
|
||||
};
|
||||
|
||||
async function listProducts(): Promise<ProductItem[]> {
|
||||
return prisma.productItem.findMany();
|
||||
}
|
||||
|
||||
async function getProduct(productId: string) {
|
||||
return prisma.productItem.findUnique({ where: { id: productId } });
|
||||
}
|
||||
|
||||
async function createProduct(createForm: CreateProduct) {
|
||||
// return prisma.productItem.create({
|
||||
// data: {
|
||||
// ...createForm,
|
||||
// code: createForm.code || '',
|
||||
// taxes: createForm.taxes || 0,
|
||||
// tags: createForm.tags || [],
|
||||
// sizes: createForm.sizes || [],
|
||||
// gender: createForm.gender || [],
|
||||
// colors: createForm.colors || [],
|
||||
// category: createForm.category || '',
|
||||
// quantity: createForm.quantity || 0,
|
||||
// available: createForm.available || 0,
|
||||
// coverUrl: createForm.coverUrl || '',
|
||||
// images: createForm.images || [],
|
||||
// description: createForm.description || '',
|
||||
// subDescription: createForm.subDescription || '',
|
||||
// publish: createForm.publish || 'published',
|
||||
// totalSold: createForm.totalSold || 0,
|
||||
// totalRatings: createForm.totalRatings || 0,
|
||||
// totalReviews: createForm.totalReviews || 0,
|
||||
// inventoryType: createForm.inventoryType || '',
|
||||
// ratings: createForm.ratings || [],
|
||||
// reviews: createForm.reviews || [],
|
||||
// },
|
||||
// });
|
||||
}
|
||||
|
||||
async function updateProduct(productId: string, updateForm: UpdateProduct) {
|
||||
return prisma.productItem.update({
|
||||
where: { id: productId },
|
||||
data: updateForm,
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteProduct(productId: string) {
|
||||
return prisma.productItem.delete({ where: { id: productId } });
|
||||
}
|
||||
|
||||
export { getProduct, listProducts, createProduct, updateProduct, deleteProduct, type CreateProduct, type UpdateProduct };
|
122
03_source/cms_backend/src/app/services/userItem.service.ts
Normal file
122
03_source/cms_backend/src/app/services/userItem.service.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
// src/app/services/user.service.ts
|
||||
//
|
||||
// PURPOSE:
|
||||
// - Handle User Record CRUD operations
|
||||
//
|
||||
// RULES:
|
||||
// - Follow Prisma best practices for database operations
|
||||
// - Validate input data before processing
|
||||
//
|
||||
|
||||
import type { UserItem } from '@prisma/client';
|
||||
|
||||
import prisma from '../lib/prisma';
|
||||
|
||||
type CreateUser = {
|
||||
email: string;
|
||||
// name?: string;
|
||||
// password: string;
|
||||
// role?: Role;
|
||||
// isEmailVerified?: boolean;
|
||||
// admin?: boolean;
|
||||
};
|
||||
|
||||
type UpdateUser = {
|
||||
email?: string;
|
||||
// name?: string;
|
||||
// password?: string;
|
||||
// role?: Role;
|
||||
// isEmailVerified?: boolean;
|
||||
isAdmin?: boolean;
|
||||
};
|
||||
|
||||
async function listUsers(): Promise<UserItem[]> {
|
||||
return prisma.userItem.findMany();
|
||||
}
|
||||
|
||||
async function getUserItem(userId: string): Promise<UserItem | null> {
|
||||
return prisma.userItem.findFirst({ where: { id: userId } });
|
||||
}
|
||||
|
||||
async function updateUser(userId: string, updateForm: UpdateUser): Promise<User> {
|
||||
return prisma.userItem.update({
|
||||
where: { id: userId },
|
||||
data: updateForm,
|
||||
});
|
||||
}
|
||||
|
||||
// check if userId is a admin
|
||||
// check if userId is a admin
|
||||
async function isAdmin(userId: string): Promise<boolean> {
|
||||
const user = await getUserItem(userId);
|
||||
return user?.isAdmin === true;
|
||||
}
|
||||
|
||||
async function changeToAdmin(userIdToPromote: string, userIdOfApplicant: string) {
|
||||
// check the applicant is admin or not
|
||||
const userApplicant = await getUserItem(userIdOfApplicant);
|
||||
let promoteResult = {};
|
||||
|
||||
if (userApplicant && userApplicant.isAdmin) {
|
||||
// applicant is an admin
|
||||
promoteResult = await updateUser(userIdToPromote, { isAdmin: true });
|
||||
} else {
|
||||
promoteResult = { status: 'failed', message: 'applicant is not a admin' };
|
||||
}
|
||||
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
async function changeToUser(userIdToPromote: string, userIdOfApplicant: string) {
|
||||
// check the applicant is admin or not
|
||||
const userApplicant = await getUserItem(userIdOfApplicant);
|
||||
let promoteResult = {};
|
||||
|
||||
if (userApplicant && userApplicant.isAdmin) {
|
||||
// applicant is an admin
|
||||
promoteResult = await updateUser(userIdToPromote, { isAdmin: false });
|
||||
} else {
|
||||
promoteResult = { status: 'failed', message: 'applicant is not a admin' };
|
||||
}
|
||||
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
async function getUserByEmail(email: string): Promise<void> {
|
||||
// return prisma.userItem.findUnique({
|
||||
// where: { email },
|
||||
// include: {
|
||||
// Token: true,
|
||||
// },
|
||||
// });
|
||||
}
|
||||
|
||||
async function createNewUser(createForm: CreateUser): Promise<void> {
|
||||
// return prisma.userItem.create({
|
||||
// data: {
|
||||
// email: createForm.email,
|
||||
// name: createForm.name,
|
||||
// password: createForm.password,
|
||||
// role: createForm.role || 'USER',
|
||||
// isEmailVerified: createForm.isEmailVerified || false,
|
||||
// },
|
||||
// });
|
||||
}
|
||||
|
||||
async function deleteUser(userId: number): Promise<void> {
|
||||
// return prisma.userItem.delete({ where: { id: userId } });
|
||||
}
|
||||
|
||||
export {
|
||||
// getUser,
|
||||
isAdmin,
|
||||
listUsers,
|
||||
updateUser,
|
||||
deleteUser,
|
||||
changeToUser,
|
||||
createNewUser,
|
||||
changeToAdmin,
|
||||
getUserByEmail,
|
||||
type CreateUser,
|
||||
type UpdateUser,
|
||||
};
|
@@ -7,7 +7,7 @@ export const STATUS = {
|
||||
UNAUTHORIZED: 401,
|
||||
};
|
||||
|
||||
export function response(data: string | Record<string, unknown>, status: number): Response {
|
||||
export function response(data: string | Record<string, unknown> | Record<string, unknown>[], status: number): Response {
|
||||
const value = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
|
||||
return new Response(value, {
|
||||
|
@@ -3,7 +3,7 @@
|
||||
set -ex
|
||||
|
||||
# -f docker-compose.db.yml
|
||||
DOCKER_COMPOSE_FILES=" -f docker-compose.yml "
|
||||
DOCKER_COMPOSE_FILES=" -f docker-compose.yml -f docker-compose.dev.yml"
|
||||
|
||||
# docker compose $DOCKER_COMPOSE_FILES build
|
||||
docker compose $DOCKER_COMPOSE_FILES up -d
|
||||
|
15
03_source/docker/03_mobile.sh
Executable file
15
03_source/docker/03_mobile.sh
Executable file
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -ex
|
||||
|
||||
# -f docker-compose.db.yml
|
||||
DOCKER_COMPOSE_FILES=" -f docker-compose.yml "
|
||||
|
||||
docker compose $DOCKER_COMPOSE_FILES exec -it mobile bash
|
||||
|
||||
# cd ../api_server
|
||||
# yarn docker:dev
|
||||
# cd ..
|
||||
|
||||
|
||||
# docker compose $DOCKER_COMPOSE_FILES logs -f
|
9
03_source/docker/docker-compose.dev.yml
Normal file
9
03_source/docker/docker-compose.dev.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
services:
|
||||
frontend:
|
||||
command: "sleep infinity"
|
||||
|
||||
mobile:
|
||||
command: "sleep infinity"
|
||||
|
||||
cms_backend:
|
||||
command: "sleep infinity"
|
@@ -12,8 +12,7 @@ services:
|
||||
volumes:
|
||||
- ../frontend:/app
|
||||
working_dir: "/app"
|
||||
# command: "yarn dev"
|
||||
command: "sleep infinity"
|
||||
command: "yarn dev"
|
||||
|
||||
mobile:
|
||||
image: 192.168.10.61:5000/hksingleparty_mobile
|
||||
@@ -38,8 +37,7 @@ services:
|
||||
volumes:
|
||||
- ../cms_backend:/app
|
||||
working_dir: "/app"
|
||||
# command: "yarn dev"
|
||||
command: "sleep infinity"
|
||||
command: "yarn dev"
|
||||
|
||||
postgres:
|
||||
container_name: postgres
|
||||
|
@@ -1,3 +1,5 @@
|
||||
// src/pages/dashboard/kanban/index.tsx
|
||||
|
||||
import { CONFIG } from 'src/global-config';
|
||||
|
||||
import { KanbanView } from 'src/sections/kanban/view';
|
||||
|
@@ -186,7 +186,7 @@ export function InvoiceDetails({ invoice }: Props) {
|
||||
<Typography variant="subtitle2" sx={{ mb: 1 }}>
|
||||
Date create
|
||||
</Typography>
|
||||
{fDate(invoice?.createdDate)}
|
||||
{fDate(invoice?.createDate)}
|
||||
</Stack>
|
||||
|
||||
<Stack sx={{ typography: 'body2' }}>
|
||||
|
@@ -58,11 +58,11 @@ export const NewInvoiceSchema = zod
|
||||
message: 'Invoice to is required!',
|
||||
}),
|
||||
sent: zod.number().default(0),
|
||||
createdDate: schemaHelper.date({ message: { required: 'Create date is required!' } }),
|
||||
createDate: schemaHelper.date({ message: { required: 'Create date is required!' } }),
|
||||
dueDate: schemaHelper.date({ message: { required: 'Due date is required!' } }),
|
||||
// Not required
|
||||
})
|
||||
.refine((data) => !fIsAfter(data.createdDate, data.dueDate), {
|
||||
.refine((data) => !fIsAfter(data.createDate, data.dueDate), {
|
||||
message: 'Due date cannot be earlier than create date!',
|
||||
path: ['dueDate'],
|
||||
});
|
||||
@@ -82,7 +82,7 @@ export function InvoiceNewEditForm({ currentInvoice }: Props) {
|
||||
|
||||
const defaultValues: NewInvoiceSchemaType = {
|
||||
invoiceNumber: 'INV-1990',
|
||||
createdDate: today(),
|
||||
createDate: today(),
|
||||
dueDate: null,
|
||||
taxes: 0,
|
||||
shipping: 0,
|
||||
|
@@ -139,7 +139,7 @@ function InvoicePdfDocument({ invoice, currentStatus }: InvoicePdfDocumentProps)
|
||||
shipping,
|
||||
subtotal,
|
||||
invoiceTo,
|
||||
createdDate,
|
||||
createDate,
|
||||
totalAmount,
|
||||
invoiceFrom,
|
||||
invoiceNumber,
|
||||
@@ -197,7 +197,7 @@ function InvoicePdfDocument({ invoice, currentStatus }: InvoicePdfDocumentProps)
|
||||
<View style={[styles.container, styles.mb40]}>
|
||||
<View style={{ width: '50%' }}>
|
||||
<Text style={[styles.text1Bold, styles.mb4]}>Date create</Text>
|
||||
<Text style={[styles.text2]}>{fDate(createdDate)}</Text>
|
||||
<Text style={[styles.text2]}>{fDate(createDate)}</Text>
|
||||
</View>
|
||||
<View style={{ width: '50%' }}>
|
||||
<Text style={[styles.text1Bold, styles.mb4]}>Due date</Text>
|
||||
|
@@ -141,8 +141,8 @@ export function InvoiceTableRow({
|
||||
|
||||
<TableCell>
|
||||
<ListItemText
|
||||
primary={fDate(row.createdDate)}
|
||||
secondary={fTime(row.createdDate)}
|
||||
primary={fDate(row.createDate)}
|
||||
secondary={fTime(row.createDate)}
|
||||
slotProps={{
|
||||
primary: { noWrap: true, sx: { typography: 'body2' } },
|
||||
secondary: { sx: { mt: 0.5, typography: 'caption' } },
|
||||
|
@@ -1,3 +1,5 @@
|
||||
// src/sections/kanban/view/kanban-view.tsx
|
||||
|
||||
import type {
|
||||
DragEndEvent,
|
||||
DragOverEvent,
|
||||
|
@@ -32,7 +32,7 @@ export type IInvoiceItem = {
|
||||
dueDate: IDateValue;
|
||||
invoiceNumber: string;
|
||||
items: IInvoiceItemItem[];
|
||||
createdDate: IDateValue;
|
||||
createDate: IDateValue;
|
||||
invoiceTo: IAddressItem;
|
||||
invoiceFrom: IAddressItem;
|
||||
};
|
||||
|
10
03_source/mobile/dev.sh
Executable file
10
03_source/mobile/dev.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
while true; do
|
||||
npm i -D
|
||||
|
||||
npm run dev
|
||||
|
||||
echo "restarting..."
|
||||
sleep 1
|
||||
done
|
@@ -62,6 +62,7 @@ import ChangeLanguage from './pages/ChangeLanguage';
|
||||
import ServiceAgreement from './pages/ServiceAgreement';
|
||||
import paths from './paths';
|
||||
import PrivacyAgreement from './pages/PrivacyAgreement';
|
||||
import AppRoute from './AppRoute';
|
||||
|
||||
setupIonicReact();
|
||||
|
||||
@@ -107,8 +108,7 @@ const IonicApp: React.FC<IonicAppProps> = ({ darkMode, schedule, setIsLoggedIn,
|
||||
which makes transitions between tabs and non tab pages smooth
|
||||
*/}
|
||||
|
||||
{/* */}
|
||||
<Route path="/not_implemented" component={NotImplemented} />
|
||||
<AppRoute />
|
||||
|
||||
{/* */}
|
||||
<Route path="/tabs" render={() => <MainTabs />} />
|
||||
@@ -118,8 +118,6 @@ const IonicApp: React.FC<IonicAppProps> = ({ darkMode, schedule, setIsLoggedIn,
|
||||
<Route path="/support" component={Support} />
|
||||
<Route path="/tutorial" component={Tutorial} />
|
||||
{/* */}
|
||||
<Route path="/event_detail/:id" component={EventDetail} />
|
||||
<Route path="/profile/:id" component={MemberProfile} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.SETTINGS} component={Settings} />
|
||||
|
18
03_source/mobile/src/AppRoute.tsx
Normal file
18
03_source/mobile/src/AppRoute.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Route } from 'react-router';
|
||||
import NotImplemented from './pages/NotImplemented';
|
||||
import EventDetail from './pages/EventDetail';
|
||||
import MemberProfile from './pages/MemberProfile';
|
||||
|
||||
const AppRoute: React.FC = () => {
|
||||
return (
|
||||
<>
|
||||
<Route path="/not_implemented" component={NotImplemented} />
|
||||
|
||||
{/* */}
|
||||
<Route path="/event_detail/:id" component={EventDetail} />
|
||||
<Route path="/profile/:id" component={MemberProfile} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AppRoute;
|
39
03_source/mobile/src/TabAppRoute.tsx
Normal file
39
03_source/mobile/src/TabAppRoute.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Route } from 'react-router';
|
||||
import NotImplemented from './pages/NotImplemented';
|
||||
import EventDetail from './pages/EventDetail';
|
||||
import MemberProfile from './pages/MemberProfile';
|
||||
import paths from './paths';
|
||||
import MembersNearByList from './pages/MembersNearByList';
|
||||
import OrderList from './pages/OrderList';
|
||||
import MessageList from './pages/MessageList';
|
||||
import Favourites from './pages/Favourites';
|
||||
import MyProfile from './pages/MyProfile';
|
||||
import EventList from './pages/EventList';
|
||||
|
||||
const TabAppRoute: React.FC = () => {
|
||||
return (
|
||||
<>
|
||||
<Route path="/tabs/not_implemented" component={NotImplemented} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.NEARBY_LIST} render={() => <MembersNearByList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.ORDERS_LIST} render={() => <OrderList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.MESSAGE_LIST} render={() => <MessageList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.FAVOURITES_LIST} render={() => <Favourites />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path="/tabs/events" render={() => <EventList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path="/tabs/my_profile" render={() => <MyProfile />} exact={true} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TabAppRoute;
|
@@ -16,8 +16,9 @@ export const getConfData = async () => {
|
||||
const response = await Promise.all([
|
||||
fetch(dataUrl),
|
||||
fetch(locationsUrl),
|
||||
axios.get(`${constants.API_ENDPOINT}/v1/events`),
|
||||
axios.get(`${constants.API_ENDPOINT}/v1/members`),
|
||||
axios.get(`${constants.API_ENDPOINT}/api/order/list`),
|
||||
// axios.get(`${constants.API_ENDPOINT}/v1/events`),
|
||||
// axios.get(`${constants.API_ENDPOINT}/v1/members`),
|
||||
//
|
||||
]);
|
||||
const responseData = await response[0].json();
|
||||
@@ -30,8 +31,12 @@ export const getConfData = async () => {
|
||||
.filter((trackName, index, array) => array.indexOf(trackName) === index)
|
||||
.sort();
|
||||
|
||||
const events = response[2].data;
|
||||
const nearByMembers = response[3].data;
|
||||
// const events = response[2].data;
|
||||
// const nearByMembers = response[3].data;
|
||||
const orders = response[2].data.orders;
|
||||
|
||||
const events = [];
|
||||
const nearByMembers = [];
|
||||
|
||||
const data = {
|
||||
schedule,
|
||||
@@ -43,16 +48,14 @@ export const getConfData = async () => {
|
||||
//
|
||||
events,
|
||||
nearByMembers,
|
||||
orders,
|
||||
//
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getUserData = async () => {
|
||||
const response = await Promise.all([
|
||||
Storage.get({ key: HAS_LOGGED_IN }),
|
||||
Storage.get({ key: HAS_SEEN_TUTORIAL }),
|
||||
Storage.get({ key: USERNAME }),
|
||||
]);
|
||||
const response = await Promise.all([Storage.get({ key: HAS_LOGGED_IN }), Storage.get({ key: HAS_SEEN_TUTORIAL }), Storage.get({ key: USERNAME })]);
|
||||
const isLoggedin = (await response[0].value) === 'true';
|
||||
const hasSeenTutorial = (await response[1].value) === 'true';
|
||||
const username = (await response[2].value) || undefined;
|
||||
|
@@ -19,144 +19,116 @@ const getSearchText = (state: AppState) => state.data.searchText;
|
||||
|
||||
export const getEvents = (state: AppState) => state.data.events;
|
||||
export const getNearbyMembers = (state: AppState) => state.data.nearByMembers;
|
||||
export const getOrders = (state: AppState) => state.data.orders;
|
||||
|
||||
export const getFilteredSchedule = createSelector(
|
||||
getSchedule,
|
||||
getFilteredTracks,
|
||||
(schedule, filteredTracks) => {
|
||||
const groups: ScheduleGroup[] = [];
|
||||
export const getFilteredSchedule = createSelector(getSchedule, getFilteredTracks, (schedule, filteredTracks) => {
|
||||
const groups: ScheduleGroup[] = [];
|
||||
|
||||
// Helper function to convert 12-hour time to 24-hour time for proper sorting
|
||||
const convertTo24Hour = (timeStr: string) => {
|
||||
const [time, period] = timeStr.toLowerCase().split(' ');
|
||||
let [hours, minutes] = time.split(':').map(Number);
|
||||
// Helper function to convert 12-hour time to 24-hour time for proper sorting
|
||||
const convertTo24Hour = (timeStr: string) => {
|
||||
const [time, period] = timeStr.toLowerCase().split(' ');
|
||||
let [hours, minutes] = time.split(':').map(Number);
|
||||
|
||||
if (period === 'pm' && hours !== 12) {
|
||||
hours += 12;
|
||||
} else if (period === 'am' && hours === 12) {
|
||||
hours = 0;
|
||||
}
|
||||
if (period === 'pm' && hours !== 12) {
|
||||
hours += 12;
|
||||
} else if (period === 'am' && hours === 12) {
|
||||
hours = 0;
|
||||
}
|
||||
|
||||
return `${hours.toString().padStart(2, '0')}:${minutes || '00'}`;
|
||||
};
|
||||
return `${hours.toString().padStart(2, '0')}:${minutes || '00'}`;
|
||||
};
|
||||
|
||||
// Sort the groups by time
|
||||
const sortedGroups = [...schedule.groups].sort((a, b) => {
|
||||
const timeA = convertTo24Hour(a.time);
|
||||
const timeB = convertTo24Hour(b.time);
|
||||
return timeA.localeCompare(timeB);
|
||||
// Sort the groups by time
|
||||
const sortedGroups = [...schedule.groups].sort((a, b) => {
|
||||
const timeA = convertTo24Hour(a.time);
|
||||
const timeB = convertTo24Hour(b.time);
|
||||
return timeA.localeCompare(timeB);
|
||||
});
|
||||
|
||||
sortedGroups.forEach((group: ScheduleGroup) => {
|
||||
const sessions: Session[] = [];
|
||||
group.sessions.forEach((session) => {
|
||||
session.tracks.forEach((track) => {
|
||||
if (filteredTracks.indexOf(track) > -1) {
|
||||
sessions.push(session);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
sortedGroups.forEach((group: ScheduleGroup) => {
|
||||
const sessions: Session[] = [];
|
||||
group.sessions.forEach((session) => {
|
||||
session.tracks.forEach((track) => {
|
||||
if (filteredTracks.indexOf(track) > -1) {
|
||||
sessions.push(session);
|
||||
}
|
||||
});
|
||||
if (sessions.length) {
|
||||
// Sort sessions within each group by start time
|
||||
const sortedSessions = sessions.sort((a, b) => {
|
||||
const timeA = convertTo24Hour(a.timeStart);
|
||||
const timeB = convertTo24Hour(b.timeStart);
|
||||
return timeA.localeCompare(timeB);
|
||||
});
|
||||
|
||||
if (sessions.length) {
|
||||
// Sort sessions within each group by start time
|
||||
const sortedSessions = sessions.sort((a, b) => {
|
||||
const timeA = convertTo24Hour(a.timeStart);
|
||||
const timeB = convertTo24Hour(b.timeStart);
|
||||
return timeA.localeCompare(timeB);
|
||||
});
|
||||
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions: sortedSessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
}
|
||||
);
|
||||
|
||||
export const getSearchedSchedule = createSelector(
|
||||
getFilteredSchedule,
|
||||
getSearchText,
|
||||
(schedule, searchText) => {
|
||||
if (!searchText) {
|
||||
return schedule;
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions: sortedSessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
const groups: ScheduleGroup[] = [];
|
||||
schedule.groups.forEach((group) => {
|
||||
const sessions = group.sessions.filter(
|
||||
(s) => s.name.toLowerCase().indexOf(searchText.toLowerCase()) > -1
|
||||
);
|
||||
if (sessions.length) {
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
});
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
export const getScheduleList = createSelector(
|
||||
getSearchedSchedule,
|
||||
(schedule) => schedule
|
||||
);
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
});
|
||||
|
||||
export const getGroupedFavorites = createSelector(
|
||||
getScheduleList,
|
||||
getFavoriteIds,
|
||||
(schedule, favoriteIds) => {
|
||||
const groups: ScheduleGroup[] = [];
|
||||
schedule.groups.forEach((group) => {
|
||||
const sessions = group.sessions.filter(
|
||||
(s) => favoriteIds.indexOf(s.id) > -1
|
||||
);
|
||||
if (sessions.length) {
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
});
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
export const getSearchedSchedule = createSelector(getFilteredSchedule, getSearchText, (schedule, searchText) => {
|
||||
if (!searchText) {
|
||||
return schedule;
|
||||
}
|
||||
);
|
||||
const groups: ScheduleGroup[] = [];
|
||||
schedule.groups.forEach((group) => {
|
||||
const sessions = group.sessions.filter((s) => s.name.toLowerCase().indexOf(searchText.toLowerCase()) > -1);
|
||||
if (sessions.length) {
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
});
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
});
|
||||
|
||||
export const getScheduleList = createSelector(getSearchedSchedule, (schedule) => schedule);
|
||||
|
||||
export const getGroupedFavorites = createSelector(getScheduleList, getFavoriteIds, (schedule, favoriteIds) => {
|
||||
const groups: ScheduleGroup[] = [];
|
||||
schedule.groups.forEach((group) => {
|
||||
const sessions = group.sessions.filter((s) => favoriteIds.indexOf(s.id) > -1);
|
||||
if (sessions.length) {
|
||||
const groupToAdd: ScheduleGroup = {
|
||||
time: group.time,
|
||||
sessions,
|
||||
};
|
||||
groups.push(groupToAdd);
|
||||
}
|
||||
});
|
||||
return {
|
||||
date: schedule.date,
|
||||
groups,
|
||||
} as Schedule;
|
||||
});
|
||||
|
||||
const getIdParam = (_state: AppState, props: any) => {
|
||||
return props.match.params['id'];
|
||||
};
|
||||
|
||||
export const getSession = createSelector(
|
||||
getSessions,
|
||||
getIdParam,
|
||||
(sessions, id) => {
|
||||
return sessions.find((s: Session) => s.id === id);
|
||||
}
|
||||
);
|
||||
export const getSession = createSelector(getSessions, getIdParam, (sessions, id) => {
|
||||
return sessions.find((s: Session) => s.id === id);
|
||||
});
|
||||
|
||||
export const getSpeaker = createSelector(
|
||||
getSpeakers,
|
||||
getIdParam,
|
||||
(speakers, id) => speakers.find((x: Speaker) => x.id === id)
|
||||
);
|
||||
export const getSpeaker = createSelector(getSpeakers, getIdParam, (speakers, id) => speakers.find((x: Speaker) => x.id === id));
|
||||
|
||||
export const getEvent = createSelector(getEvents, getIdParam, (events, id) =>
|
||||
events.find((x: Event) => x.id === id)
|
||||
);
|
||||
export const getEvent = createSelector(getEvents, getIdParam, (events, id) => events.find((x: Event) => x.id === id));
|
||||
|
||||
export const getSpeakerSessions = createSelector(getSessions, (sessions) => {
|
||||
const speakerSessions: { [key: string]: Session[] } = {};
|
||||
@@ -175,9 +147,7 @@ export const getSpeakerSessions = createSelector(getSessions, (sessions) => {
|
||||
});
|
||||
|
||||
export const mapCenter = (state: AppState) => {
|
||||
const item = state.data.locations.find(
|
||||
(l: Location) => l.id === state.data.mapCenterId
|
||||
);
|
||||
const item = state.data.locations.find((l: Location) => l.id === state.data.mapCenterId);
|
||||
if (item == null) {
|
||||
return {
|
||||
id: 1,
|
||||
|
61
03_source/mobile/src/data/sessions/orders.actions.ts
Normal file
61
03_source/mobile/src/data/sessions/orders.actions.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { getConfData } from '../dataApi';
|
||||
import { ActionType } from '../../util/types';
|
||||
import { ConfState } from './conf.state';
|
||||
|
||||
export const loadConfData = () => async (dispatch: React.Dispatch<any>) => {
|
||||
dispatch(setLoading(true));
|
||||
const data = await getConfData();
|
||||
dispatch(setData(data));
|
||||
dispatch(setLoading(false));
|
||||
};
|
||||
|
||||
export const setLoading = (isLoading: boolean) =>
|
||||
({
|
||||
type: 'set-conf-loading',
|
||||
isLoading,
|
||||
} as const);
|
||||
|
||||
export const setData = (data: Partial<ConfState>) =>
|
||||
({
|
||||
type: 'set-conf-data',
|
||||
data,
|
||||
} as const);
|
||||
|
||||
export const addFavorite = (sessionId: number) =>
|
||||
({
|
||||
type: 'add-favorite',
|
||||
sessionId,
|
||||
} as const);
|
||||
|
||||
export const removeFavorite = (sessionId: number) =>
|
||||
({
|
||||
type: 'remove-favorite',
|
||||
sessionId,
|
||||
} as const);
|
||||
|
||||
export const updateFilteredTracks = (filteredTracks: string[]) =>
|
||||
({
|
||||
type: 'update-filtered-tracks',
|
||||
filteredTracks,
|
||||
} as const);
|
||||
|
||||
export const setSearchText = (searchText?: string) =>
|
||||
({
|
||||
type: 'set-search-text',
|
||||
searchText,
|
||||
} as const);
|
||||
|
||||
export const setMenuEnabled = (menuEnabled: boolean) =>
|
||||
({
|
||||
type: 'set-menu-enabled',
|
||||
menuEnabled,
|
||||
} as const);
|
||||
|
||||
export type OrdersActions =
|
||||
| ActionType<typeof setLoading>
|
||||
| ActionType<typeof setData>
|
||||
| ActionType<typeof addFavorite>
|
||||
| ActionType<typeof removeFavorite>
|
||||
| ActionType<typeof updateFilteredTracks>
|
||||
| ActionType<typeof setSearchText>
|
||||
| ActionType<typeof setMenuEnabled>;
|
31
03_source/mobile/src/data/sessions/orders.reducer.ts
Normal file
31
03_source/mobile/src/data/sessions/orders.reducer.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { OrdersActions } from './orders.actions';
|
||||
import { ConfState } from './conf.state';
|
||||
|
||||
export const orderReducer = (state: ConfState, action: OrdersActions): ConfState => {
|
||||
switch (action.type) {
|
||||
case 'set-conf-loading': {
|
||||
return { ...state, loading: action.isLoading };
|
||||
}
|
||||
case 'set-conf-data': {
|
||||
return { ...state, ...action.data };
|
||||
}
|
||||
case 'add-favorite': {
|
||||
return { ...state, favorites: [...state.favorites, action.sessionId] };
|
||||
}
|
||||
case 'remove-favorite': {
|
||||
return {
|
||||
...state,
|
||||
favorites: [...state.favorites.filter((x) => x !== action.sessionId)],
|
||||
};
|
||||
}
|
||||
case 'update-filtered-tracks': {
|
||||
return { ...state, filteredTracks: action.filteredTracks };
|
||||
}
|
||||
case 'set-search-text': {
|
||||
return { ...state, searchText: action.searchText };
|
||||
}
|
||||
case 'set-menu-enabled': {
|
||||
return { ...state, menuEnabled: action.menuEnabled };
|
||||
}
|
||||
}
|
||||
};
|
@@ -3,6 +3,8 @@ import { combineReducers } from './combineReducers';
|
||||
import { sessionsReducer } from './sessions/sessions.reducer';
|
||||
import { userReducer } from './user/user.reducer';
|
||||
import { locationsReducer } from './locations/locations.reducer';
|
||||
//
|
||||
import { orderReducer } from './sessions/orders.reducer';
|
||||
|
||||
export const initialState: AppState = {
|
||||
data: {
|
||||
@@ -19,6 +21,7 @@ export const initialState: AppState = {
|
||||
//
|
||||
events: [],
|
||||
nearbyMembers: [],
|
||||
orders: [],
|
||||
},
|
||||
user: {
|
||||
hasSeenTutorial: false,
|
||||
@@ -35,6 +38,8 @@ export const reducers = combineReducers({
|
||||
data: sessionsReducer,
|
||||
user: userReducer,
|
||||
locations: locationsReducer,
|
||||
//
|
||||
order: orderReducer,
|
||||
});
|
||||
|
||||
export type AppState = ReturnType<typeof reducers>;
|
||||
|
15
03_source/mobile/src/models/Order.ts
Normal file
15
03_source/mobile/src/models/Order.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export type IDateValue = string | number | null;
|
||||
|
||||
export interface Order {
|
||||
id: string;
|
||||
createdAt: IDateValue;
|
||||
//
|
||||
taxes: number;
|
||||
status: string;
|
||||
shipping: number;
|
||||
discount: number;
|
||||
subtotal: number;
|
||||
orderNumber: string;
|
||||
totalAmount: number;
|
||||
totalQuantity: number;
|
||||
}
|
@@ -17,6 +17,7 @@ import MyProfile from './MyProfile';
|
||||
import MessageList from './MessageList';
|
||||
import paths from '../paths';
|
||||
import Favourites from './Favourites';
|
||||
import TabAppRoute from '../TabAppRoute';
|
||||
|
||||
interface MainTabsProps {}
|
||||
|
||||
@@ -40,22 +41,7 @@ const MainTabs: React.FC<MainTabsProps> = () => {
|
||||
<Route path="/tabs/about" render={() => <About />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path="/tabs/events" render={() => <EventList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.NEARBY_LIST} render={() => <MembersNearByList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.ORDERS_LIST} render={() => <OrderList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.MESSAGE_LIST} render={() => <MessageList />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path={paths.FAVOURITES_LIST} render={() => <Favourites />} exact={true} />
|
||||
|
||||
{/* */}
|
||||
<Route path="/tabs/my_profile" render={() => <MyProfile />} exact={true} />
|
||||
<TabAppRoute />
|
||||
</IonRouterOutlet>
|
||||
{/* */}
|
||||
<IonTabBar slot="bottom">
|
||||
|
155
03_source/mobile/src/pages/MyProfile/NotLoggedIn/index.tsx
Normal file
155
03_source/mobile/src/pages/MyProfile/NotLoggedIn/index.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
// REQ0053/profile-page
|
||||
//
|
||||
// PURPOSE:
|
||||
// - Provides functionality view user profile
|
||||
//
|
||||
// RULES:
|
||||
// - T.B.A.
|
||||
//
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
IonHeader,
|
||||
IonToolbar,
|
||||
IonTitle,
|
||||
IonContent,
|
||||
IonPage,
|
||||
IonButtons,
|
||||
IonMenuButton,
|
||||
IonGrid,
|
||||
IonRow,
|
||||
IonCol,
|
||||
useIonRouter,
|
||||
IonButton,
|
||||
IonIcon,
|
||||
IonPopover,
|
||||
IonAvatar,
|
||||
IonImg,
|
||||
IonItem,
|
||||
IonLabel,
|
||||
IonList,
|
||||
IonModal,
|
||||
IonSearchbar,
|
||||
useIonModal,
|
||||
IonInput,
|
||||
RefresherEventDetail,
|
||||
IonRefresher,
|
||||
IonRefresherContent,
|
||||
} from '@ionic/react';
|
||||
import SpeakerItem from '../../../components/SpeakerItem';
|
||||
import { Speaker } from '../../../models/Speaker';
|
||||
import { Session } from '../../../models/Schedule';
|
||||
import { connect } from '../../../data/connect';
|
||||
import * as selectors from '../../../data/selectors';
|
||||
import '../../SpeakerList.scss';
|
||||
import { getEvents } from '../../../api/getEvents';
|
||||
import { format } from 'date-fns';
|
||||
import { Event } from '../types';
|
||||
import { alertOutline, chevronDownCircleOutline, createOutline, heart, menuOutline, settingsOutline } from 'ionicons/icons';
|
||||
import AboutPopover from '../../../components/AboutPopover';
|
||||
import paths from '../../../paths';
|
||||
import { getProfileById } from '../../../api/getProfileById';
|
||||
import { defaultMember, Member } from '../../MemberProfile/type';
|
||||
|
||||
interface OwnProps {}
|
||||
|
||||
interface StateProps {
|
||||
speakers: Speaker[];
|
||||
speakerSessions: { [key: string]: Session[] };
|
||||
}
|
||||
|
||||
interface DispatchProps {}
|
||||
|
||||
interface SpeakerListProps extends OwnProps, StateProps, DispatchProps {}
|
||||
|
||||
const MyProfile: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) => {
|
||||
const [profile, setProfile] = useState<Member>(defaultMember);
|
||||
|
||||
const [showPopover, setShowPopover] = useState(false);
|
||||
const [popoverEvent, setPopoverEvent] = useState<MouseEvent>();
|
||||
const modal = useRef<HTMLIonModalElement>(null);
|
||||
|
||||
const router = useIonRouter();
|
||||
|
||||
function handleShowSettingButtonClick() {
|
||||
router.push(paths.SETTINGS);
|
||||
}
|
||||
|
||||
function handleNotImplementedClick() {
|
||||
router.push(paths.NOT_IMPLEMENTED);
|
||||
}
|
||||
|
||||
function handleRefresh(event: CustomEvent<RefresherEventDetail>) {
|
||||
setTimeout(() => {
|
||||
// Any calls to load data go here
|
||||
event.detail.complete();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
const [disableForwardLoginButton, setDisableForwardLoginButton] = useState(false);
|
||||
function handleForwardLoginPage() {
|
||||
try {
|
||||
setDisableForwardLoginButton(true);
|
||||
router.push(paths.login);
|
||||
setDisableForwardLoginButton(false);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
getProfileById('2').then(({ data }) => {
|
||||
console.log({ data });
|
||||
setProfile(data);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!profile) return <>loading</>;
|
||||
|
||||
return (
|
||||
<IonPage id="speaker-list">
|
||||
<IonHeader translucent={true} className="ion-no-border">
|
||||
<IonToolbar>
|
||||
<IonButtons slot="end">
|
||||
{/* <IonMenuButton /> */}
|
||||
<IonButton shape="round" onClick={() => handleShowSettingButtonClick()}>
|
||||
<IonIcon slot="icon-only" icon={settingsOutline}></IonIcon>
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle>My profile</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent fullscreen={true}>
|
||||
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
|
||||
<IonRefresherContent pullingIcon={chevronDownCircleOutline} pullingText="Pull to refresh" refreshingSpinner="circles" refreshingText="Refreshing..."></IonRefresherContent>
|
||||
</IonRefresher>
|
||||
|
||||
<IonHeader collapse="condense" className="ion-no-border">
|
||||
<IonToolbar>
|
||||
<IonTitle size="large">My profile</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<div style={{ height: '50vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<div>
|
||||
not login yet, <br />
|
||||
please login or sign up
|
||||
</div>
|
||||
<div style={{ height: '50vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<IonButton disabled={disableForwardLoginButton} onClick={handleForwardLoginPage}>
|
||||
Login
|
||||
</IonButton>
|
||||
</div>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default connect<OwnProps, StateProps, DispatchProps>({
|
||||
mapStateToProps: (state) => ({
|
||||
speakers: selectors.getSpeakers(state),
|
||||
speakerSessions: selectors.getSpeakerSessions(state),
|
||||
}),
|
||||
component: React.memo(MyProfile),
|
||||
});
|
@@ -49,6 +49,7 @@ import AboutPopover from '../../components/AboutPopover';
|
||||
import paths from '../../paths';
|
||||
import { getProfileById } from '../../api/getProfileById';
|
||||
import { defaultMember, Member } from '../MemberProfile/type';
|
||||
import NotLoggedIn from './NotLoggedIn';
|
||||
|
||||
interface OwnProps {}
|
||||
|
||||
@@ -63,6 +64,7 @@ interface SpeakerListProps extends OwnProps, StateProps, DispatchProps {}
|
||||
|
||||
const MyProfile: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) => {
|
||||
const [profile, setProfile] = useState<Member>(defaultMember);
|
||||
|
||||
const [showPopover, setShowPopover] = useState(false);
|
||||
const [popoverEvent, setPopoverEvent] = useState<MouseEvent>();
|
||||
const modal = useRef<HTMLIonModalElement>(null);
|
||||
@@ -92,6 +94,7 @@ const MyProfile: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) =>
|
||||
}, []);
|
||||
|
||||
if (!profile) return <>loading</>;
|
||||
if (profile.id == -1) return <NotLoggedIn />;
|
||||
|
||||
return (
|
||||
<IonPage id="speaker-list">
|
||||
|
@@ -7,34 +7,9 @@
|
||||
// - T.B.A.
|
||||
//
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
IonHeader,
|
||||
IonToolbar,
|
||||
IonContent,
|
||||
IonPage,
|
||||
IonButtons,
|
||||
IonMenuButton,
|
||||
IonButton,
|
||||
IonIcon,
|
||||
IonDatetime,
|
||||
IonSelectOption,
|
||||
IonList,
|
||||
IonItem,
|
||||
IonLabel,
|
||||
IonSelect,
|
||||
IonPopover,
|
||||
IonText,
|
||||
IonFooter,
|
||||
useIonRouter,
|
||||
} from '@ionic/react';
|
||||
import { IonHeader, IonToolbar, IonContent, IonPage, IonButtons, IonMenuButton, IonButton, IonIcon, IonDatetime, IonSelectOption, IonList, IonItem, IonLabel, IonSelect, IonPopover, IonText, IonFooter, useIonRouter } from '@ionic/react';
|
||||
import './style.scss';
|
||||
import {
|
||||
chevronBackOutline,
|
||||
ellipsisHorizontal,
|
||||
ellipsisVertical,
|
||||
heart,
|
||||
logoIonic,
|
||||
} from 'ionicons/icons';
|
||||
import { chevronBackOutline, ellipsisHorizontal, ellipsisVertical, heart, logoIonic } from 'ionicons/icons';
|
||||
import AboutPopover from '../../components/AboutPopover';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
import { TestContent } from './TestContent';
|
||||
@@ -60,12 +35,8 @@ interface Event {
|
||||
const EventDetail: React.FC<AboutProps> = () => {
|
||||
const [showPopover, setShowPopover] = useState(false);
|
||||
const [popoverEvent, setPopoverEvent] = useState<MouseEvent>();
|
||||
const [location, setLocation] = useState<
|
||||
'madison' | 'austin' | 'chicago' | 'seattle'
|
||||
>('madison');
|
||||
const [conferenceDate, setConferenceDate] = useState(
|
||||
'2047-05-17T00:00:00-05:00'
|
||||
);
|
||||
const [location, setLocation] = useState<'madison' | 'austin' | 'chicago' | 'seattle'>('madison');
|
||||
const [conferenceDate, setConferenceDate] = useState('2047-05-17T00:00:00-05:00');
|
||||
|
||||
const selectOptions = {
|
||||
header: 'Select a Location',
|
||||
@@ -95,8 +66,6 @@ const EventDetail: React.FC<AboutProps> = () => {
|
||||
router.goBack();
|
||||
}
|
||||
|
||||
if (!eventDetail) return <>loading</>;
|
||||
|
||||
return (
|
||||
<IonPage id="about-page">
|
||||
<IonContent>
|
||||
@@ -110,11 +79,7 @@ const EventDetail: React.FC<AboutProps> = () => {
|
||||
</IonButtons>
|
||||
<IonButtons slot="end">
|
||||
<IonButton onClick={presentPopover}>
|
||||
<IonIcon
|
||||
slot="icon-only"
|
||||
ios={ellipsisHorizontal}
|
||||
md={ellipsisVertical}
|
||||
></IonIcon>
|
||||
<IonIcon slot="icon-only" ios={ellipsisHorizontal} md={ellipsisVertical}></IonIcon>
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
</IonToolbar>
|
||||
@@ -143,7 +108,8 @@ const EventDetail: React.FC<AboutProps> = () => {
|
||||
backgroundPosition: 'center',
|
||||
}}
|
||||
></div>
|
||||
Sorry but Not implemented
|
||||
Sorry this feature
|
||||
<br /> Not implemented
|
||||
<IonButton onClick={handleBackOnClick} fill="clear" size="large">
|
||||
<IonIcon icon={chevronBackOutline} slot="start"></IonIcon>
|
||||
Back
|
||||
|
@@ -38,17 +38,11 @@ import '../SpeakerList.scss';
|
||||
import { getEvents } from '../../api/getEvents';
|
||||
import { format } from 'date-fns';
|
||||
import { Order } from './types';
|
||||
import {
|
||||
chevronBackOutline,
|
||||
chevronDownCircleOutline,
|
||||
chevronForwardOutline,
|
||||
heart,
|
||||
logoIonic,
|
||||
menuOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { bookmarksOutline, chevronBackOutline, chevronDownCircleOutline, chevronForwardOutline, heart, logoIonic, menuOutline } from 'ionicons/icons';
|
||||
import AboutPopover from '../../components/AboutPopover';
|
||||
import { getOrders } from '../../api/getOrders';
|
||||
import Loading from '../../components/Loading';
|
||||
import paths from '../../paths';
|
||||
|
||||
interface OwnProps {}
|
||||
|
||||
@@ -61,17 +55,14 @@ interface DispatchProps {}
|
||||
|
||||
interface SpeakerListProps extends OwnProps, StateProps, DispatchProps {}
|
||||
|
||||
const EventList: React.FC<SpeakerListProps> = ({
|
||||
speakers,
|
||||
speakerSessions,
|
||||
}) => {
|
||||
const [orders, setEvents] = useState<Order[] | []>([]);
|
||||
const EventList: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) => {
|
||||
const router = useIonRouter();
|
||||
const [orders, setEvents] = useState<Order[]>([]);
|
||||
|
||||
const [showPopover, setShowPopover] = useState(false);
|
||||
const [popoverEvent, setPopoverEvent] = useState<MouseEvent>();
|
||||
const modal = useRef<HTMLIonModalElement>(null);
|
||||
|
||||
const router = useIonRouter();
|
||||
|
||||
useEffect(() => {
|
||||
getOrders().then(({ data }) => {
|
||||
console.log({ data });
|
||||
@@ -86,8 +77,16 @@ const EventList: React.FC<SpeakerListProps> = ({
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function handleShowOrderDetail(event_id: string) {
|
||||
router.push(`/order_detail/${event_id}`);
|
||||
function handleShowOrderDetail(order_id: string) {
|
||||
router.push(paths.getOrderDetail(order_id));
|
||||
}
|
||||
|
||||
function handleNotImplemented() {
|
||||
router.push(paths.NOT_IMPLEMENTED);
|
||||
}
|
||||
|
||||
function handleBookmarksClick() {
|
||||
router.push(paths.FAVOURITES_LIST);
|
||||
}
|
||||
|
||||
if (!orders) return <Loading />;
|
||||
@@ -96,18 +95,19 @@ const EventList: React.FC<SpeakerListProps> = ({
|
||||
<IonPage id="speaker-list">
|
||||
<IonHeader translucent={true} className="ion-no-border">
|
||||
<IonToolbar>
|
||||
<IonButtons slot="end">
|
||||
{/* <IonMenuButton /> */}
|
||||
<IonButton shape="round" expand="block" onClick={handleBookmarksClick}>
|
||||
<IonIcon slot="icon-only" icon={bookmarksOutline}></IonIcon>
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle>My Orders</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent fullscreen={true}>
|
||||
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
|
||||
<IonRefresherContent
|
||||
pullingIcon={chevronDownCircleOutline}
|
||||
pullingText="Pull to refresh"
|
||||
refreshingSpinner="circles"
|
||||
refreshingText="Refreshing..."
|
||||
></IonRefresherContent>
|
||||
<IonRefresherContent pullingIcon={chevronDownCircleOutline} pullingText="Pull to refresh" refreshingSpinner="circles" refreshingText="Refreshing..."></IonRefresherContent>
|
||||
</IonRefresher>
|
||||
|
||||
<IonHeader collapse="condense">
|
||||
@@ -116,94 +116,73 @@ const EventList: React.FC<SpeakerListProps> = ({
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonGrid fixed>
|
||||
<IonRow>
|
||||
{orders.map((order, idx) => (
|
||||
<IonCol size="12" size-md="6" key={idx}>
|
||||
<div>
|
||||
<IonList>
|
||||
{orders.map((order, idx) => (
|
||||
<IonItem button onClick={handleNotImplemented}>
|
||||
<div
|
||||
style={{
|
||||
paddingBottom: '1rem',
|
||||
paddingTop: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ width: '70px' }}>
|
||||
<IonAvatar>
|
||||
<img alt="Silhouette of a person's head" src="https://plus.unsplash.com/premium_photo-1683121126477-17ef068309bc" />
|
||||
</IonAvatar>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '1rem',
|
||||
flexGrow: 1,
|
||||
}}
|
||||
>
|
||||
<div style={{ width: '70px' }}>
|
||||
<IonAvatar>
|
||||
<img
|
||||
alt="Silhouette of a person's head"
|
||||
src="https://plus.unsplash.com/premium_photo-1683121126477-17ef068309bc"
|
||||
/>
|
||||
</IonAvatar>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '1.2rem' }}>{order.title}</div>
|
||||
<IonButton shape="round" onClick={() => handleShowOrderDetail('1')} size="small" fill="clear">
|
||||
<IonIcon slot="icon-only" icon={chevronForwardOutline} size="small"></IonIcon>
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '1rem',
|
||||
flexGrow: 1,
|
||||
gap: '0.33rem',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '1.2rem' }}>{order.title}</div>
|
||||
<IonButton
|
||||
shape="round"
|
||||
onClick={() => handleShowOrderDetail('1')}
|
||||
size="small"
|
||||
fill="clear"
|
||||
>
|
||||
<IonIcon
|
||||
slot="icon-only"
|
||||
icon={chevronForwardOutline}
|
||||
size="small"
|
||||
></IonIcon>
|
||||
</IonButton>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.33rem',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
<div>Order time: {order.createdAt} </div>
|
||||
<div>Last payment date: {order.last_payment_date}</div>
|
||||
<div>Number of applicants: 38 </div>
|
||||
<div>Remaining dates: 50 </div>
|
||||
<div>
|
||||
<IonButton fill="outline">{order.status}</IonButton>
|
||||
</div>
|
||||
<div>Order time: {order.createdAt} </div>
|
||||
<div>Last payment date: {order.last_payment_date}</div>
|
||||
<div>Number of applicants: 38 </div>
|
||||
<div>Remaining dates: 50 </div>
|
||||
<div>
|
||||
<IonButton fill="outline">{order.status}</IonButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
borderBottom: '1px solid lightgray',
|
||||
marginTop: '0.5rem',
|
||||
marginBottom: '0.5rem',
|
||||
}}
|
||||
></div>
|
||||
</IonCol>
|
||||
))}
|
||||
</IonRow>
|
||||
</IonGrid>
|
||||
</div>
|
||||
</IonItem>
|
||||
))}
|
||||
</IonList>
|
||||
</IonContent>
|
||||
|
||||
{/* REQ0079/event-filter */}
|
||||
<IonModal
|
||||
ref={modal}
|
||||
trigger="open-modal"
|
||||
initialBreakpoint={0.5}
|
||||
breakpoints={[0, 0.25, 0.5, 0.75]}
|
||||
>
|
||||
<IonModal ref={modal} trigger="open-modal" initialBreakpoint={0.5} breakpoints={[0, 0.25, 0.5, 0.75]}>
|
||||
<IonContent className="ion-padding">
|
||||
<div
|
||||
style={{
|
||||
@@ -255,10 +234,7 @@ const EventList: React.FC<SpeakerListProps> = ({
|
||||
<IonButton shape="round">All</IonButton>
|
||||
</div>
|
||||
|
||||
<IonButton
|
||||
shape="round"
|
||||
style={{ marginTop: '1rem', marginBottom: '1rem' }}
|
||||
>
|
||||
<IonButton shape="round" style={{ marginTop: '1rem', marginBottom: '1rem' }}>
|
||||
Apply
|
||||
</IonButton>
|
||||
</div>
|
||||
|
@@ -31,13 +31,14 @@ import {
|
||||
} from '@ionic/react';
|
||||
import SpeakerItem from '../../components/SpeakerItem';
|
||||
import { Speaker } from '../../models/Speaker';
|
||||
import { Order } from '../../models/Order';
|
||||
import { Session } from '../../models/Schedule';
|
||||
import { connect } from '../../data/connect';
|
||||
import * as selectors from '../../data/selectors';
|
||||
import '../SpeakerList.scss';
|
||||
import { getEvents } from '../../api/getEvents';
|
||||
import { format } from 'date-fns';
|
||||
import { Order } from './types';
|
||||
// import { Order } from './types';
|
||||
import { bookmarksOutline, chevronBackOutline, chevronDownCircleOutline, chevronForwardOutline, heart, logoIonic, menuOutline } from 'ionicons/icons';
|
||||
import AboutPopover from '../../components/AboutPopover';
|
||||
import { getOrders } from '../../api/getOrders';
|
||||
@@ -47,7 +48,8 @@ import paths from '../../paths';
|
||||
interface OwnProps {}
|
||||
|
||||
interface StateProps {
|
||||
speakers: Speaker[];
|
||||
orders: Order[];
|
||||
//
|
||||
speakerSessions: { [key: string]: Session[] };
|
||||
}
|
||||
|
||||
@@ -55,19 +57,93 @@ interface DispatchProps {}
|
||||
|
||||
interface SpeakerListProps extends OwnProps, StateProps, DispatchProps {}
|
||||
|
||||
const EventList: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) => {
|
||||
const RemainingDays: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<div>#Rem:</div>
|
||||
<div>{amount}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const NumApplicants: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<div>#app. :</div>
|
||||
<div>{amount}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TotalAmount: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1.1rem' }}>
|
||||
<div style={{ display: 'flex', gap: '1rem', fontWeight: 'bold', fontSize: '1.2rem', opacity: 0.8 }}>
|
||||
<div>Total:</div>
|
||||
<div style={{ minWidth: '75px', display: 'inline-flex', justifyContent: 'flex-end' }}>{amount} </div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Subtotal HK$83.74
|
||||
const Subtotal: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end' }}>
|
||||
<div>Subtotal:</div>
|
||||
<div style={{ minWidth: '50px', display: 'inline-flex', justifyContent: 'flex-end' }}>{amount} </div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Shipping - HK$10
|
||||
const Shipping: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<div style={{ display: 'flex', gap: '1rem', fontWeight: 'bold' }}>
|
||||
<div>Shipping:</div>
|
||||
<div style={{ minWidth: '50px', display: 'inline-flex', justifyContent: 'flex-end' }}>{amount} </div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Discount - HK$10
|
||||
const Discount: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<div style={{ display: 'flex', gap: '1rem', fontWeight: 'bold' }}>
|
||||
<div>Discount:</div>
|
||||
<div style={{ minWidth: '50px', display: 'inline-flex', justifyContent: 'flex-end' }}>{amount} </div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Taxes HK$10
|
||||
const Tax: React.FC<{ amount: number }> = ({ amount }) => {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<div style={{ display: 'flex', gap: '1rem', fontWeight: 'bold' }}>
|
||||
<div>Tax:</div>
|
||||
<div style={{ minWidth: '50px', display: 'inline-flex', justifyContent: 'flex-end' }}>{amount} </div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const EventList: React.FC<SpeakerListProps> = ({ orders, speakerSessions }) => {
|
||||
const router = useIonRouter();
|
||||
const [orders, setEvents] = useState<Order[] | []>([]);
|
||||
|
||||
const [showPopover, setShowPopover] = useState(false);
|
||||
const [popoverEvent, setPopoverEvent] = useState<MouseEvent>();
|
||||
const modal = useRef<HTMLIonModalElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getOrders().then(({ data }) => {
|
||||
console.log({ data });
|
||||
setEvents(data);
|
||||
});
|
||||
// getOrders().then(({ data }) => {
|
||||
// console.log({ data });
|
||||
// setEvents(data);
|
||||
// });
|
||||
}, []);
|
||||
|
||||
function handleRefresh(event: CustomEvent<RefresherEventDetail>) {
|
||||
@@ -119,58 +195,68 @@ const EventList: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) =>
|
||||
<IonList>
|
||||
{orders.map((order, idx) => (
|
||||
<IonItem button onClick={handleNotImplemented}>
|
||||
<div
|
||||
style={{
|
||||
paddingBottom: '1rem',
|
||||
paddingTop: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ width: '70px' }}>
|
||||
<IonAvatar>
|
||||
<img alt="Silhouette of a person's head" src="https://plus.unsplash.com/premium_photo-1683121126477-17ef068309bc" />
|
||||
</IonAvatar>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '1rem',
|
||||
flexGrow: 1,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '1.2rem' }}>{order.title}</div>
|
||||
<IonButton shape="round" onClick={() => handleShowOrderDetail('1')} size="small" fill="clear">
|
||||
<IonIcon slot="icon-only" icon={chevronForwardOutline} size="small"></IonIcon>
|
||||
</IonButton>
|
||||
<div style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', width: 'calc( 100vw - 35px )' }}>
|
||||
<div style={{}}>
|
||||
<div>
|
||||
<div style={{ width: '70px' }}>
|
||||
<IonAvatar>
|
||||
<img alt="Silhouette of a person's head" src="https://plus.unsplash.com/premium_photo-1683121126477-17ef068309bc" />
|
||||
</IonAvatar>
|
||||
<div style={{ marginTop: '1rem', display: 'inline-flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<NumApplicants amount={38} />
|
||||
<RemainingDays amount={50} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ flexGrow: 1 }}>
|
||||
<div
|
||||
style={{
|
||||
flexGrow: 1,
|
||||
//
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.33rem',
|
||||
fontSize: '0.9rem',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div>Order time: {order.createdAt} </div>
|
||||
<div>Last payment date: {order.last_payment_date}</div>
|
||||
<div>Number of applicants: 38 </div>
|
||||
<div>Remaining dates: 50 </div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '1.2rem' }}>{order.orderNumber}</div>
|
||||
<IonButton shape="round" onClick={() => handleShowOrderDetail('1')} size="small" fill="clear">
|
||||
<IonIcon slot="icon-only" icon={chevronForwardOutline} size="small"></IonIcon>
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.33rem',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'inline-flex', gap: '0.5rem' }}>
|
||||
<div style={{ fontWeight: 'bold' }}>Order time:</div>
|
||||
<div>{order.createdAt.split('T')[0]}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 'bold' }}>Last payment date:</div>
|
||||
<div>{order.last_payment_date}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<IonButton fill="outline">{order.status}</IonButton>
|
||||
<Subtotal amount={order.subtotal} />
|
||||
<Shipping amount={order.shipping} />
|
||||
<Discount amount={order.discount} />
|
||||
<Tax amount={order.taxes} />
|
||||
<TotalAmount amount={order.totalAmount} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -180,73 +266,14 @@ const EventList: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) =>
|
||||
))}
|
||||
</IonList>
|
||||
</IonContent>
|
||||
|
||||
{/* REQ0079/event-filter */}
|
||||
<IonModal ref={modal} trigger="open-modal" initialBreakpoint={0.5} breakpoints={[0, 0.25, 0.5, 0.75]}>
|
||||
<IonContent className="ion-padding">
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
gap: '1rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
fontWeight: '1rem',
|
||||
fontSize: '1.5rem',
|
||||
marginTop: '0.5rem',
|
||||
marginBottom: '0.5rem',
|
||||
}}
|
||||
>
|
||||
Filter
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
fontWeight: '1rem',
|
||||
marginTop: '0.5rem',
|
||||
marginBottom: '0.5rem',
|
||||
}}
|
||||
>
|
||||
Maximum number of participant
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<IonButton shape="round">2-10</IonButton>
|
||||
<IonButton shape="round">12-40</IonButton>
|
||||
<IonButton shape="round">All</IonButton>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
fontWeight: '1rem',
|
||||
marginTop: '0.5rem',
|
||||
marginBottom: '0.5rem',
|
||||
}}
|
||||
>
|
||||
Held date
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<IonButton shape="round">Weekly</IonButton>
|
||||
<IonButton shape="round">Monthly</IonButton>
|
||||
<IonButton shape="round">All</IonButton>
|
||||
</div>
|
||||
|
||||
<IonButton shape="round" style={{ marginTop: '1rem', marginBottom: '1rem' }}>
|
||||
Apply
|
||||
</IonButton>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonModal>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default connect<OwnProps, StateProps, DispatchProps>({
|
||||
mapStateToProps: (state) => ({
|
||||
speakers: selectors.getSpeakers(state),
|
||||
orders: selectors.getOrders(state),
|
||||
// TODO: review below
|
||||
speakerSessions: selectors.getSpeakerSessions(state),
|
||||
}),
|
||||
component: React.memo(EventList),
|
||||
|
@@ -11,5 +11,7 @@ const paths = {
|
||||
CHANGE_LANGUAGE: '/change_language',
|
||||
SERVICE_AGREEMENT: '/service_agreement',
|
||||
PRIVACY_AGREEMENT: '/privacy_agreement',
|
||||
//
|
||||
login: '/login',
|
||||
};
|
||||
export default paths;
|
||||
|
File diff suppressed because it is too large
Load Diff
14
98_AI_workspace/software-engineer/001_greetings.md
Normal file
14
98_AI_workspace/software-engineer/001_greetings.md
Normal file
@@ -0,0 +1,14 @@
|
||||
```markdown
|
||||
# Greetings
|
||||
|
||||
Hi,
|
||||
|
||||
Imagine you are a software engineer and i will send you the guideline.
|
||||
plesae read it, prepare yourself and i will tell you the task afterwards
|
||||
|
||||
please read and understand the markdown files in directory
|
||||
`/home/logic/_wsl_workspace/001_github_ws/HKSingleParty-ws/HKSingleParty/98_AI_workspace/software-engineer`,
|
||||
it provides background information of project i want you to help.
|
||||
|
||||
thanks
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user