Skip to content

Commit

Permalink
usage limitation
Browse files Browse the repository at this point in the history
  • Loading branch information
djyde committed Jul 13, 2023
1 parent c82cd09 commit 53cfc6e
Show file tree
Hide file tree
Showing 11 changed files with 283 additions and 16 deletions.
18 changes: 18 additions & 0 deletions pages/api/comment/[commentId]/approve.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import { NextApiRequest, NextApiResponse } from 'next'
import { AuthService } from '../../../../service/auth.service'
import { CommentService } from '../../../../service/comment.service'
import { SubscriptionService, usageLimitation } from '../../../../service/subscription.service'
import { UsageLabel, UsageService } from '../../../../service/usage.service'
import { getSession } from '../../../../utils.server'

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const commentService = new CommentService(req)
const authService = new AuthService(req, res)
const usageService = new UsageService(req)
const session = await getSession(req)

const subscriptionService = new SubscriptionService()

if (req.method === 'POST') {
const commentId = req.query.commentId as string
Expand All @@ -18,7 +25,18 @@ export default async function handler(
return
}

// check usage
if (!await subscriptionService.approveCommentValidate(session.uid)) {
res.status(402).json({
error:
`You have reached the maximum number of approving comments on free plan (${usageLimitation['approve_comment']}/month). Please upgrade to Pro plan to approve more comments.`,
})
return
}

await commentService.approve(commentId)
await usageService.incr(UsageLabel.ApproveComment)

res.json({
message: 'success',
})
Expand Down
15 changes: 15 additions & 0 deletions pages/api/open/approve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import { resolvedConfig } from '../../../utils.server'
import jwt from 'jsonwebtoken'
import { CommentService } from '../../../service/comment.service'
import { SecretKey, TokenBody, TokenService } from '../../../service/token.service'
import { UsageLabel, UsageService } from '../../../service/usage.service'
import { SubscriptionService, usageLimitation } from '../../../service/subscription.service'

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const commentService = new CommentService(req)
const usageService = new UsageService(req)
const subscriptionService = new SubscriptionService()

const tokenService = new TokenService()

if (req.method === 'GET') {
Expand Down Expand Up @@ -59,6 +64,14 @@ export default async function handler(
return
}

// check usage
if (!await subscriptionService.quickApproveValidate(tokenBody.owner.id)) {
res.status(402).json({
error: `You have reached the maximum number of Quick Approve on free plan (${usageLimitation.quick_approve}/month). Please upgrade to Pro plan to use Quick Approve more.`
})
return
}

// firstly, approve comment
await commentService.approve(tokenBody.commentId)

Expand All @@ -69,6 +82,8 @@ export default async function handler(
})
}

await usageService.incr(UsageLabel.QuickApprove)

res.json({
message: 'success'
})
Expand Down
21 changes: 21 additions & 0 deletions pages/api/projects.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
import { NextApiRequest, NextApiResponse } from "next";
import { ProjectService } from "../../service/project.service";
import { SubscriptionService } from "../../service/subscription.service";
import { getSession, prisma } from "../../utils.server";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const projectService = new ProjectService(req)
const subscriptionService = new SubscriptionService()
const session = await getSession(req)

if (req.method === 'POST') {
if (!session) {
res.status(401).json({
error: 'Unauthorized'
})
return
}

// check subscription
if (!await subscriptionService.createProjectValidate(session.uid)) {
// if (true) {
res.status(402).json({
error: 'You have reached the maximum number of sites on free plan. Please upgrade to Pro plan to create more sites.'
})
return
}

const { title } = req.body as {
title: string
}

const created = await projectService.create(title)

res.json({
Expand Down
13 changes: 13 additions & 0 deletions pages/dashboard/project/[projectId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { MainLayout } from '../../../components/Layout'
import { AiOutlineCode, AiOutlineUnorderedList, AiOutlineControl, AiOutlineCheck, AiOutlineClose, AiOutlineSmile } from 'react-icons/ai'
import { List, Stack, Box, Text, Group, Anchor, Button, Pagination, Textarea, Title, Center } from '@mantine/core'
import { MainLayoutData, ViewDataService } from '../../../service/viewData.service'
import { notifications } from '@mantine/notifications'

const getComments = async ({ queryKey }) => {
const [_key, { projectId, page }] = queryKey
Expand Down Expand Up @@ -69,6 +70,18 @@ function CommentToolbar(props: {
const approveCommentMutation = useMutation(approveComment, {
onSuccess() {
props.refetch()
},
onError(data: any) {
const {
error: message,
status: statusCode
} = data.response.data

notifications.show({
title: "Error",
message,
color: 'yellow'
})
}
})
const replyCommentMutation = useMutation(replyAsModerator, {
Expand Down
12 changes: 12 additions & 0 deletions pages/getting-start.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ function GettingStart() {
shallow: true,
})
},
onError(data: any) {
const {
error: message,
status: statusCode
} = data.response.data

notifications.show({
title: "Error",
message,
color: 'yellow'
})
}
}
)
}
Expand Down
24 changes: 18 additions & 6 deletions pages/open/approve.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,16 @@ function ApprovePage(props: {
})
setReplyContent('')
},
onError() {
onError(data: any) {
const {
error: message,
status: statusCode
} = data.response.data

notifications.show({
title: 'Something went wrong',
message: 'Please try again later',
title: "Error",
message,
color: 'yellow'
})
}
})
Expand All @@ -61,10 +67,16 @@ function ApprovePage(props: {

location.reload()
},
onError() {
onError(data: any) {
const {
error: message,
status: statusCode
} = data.response.data

notifications.show({
title: 'Something went wrong',
message: 'Please try again later',
title: "Error",
message,
color: 'yellow'
})
}
})
Expand Down
12 changes: 12 additions & 0 deletions prisma/sqlite/migrations/20230713070441_usage/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "usages" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"label" TEXT NOT NULL,
"count" INTEGER NOT NULL DEFAULT 0,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "usages_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);

-- CreateIndex
CREATE UNIQUE INDEX "usages_userId_label_key" ON "usages"("userId", "label");
32 changes: 25 additions & 7 deletions prisma/sqlite/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ model User {
enableNewCommentNotification Boolean? @default(true) @map(name: "enable_new_comment_notification")
notificationEmail String? @map(name: "notification_email")
usage Usage[]
@@map(name: "users")
}

Expand All @@ -71,13 +73,13 @@ model Subscription {
userId String @unique
user User @relation(fields: [userId], references: [id])
lemonSubscriptionId String? @map(name: "lemon_subscription_id")
orderId String @map(name: "order_id")
productId String? @map(name: "product_id")
variantId String? @map(name: "variant_id")
customerId String? @map(name: "customer_id")
status String
endsAt DateTime? @map(name: "endsAt")
lemonSubscriptionId String? @map(name: "lemon_subscription_id")
orderId String @map(name: "order_id")
productId String? @map(name: "product_id")
variantId String? @map(name: "variant_id")
customerId String? @map(name: "customer_id")
status String
endsAt DateTime? @map(name: "endsAt")
updatePaymentMethodUrl String? @map(name: "update_payment_method_url")
Expand Down Expand Up @@ -163,3 +165,19 @@ model Comment {
@@map("comments")
}

model Usage {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id])
label String
count Int @default(0)
updatedAt DateTime @updatedAt
@@unique([userId, label])
@@map("usages")
}
Loading

0 comments on commit 53cfc6e

Please sign in to comment.