Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion app/api/chat/messages/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,3 @@ export async function POST(req: Request) {
)
}
}

80 changes: 80 additions & 0 deletions app/api/products/[id]/available/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import dbConnect from '@/lib/dbConnect'
import { NextRequest, NextResponse } from 'next/server'
import mongoose from 'mongoose'
import Product from '@/model/Product'
import { verifyJwt } from '@/lib/auth-utils'

type RouteContext = { params: Promise<{ id: string }> }

/**
* PATCH /api/products/:id/available
* Mark a product as available again. Only seller can do this.
*/
export async function PATCH(req: NextRequest, context: RouteContext) {
try {
await dbConnect()

const { id } = await context.params

if (!mongoose.Types.ObjectId.isValid(id)) {
return NextResponse.json(
{ message: 'Invalid product ID' },
{ status: 400 }
)
}

// Authenticate the user
const authResponse = await verifyJwt(req)
if (authResponse.status !== 200) {
return authResponse
}

const authData = await authResponse.json()
const userId = authData.userId as string

const product = await Product.findById(id)
if (!product) {
return NextResponse.json(
{ message: 'Product not found' },
{ status: 404 }
)
}

// Verify ownership — only the seller can mark as available
if (product.seller.toString() !== userId) {
return NextResponse.json(
{ message: 'Forbidden — you can only update your own listings' },
{ status: 403 }
)
}

if (!product.is_sold) {
return NextResponse.json(
{ message: 'Product is already available' },
{ status: 400 }
)
}

product.is_sold = false
product.show_when_sold = false
if (product.quantity <= 0) {
product.quantity = 1
}

await product.save()

return NextResponse.json(
{ message: 'Product is available again', product },
{ status: 200 }
)
} catch (error: unknown) {
console.error('PATCH /api/products/[id]/available error:', error)
return NextResponse.json(
{
message:
error instanceof Error ? error.message : 'Internal Server Error',
},
{ status: 500 }
)
}
}
122 changes: 122 additions & 0 deletions app/api/products/[id]/comments/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import dbConnect from '@/lib/dbConnect'
import { NextRequest, NextResponse } from 'next/server'
import mongoose from 'mongoose'
import Product, { IComment } from '@/model/Product'

Check warning on line 4 in app/api/products/[id]/comments/route.ts

View workflow job for this annotation

GitHub Actions / Lint

'IComment' is defined but never used
import User from '@/model/User'

Check warning on line 5 in app/api/products/[id]/comments/route.ts

View workflow job for this annotation

GitHub Actions / Lint

'User' is defined but never used
import { verifyJwt } from '@/lib/auth-utils'

type RouteContext = { params: Promise<{ id: string }> }

/**
* POST /api/products/:id/comments
* Add a new comment or reply to an existing comment.
*/
export async function POST(req: NextRequest, context: RouteContext) {
try {
await dbConnect()

const { id } = await context.params

if (!mongoose.Types.ObjectId.isValid(id)) {
return NextResponse.json(
{ message: 'Invalid product ID' },
{ status: 400 }
)
}

// Authenticate the user
const authResponse = await verifyJwt(req)
if (authResponse.status !== 200) {
return authResponse
}

const authData = await authResponse.json()
const userId = authData.userId as string

const body = await req.json()
const { text, offerPrice, parentCommentId } = body

if (!text || !String(text).trim()) {
return NextResponse.json(
{ message: 'Comment text is required' },
{ status: 400 }
)
}

const product = await Product.findById(id)
if (!product) {
return NextResponse.json(
{ message: 'Product not found' },
{ status: 404 }
)
}

if (!product.comments) {
product.comments = []
}

const newReply = {
user: new mongoose.Types.ObjectId(userId),
text: String(text).trim().substring(0, 500),
createdAt: new Date(),
}

if (parentCommentId) {
// It's a reply
if (!mongoose.Types.ObjectId.isValid(parentCommentId)) {
return NextResponse.json(
{ message: 'Invalid parent comment ID' },
{ status: 400 }
)
}

const parentComment = product.comments.find(
(c: any) => c._id && c._id.toString() === parentCommentId

Check failure on line 74 in app/api/products/[id]/comments/route.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
) as any

Check failure on line 75 in app/api/products/[id]/comments/route.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (!parentComment) {
return NextResponse.json(
{ message: 'Parent comment not found' },
{ status: 404 }
)
}

parentComment.replies.push(newReply)
} else {
// Top level comment
const newComment = {
user: new mongoose.Types.ObjectId(userId),
text: String(text).trim().substring(0, 1000),
offerPrice:
offerPrice !== undefined && offerPrice !== null && offerPrice !== ''
? Number(offerPrice)
: undefined,
Comment on lines +89 to +92
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Validate offerPrice is a valid positive number.

The current check allows any truthy value to be converted to Number(), which could result in NaN being stored if a non-numeric string is passed.

🛡️ Proposed fix
         offerPrice:
-          offerPrice !== undefined && offerPrice !== null && offerPrice !== ''
-            ? Number(offerPrice)
+          offerPrice !== undefined && offerPrice !== null && offerPrice !== '' &&
+          !isNaN(Number(offerPrice)) && Number(offerPrice) >= 0
+            ? Number(offerPrice)
             : undefined,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
offerPrice:
offerPrice !== undefined && offerPrice !== null && offerPrice !== ''
? Number(offerPrice)
: undefined,
offerPrice:
offerPrice !== undefined && offerPrice !== null && offerPrice !== '' &&
!isNaN(Number(offerPrice)) && Number(offerPrice) >= 0
? Number(offerPrice)
: undefined,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/api/products/`[id]/comments/route.ts around lines 89 - 92, The current
assignment for offerPrice blindly converts any truthy value to Number(), which
can produce NaN; update the logic around offerPrice (in the route handler that
prepares the comment payload) to first coerce to string and trim, then parse
with parseFloat and only use the numeric value if Number.isFinite(parsed) &&
parsed > 0; otherwise set offerPrice to undefined (or return a 400 validation
error if you prefer strict validation). Reference the existing offerPrice
variable and the payload construction where offerPrice is assigned to locate and
replace the conversion logic.

createdAt: new Date(),
replies: [],
}
product.comments.push(newComment as any)

Check failure on line 96 in app/api/products/[id]/comments/route.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
}

await product.save()

// We want the populated user info back, so we populate the newly added part, or just fetch the whole product populated
const populatedProduct = await Product.findById(product._id)
.populate('seller', 'name email image')
.populate({ path: 'comments.user', select: 'name email image' })
.populate({ path: 'comments.replies.user', select: 'name email image' })
.lean()

return NextResponse.json(
{ message: 'Comment added successfully', product: populatedProduct },
{ status: 201 }
)
} catch (error: unknown) {
console.error('POST /api/products/[id]/comments error:', error)
return NextResponse.json(
{
message:
error instanceof Error ? error.message : 'Internal Server Error',
},
{ status: 500 }
)
}
}
Loading
Loading