chore: track Payload web application
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/** Agent update endpoint: PUT /api/agent/posts/:slug */
|
||||
export async function PUT(req: NextRequest, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const key = process.env.AGENT_API_KEY
|
||||
if (!key || req.headers.get('x-agent-key') !== key) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { slug } = await ctx.params
|
||||
const body = (await req.json().catch(() => null)) as Record<string, unknown> | null
|
||||
if (!body) return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
})
|
||||
const post = existing.docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'not found' }, { status: 404 })
|
||||
|
||||
// Only writable fields; status is admin-only
|
||||
const allowed = ['title', 'slug', 'dek', 'teaser', 'content', 'category', 'access', 'readingMinutes', 'cover'] as const
|
||||
const data: Record<string, unknown> = {}
|
||||
for (const field of allowed) {
|
||||
if (field in body) data[field] = body[field]
|
||||
}
|
||||
|
||||
const doc = await payload.update({ collection: 'posts', id: post.id, data, depth: 0 })
|
||||
return NextResponse.json({
|
||||
id: doc.id, title: doc.title, slug: doc.slug,
|
||||
status: doc.status, access: doc.access, category: doc.category,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import type { Payload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
type Body = Record<string, unknown>
|
||||
|
||||
function unauthorized() {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
function validKey(req: NextRequest) {
|
||||
const key = process.env.AGENT_API_KEY
|
||||
if (!key) return false
|
||||
return req.headers.get('x-agent-key') === key
|
||||
}
|
||||
|
||||
/** Fields the agent is allowed to write; status is NEVER included. */
|
||||
function pickFields(body: Body): Body {
|
||||
const allowed = ['title', 'slug', 'dek', 'teaser', 'content', 'category', 'access', 'readingMinutes', 'cover'] as const
|
||||
const out: Body = {}
|
||||
for (const field of allowed) {
|
||||
if (field in body) out[field] = body[field]
|
||||
}
|
||||
// cover omitted → per-category default assigned below (seeded covers)
|
||||
return out
|
||||
}
|
||||
|
||||
const CATEGORY_COVER_SLUGS: Record<string, string> = {
|
||||
'وكلاء': 'cover-agents',
|
||||
'نماذج': 'cover-models',
|
||||
'استرجاع': 'cover-retrieval',
|
||||
'سلامة': 'cover-safety',
|
||||
'أدوات': 'cover-tools',
|
||||
'أعمال': 'cover-business',
|
||||
}
|
||||
|
||||
async function defaultCoverId(payload: Payload, category: unknown) {
|
||||
const filename = CATEGORY_COVER_SLUGS[String(category)] || 'cover-default'
|
||||
const res = await payload.find({
|
||||
collection: 'media',
|
||||
where: { filename: { equals: `${filename}.jpg` } },
|
||||
limit: 1,
|
||||
})
|
||||
return res.docs[0]?.id
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!validKey(req)) return unauthorized()
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const body = (await req.json().catch(() => null)) as Body | null
|
||||
if (!body || typeof body.slug !== 'string' || !body.slug) {
|
||||
return NextResponse.json({ error: 'slug is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Slug conflict → 409
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: body.slug } },
|
||||
limit: 1,
|
||||
})
|
||||
if (existing.docs.length > 0) {
|
||||
return NextResponse.json({ error: 'slug already exists' }, { status: 409 })
|
||||
}
|
||||
|
||||
const data = pickFields(body)
|
||||
if (!data.cover) data.cover = await defaultCoverId(payload, data.category)
|
||||
if (!data.content || typeof data.content !== 'object') {
|
||||
// minimal valid Lexical doc (empty root is rejected by validation); agent PUTs full content later
|
||||
data.content = {
|
||||
root: {
|
||||
type: 'root', format: '', indent: 0, version: 1, direction: 'rtl',
|
||||
children: [{ type: 'paragraph', version: 1, children: [{ type: 'text', version: 1, text: '…' }] }],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const doc = await payload.create({
|
||||
collection: 'posts',
|
||||
data: { ...data, status: 'draft' },
|
||||
draft: true,
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
slug: doc.slug,
|
||||
status: doc.status,
|
||||
access: doc.access,
|
||||
category: doc.category,
|
||||
}, { status: 201 })
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
if (!validKey(req)) return unauthorized()
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const slug = req.nextUrl.pathname.split('/').filter(Boolean).pop() as string
|
||||
const body = (await req.json().catch(() => null)) as Body | null
|
||||
if (!body) return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = existing.docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'not found' }, { status: 404 })
|
||||
|
||||
const data = pickFields(body)
|
||||
delete (data as Body).status // agent can never publish/unpublish
|
||||
|
||||
const doc = await payload.update({
|
||||
collection: 'posts',
|
||||
id: post.id,
|
||||
data,
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
slug: doc.slug,
|
||||
status: doc.status,
|
||||
access: doc.access,
|
||||
category: doc.category,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import { randomBytes } from 'crypto'
|
||||
import configPromise from '@payload-config'
|
||||
import { sendVerificationEmail } from '@/lib/mail'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/auth/resend-verification — logged-in user asks for a fresh
|
||||
verification email. Regenerates the token so old links die. */
|
||||
export async function POST() {
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (user.emailVerified) return NextResponse.json({ already: true })
|
||||
|
||||
const token = randomBytes(32).toString('hex')
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { verificationToken: token },
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
const { sent } = await sendVerificationEmail(user.email, token)
|
||||
if (!sent) {
|
||||
return NextResponse.json(
|
||||
{ error: 'خدمة البريد غير مربوطة بعد — ستعمل تلقائياً بعد ضبط SMTP على الاستضافة.' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ sent: true })
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { redirect } from 'next/navigation'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* GET /api/auth/verify-email?token=... — the link sent by email.
|
||||
Marks the account verified and lands the user on onboarding. */
|
||||
export async function GET(request: Request) {
|
||||
const token = new URL(request.url).searchParams.get('token')
|
||||
if (!token) redirect('/verify-email?invalid=1')
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { docs } = await payload.find({
|
||||
collection: 'users',
|
||||
where: { verificationToken: { equals: token } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const user = docs[0]
|
||||
if (!user) redirect('/verify-email?invalid=1')
|
||||
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { emailVerified: true, verificationToken: null },
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
redirect('/onboarding')
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/comments — create a moderated comment.
|
||||
Signed-in only (401); VIP post requires entitlement (403); 1 comment / 60 s
|
||||
per user, counting pending (429); body 8–2000 chars (400).
|
||||
NOTE: deliberately NOT /api/comments — Payload mounts its admin REST there
|
||||
(see docs/adr/0001-comments-route-not-at-api-comments.md). */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'سجّل الدخول للتعليق.' }, { status: 401 })
|
||||
|
||||
const parsed = await _request.json().catch(() => null)
|
||||
const text = typeof parsed?.body === 'string' ? parsed.body.trim() : ''
|
||||
if (text.length < 8) return NextResponse.json({ error: 'اكتب تعليقاً من ٨ أحرف على الأقل.' }, { status: 400 })
|
||||
if (text.length > 2000) return NextResponse.json({ error: 'التعليق طويل جداً — ٢٠٠٠ حرف كحد أقصى.' }, { status: 400 })
|
||||
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { and: [{ slug: { equals: slug } }, { status: { equals: 'published' } }] },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
})
|
||||
const post = docs[0] as unknown as { id: number; access: string } | undefined
|
||||
if (!post) return NextResponse.json({ error: 'المقال غير موجود.' }, { status: 404 })
|
||||
|
||||
// Mirror the UI paywall: commenting on a VIP post requires entitlement.
|
||||
const role = (user as { role?: string }).role
|
||||
if (post.access === 'vip' && role !== 'vip' && role !== 'admin') {
|
||||
return NextResponse.json({ error: 'التعليق على هذا الدليل متاح لأعضاء العضوية.' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Naive per-user rate limit: 1 comment / 60 s, any post, counts pending.
|
||||
const recent = await payload.find({
|
||||
collection: 'comments',
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
where: {
|
||||
and: [
|
||||
{ author: { equals: user.id } },
|
||||
{ createdAt: { greater_than: new Date(Date.now() - 60_000) } },
|
||||
],
|
||||
},
|
||||
})
|
||||
if (recent.docs.length) return NextResponse.json({ error: 'تمهّل قليلاً قبل تعليق جديد.' }, { status: 429 })
|
||||
|
||||
const fullName = (user as { fullName?: string }).fullName
|
||||
await payload.create({
|
||||
collection: 'comments',
|
||||
data: { post: post.id, author: user.id, authorName: fullName || 'عضو', body: text, status: 'pending' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
return NextResponse.json({ ok: true, pending: true }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/like — toggle. Login required (401 otherwise);
|
||||
one like per user per post (PostLikes uniqueness); likes counter on post. */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
select: { likes: true },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'post-likes',
|
||||
where: { and: [{ user: { equals: user.id } }, { post: { equals: post.id } }] },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
let liked: boolean
|
||||
if (existing.docs.length > 0) {
|
||||
await payload.delete({ collection: 'post-likes', id: existing.docs[0].id, overrideAccess: true })
|
||||
liked = false
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: 'post-likes',
|
||||
data: { user: user.id, post: post.id },
|
||||
overrideAccess: true,
|
||||
})
|
||||
liked = true
|
||||
}
|
||||
|
||||
const likes = Math.max(0, (typeof post.likes === 'number' ? post.likes : 0) + (liked ? 1 : -1))
|
||||
await payload.update({ collection: 'posts', id: post.id, data: { likes }, overrideAccess: true })
|
||||
return NextResponse.json({ liked, likes })
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/view — global view counter (client fires this once
|
||||
per browser session per post, from the post page). */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
select: { views: true },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const views = (typeof post.views === 'number' ? post.views : 0) + 1
|
||||
await payload.update({ collection: 'posts', id: post.id, data: { views }, overrideAccess: true })
|
||||
return NextResponse.json({ views })
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import Stripe from 'stripe'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const secret = process.env.STRIPE_SECRET_KEY
|
||||
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET
|
||||
if (!secret || !webhookSecret) {
|
||||
return NextResponse.json({ error: 'Stripe not configured' }, { status: 503 })
|
||||
}
|
||||
|
||||
const stripe = new Stripe(secret)
|
||||
const signature = req.headers.get('stripe-signature')
|
||||
if (!signature) return NextResponse.json({ error: 'Missing signature' }, { status: 400 })
|
||||
|
||||
const rawBody = await req.text()
|
||||
let event: Stripe.Event
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret)
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
|
||||
if (event.type === 'checkout.session.completed') {
|
||||
const session = event.data.object
|
||||
const userId = session.client_reference_id || session.metadata?.payloadUserId
|
||||
if (userId) {
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: userId,
|
||||
data: { role: 'vip' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === 'customer.subscription.deleted') {
|
||||
const subscription = event.data.object
|
||||
const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id
|
||||
const { docs } = await payload.find({
|
||||
collection: 'users',
|
||||
where: { stripeCustomerId: { equals: customerId } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
for (const u of docs) {
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: u.id,
|
||||
data: { role: 'free' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ received: true })
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import type { Payload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import Stripe from 'stripe'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST() {
|
||||
const secret = process.env.STRIPE_SECRET_KEY
|
||||
const priceId = process.env.STRIPE_PRICE_ID
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'
|
||||
|
||||
// Stripe pending mode: no keys yet → simulated gateway. The flow completes
|
||||
// through /payment-success (which activates VIP on the logged-in account);
|
||||
// adding STRIPE_SECRET_KEY + STRIPE_PRICE_ID switches to real Checkout with
|
||||
// the same success/cancel pages.
|
||||
if (!secret || !priceId) {
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
return NextResponse.json({ url: '/payment-success?simulated=1' })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const stripe = new Stripe(secret)
|
||||
let customerId = user.stripeCustomerId as string | undefined
|
||||
if (!customerId) {
|
||||
const customer = await stripe.customers.create({
|
||||
email: user.email,
|
||||
metadata: { payloadUserId: String(user.id) },
|
||||
})
|
||||
customerId = customer.id
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { stripeCustomerId: customerId },
|
||||
})
|
||||
}
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
client_reference_id: String(user.id),
|
||||
success_url: `${siteUrl}/payment-success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${siteUrl}/payment-cancelled`,
|
||||
})
|
||||
|
||||
return NextResponse.json({ url: session.url })
|
||||
}
|
||||
Reference in New Issue
Block a user