SEO: Fix structured data validation errors, delete static sitemap, and update indexing scripts

This commit is contained in:
Timo Knuth
2026-01-23 23:10:22 +01:00
parent f3637fc2fe
commit eef4855c1b
147 changed files with 24590 additions and 27027 deletions

View File

@@ -0,0 +1,122 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
import { cookies } from 'next/headers';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
let userId: string | undefined;
// Try NextAuth session first
const session = await getServerSession(authOptions);
if (session?.user?.id) {
userId = session.user.id;
} else {
// Fallback: Check raw userId cookie (like /api/user does)
const cookieStore = await cookies();
userId = cookieStore.get('userId')?.value;
}
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id } = await params;
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const limit = parseInt(searchParams.get('limit') || '20');
const skip = (page - 1) * limit;
// Verify QR ownership and type
const qrCode = await db.qRCode.findUnique({
where: { id, userId: userId },
select: { id: true, contentType: true },
});
if (!qrCode) {
return NextResponse.json({ error: 'QR code not found' }, { status: 404 });
}
// Check if consistent with schema (Prisma enum mismatch fix)
// @ts-ignore - Temporary ignore until client regeneration catches up fully in all envs
if (qrCode.contentType !== 'FEEDBACK') {
return NextResponse.json({ error: 'Not a feedback QR code' }, { status: 400 });
}
// Fetch feedback entries (stored as QRScans with ipHash='feedback')
const [feedbackEntries, totalCount] = await Promise.all([
db.qRScan.findMany({
where: { qrId: id, ipHash: 'feedback' },
orderBy: { ts: 'desc' },
skip,
take: limit,
select: { id: true, userAgent: true, ts: true },
}),
db.qRScan.count({
where: { qrId: id, ipHash: 'feedback' },
}),
]);
// Parse feedback data from userAgent field
const feedbacks = feedbackEntries.map((entry) => {
const parsed = parseFeedback(entry.userAgent || '');
return {
id: entry.id,
rating: parsed.rating,
comment: parsed.comment,
date: entry.ts,
};
});
// Calculate stats
const allRatings = await db.qRScan.findMany({
where: { qrId: id, ipHash: 'feedback' },
select: { userAgent: true },
});
const ratings = allRatings.map((e) => parseFeedback(e.userAgent || '').rating).filter((r) => r > 0);
const avgRating = ratings.length > 0 ? ratings.reduce((a, b) => a + b, 0) / ratings.length : 0;
// Rating distribution
const distribution = {
5: ratings.filter((r) => r === 5).length,
4: ratings.filter((r) => r === 4).length,
3: ratings.filter((r) => r === 3).length,
2: ratings.filter((r) => r === 2).length,
1: ratings.filter((r) => r === 1).length,
};
return NextResponse.json({
feedbacks,
stats: {
total: totalCount,
avgRating: Math.round(avgRating * 10) / 10,
distribution,
},
pagination: {
page,
limit,
totalPages: Math.ceil(totalCount / limit),
hasMore: skip + limit < totalCount,
},
});
} catch (error) {
console.error('Error fetching feedback:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
function parseFeedback(userAgent: string): { rating: number; comment: string } {
// Format: "rating:4|comment:Great service!"
const ratingMatch = userAgent.match(/rating:(\d)/);
const commentMatch = userAgent.match(/comment:(.+)/);
return {
rating: ratingMatch ? parseInt(ratingMatch[1]) : 0,
comment: commentMatch ? commentMatch[1] : '',
};
}

View File

@@ -0,0 +1,205 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { db } from '@/lib/db';
import { z } from 'zod';
import { csrfProtection } from '@/lib/csrf';
import { rateLimit, getClientIdentifier, RateLimits } from '@/lib/rateLimit';
const updateQRSchema = z.object({
title: z.string().min(1).optional(),
content: z.any().optional(),
tags: z.array(z.string()).optional(),
style: z.any().optional(),
});
// GET /api/qrs/[id] - Get a single QR code
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const userId = cookies().get('userId')?.value;
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const qrCode = await db.qRCode.findFirst({
where: {
id: params.id,
userId,
},
include: {
scans: {
orderBy: { ts: 'desc' },
take: 100,
},
},
});
if (!qrCode) {
return NextResponse.json({ error: 'QR code not found' }, { status: 404 });
}
return NextResponse.json(qrCode);
} catch (error) {
console.error('Error fetching QR code:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
// PATCH /api/qrs/[id] - Update a QR code
export async function PATCH(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// CSRF Protection
const csrfCheck = csrfProtection(request);
if (!csrfCheck.valid) {
return NextResponse.json({ error: csrfCheck.error }, { status: 403 });
}
const userId = cookies().get('userId')?.value;
// Rate Limiting (user-based)
const clientId = userId || getClientIdentifier(request);
const rateLimitResult = rateLimit(clientId, RateLimits.QR_MODIFY);
if (!rateLimitResult.success) {
return NextResponse.json(
{
error: 'Too many requests. Please try again later.',
retryAfter: Math.ceil((rateLimitResult.reset - Date.now()) / 1000)
},
{
status: 429,
headers: {
'X-RateLimit-Limit': rateLimitResult.limit.toString(),
'X-RateLimit-Remaining': rateLimitResult.remaining.toString(),
'X-RateLimit-Reset': rateLimitResult.reset.toString(),
}
}
);
}
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const data = updateQRSchema.parse(body);
// Check ownership
const existing = await db.qRCode.findFirst({
where: {
id: params.id,
userId,
},
});
if (!existing) {
return NextResponse.json({ error: 'QR code not found' }, { status: 404 });
}
// Static QR codes cannot be edited
if (existing.type === 'STATIC' && data.content) {
return NextResponse.json(
{ error: 'Static QR codes cannot be edited' },
{ status: 400 }
);
}
// Update QR code
const updated = await db.qRCode.update({
where: { id: params.id },
data: {
...(data.title && { title: data.title }),
...(data.content && { content: data.content }),
...(data.tags && { tags: data.tags }),
...(data.style && { style: data.style }),
},
});
return NextResponse.json(updated);
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Invalid input', details: error.errors },
{ status: 400 }
);
}
console.error('Error updating QR code:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
// DELETE /api/qrs/[id] - Delete a QR code
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// CSRF Protection
const csrfCheck = csrfProtection(request);
if (!csrfCheck.valid) {
return NextResponse.json({ error: csrfCheck.error }, { status: 403 });
}
const userId = cookies().get('userId')?.value;
// Rate Limiting (user-based)
const clientId = userId || getClientIdentifier(request);
const rateLimitResult = rateLimit(clientId, RateLimits.QR_MODIFY);
if (!rateLimitResult.success) {
return NextResponse.json(
{
error: 'Too many requests. Please try again later.',
retryAfter: Math.ceil((rateLimitResult.reset - Date.now()) / 1000)
},
{
status: 429,
headers: {
'X-RateLimit-Limit': rateLimitResult.limit.toString(),
'X-RateLimit-Remaining': rateLimitResult.remaining.toString(),
'X-RateLimit-Reset': rateLimitResult.reset.toString(),
}
}
);
}
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check ownership
const existing = await db.qRCode.findFirst({
where: {
id: params.id,
userId,
},
});
if (!existing) {
return NextResponse.json({ error: 'QR code not found' }, { status: 404 });
}
// Delete QR code (cascades to scans)
await db.qRCode.delete({
where: { id: params.id },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting QR code:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}