fix email message x2

This commit is contained in:
ismail 2026-02-02 20:26:22 +01:00
parent ca0a4c6968
commit 0bd38101b4
1 changed files with 24 additions and 28 deletions

View File

@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { verifyToken, TokenPayload } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { sendEmail } from '@/lib/email';
// Email import removed - using dynamic import for sendMessageNotification in POST handler
function getUserFromRequest(request: NextRequest): TokenPayload | null {
const authHeader = request.headers.get('authorization');
@ -94,36 +94,32 @@ export async function POST(request: NextRequest) {
await connection.commit();
// Notify admins via email if they are offline
const [admins] = await pool.query<RowDataPacket[]>(
`SELECT id, email FROM users WHERE role = 'admin'`
// Fetch full sender details for notification
const [senderDetails] = await pool.query<RowDataPacket[]>(
`SELECT full_name, email, mobile, personnummer, address, zip_code, city FROM users WHERE id = ?`,
[user.userId]
);
const sender = senderDetails[0];
for (const admin of admins) {
// Check if admin is online (has active session)
const [sessions] = await pool.query<RowDataPacket[]>(
`SELECT COUNT(*) as count FROM user_sessions
WHERE user_id = ? AND expires_at > NOW()`,
[admin.id]
);
// Send ONE email to CONTACT_EMAIL with premium template
const { sendMessageNotification } = await import('@/lib/email');
const adminEmail = process.env.CONTACT_EMAIL || 'info@nordicstorium.se';
const isOnline = sessions[0].count > 0;
if (!isOnline) {
await sendEmail(
admin.email,
`Nytt meddelande: ${subject}`,
`
<h2>Nytt kundmeddelande</h2>
<p><strong>Från:</strong> ${user.email}</p>
<p><strong>Ämne:</strong> ${subject}</p>
<p><strong>Meddelande:</strong></p>
<blockquote style="border-left: 3px solid #ccc; padding-left: 10px; margin: 10px 0;">${message}</blockquote>
<p><a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/admin/messages/${conversationId}">Svara här</a></p>
`
);
}
}
await sendMessageNotification(
adminEmail,
`Nytt kundmeddelande: ${subject}`,
sender.full_name || 'Kund',
sender.email,
sender.mobile,
sender.personnummer,
sender.address,
sender.zip_code,
sender.city,
message,
`${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/admin/messages`,
'Svara i Adminpanelen',
true // Customer is sender
);
return NextResponse.json({
success: true,