initial commit: rocket.new export of broadcastbeat
This commit is contained in:
100
src/app/api/adops/campaigns/route.ts
Normal file
100
src/app/api/adops/campaigns/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
// Admin-only guard
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// GET /api/adops/campaigns
|
||||
export async function GET(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const publication = searchParams.get('publication');
|
||||
const status = searchParams.get('status');
|
||||
const client = searchParams.get('client');
|
||||
const limit = parseInt(searchParams.get('limit') || '50');
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
|
||||
let query = supabase
|
||||
.from('ad_campaigns')
|
||||
.select('*', { count: 'exact' })
|
||||
.order('created_at', { ascending: false })
|
||||
.range(offset, offset + limit - 1);
|
||||
|
||||
if (publication) query = query.eq('publication_id', publication);
|
||||
if (status) query = query.eq('status', status);
|
||||
if (client) query = query.ilike('client_name', `%${client}%`);
|
||||
|
||||
const { data, error, count } = await query;
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
return NextResponse.json({ campaigns: data, total: count });
|
||||
}
|
||||
|
||||
// POST /api/adops/campaigns
|
||||
export async function POST(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('ad_campaigns')
|
||||
.insert({
|
||||
campaign_name: body.campaign_name,
|
||||
client_name: body.client_name,
|
||||
publication_id: body.publication_id,
|
||||
placement_zone: body.placement_zone,
|
||||
banner_url: body.banner_url,
|
||||
destination_url: body.destination_url,
|
||||
start_date: body.start_date,
|
||||
end_date: body.end_date,
|
||||
agreed_rate: body.agreed_rate,
|
||||
status: body.status || 'pending_info',
|
||||
campaign_type: body.campaign_type || 'banner',
|
||||
blackmagic_excluded: body.blackmagic_excluded || false,
|
||||
notes: body.notes,
|
||||
created_by: user.email,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ campaign: data });
|
||||
}
|
||||
|
||||
// PATCH /api/adops/campaigns
|
||||
export async function PATCH(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
const { id, ...updates } = body;
|
||||
|
||||
if (!id) return NextResponse.json({ error: 'Campaign ID required' }, { status: 400 });
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('ad_campaigns')
|
||||
.update({ ...updates, updated_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ campaign: data });
|
||||
}
|
||||
92
src/app/api/adops/cron/end-campaigns/route.ts
Normal file
92
src/app/api/adops/cron/end-campaigns/route.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// POST /api/adops/cron/end-campaigns — daily midnight check
|
||||
export async function POST(request: NextRequest) {
|
||||
const cronSecret = request.headers.get('x-cron-secret');
|
||||
const isValidCron = cronSecret && cronSecret === process.env.CRON_SECRET;
|
||||
|
||||
if (!isValidCron) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Find campaigns that should end today or earlier
|
||||
const { data: expiredCampaigns } = await supabase
|
||||
.from('ad_campaigns')
|
||||
.select('*')
|
||||
.eq('status', 'active')
|
||||
.lte('end_date', today);
|
||||
|
||||
if (!expiredCampaigns?.length) {
|
||||
return NextResponse.json({ success: true, ended: 0 });
|
||||
}
|
||||
|
||||
let ended = 0;
|
||||
for (const campaign of expiredCampaigns) {
|
||||
await supabase
|
||||
.from('ad_campaigns')
|
||||
.update({
|
||||
status: 'ended',
|
||||
deactivated_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', campaign.id);
|
||||
|
||||
// Send end notification
|
||||
try {
|
||||
const { sendToJeffAndRyan, sendToRyanOnly } = await import('@/lib/adops/adOpsEmailSender');
|
||||
const { campaignEndedEmailJeff, campaignEndedEmailRyan } = await import('@/lib/adops/emailTemplates');
|
||||
|
||||
const jeffEmail = campaignEndedEmailJeff({
|
||||
clientName: campaign.client_name,
|
||||
publication: campaign.publication_id,
|
||||
endDate: campaign.end_date,
|
||||
impressions: campaign.impressions || 0,
|
||||
clicks: campaign.clicks || 0,
|
||||
ctr: campaign.ctr || 0,
|
||||
campaignId: campaign.id,
|
||||
});
|
||||
|
||||
await sendToJeffAndRyan({ subject: jeffEmail.subject, html: jeffEmail.html });
|
||||
|
||||
if (campaign.agreed_rate) {
|
||||
const ryanEmail = campaignEndedEmailRyan({
|
||||
clientName: campaign.client_name,
|
||||
publication: campaign.publication_id,
|
||||
endDate: campaign.end_date,
|
||||
impressions: campaign.impressions || 0,
|
||||
clicks: campaign.clicks || 0,
|
||||
ctr: campaign.ctr || 0,
|
||||
campaignId: campaign.id,
|
||||
agreedRate: campaign.agreed_rate,
|
||||
invoiceId: campaign.mooninvoice_invoice_id,
|
||||
invoiceStatus: 'sent',
|
||||
});
|
||||
await sendToRyanOnly({ subject: ryanEmail.subject, html: ryanEmail.html });
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('[Cron] Email error for campaign', campaign.id, err.message);
|
||||
}
|
||||
|
||||
ended++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, ended });
|
||||
}
|
||||
56
src/app/api/adops/cron/rmp-deactivate/route.ts
Normal file
56
src/app/api/adops/cron/rmp-deactivate/route.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
|
||||
// GET /api/adops/cron/deactivate — run daily 11:59 PM
|
||||
export async function GET(request: NextRequest) {
|
||||
// Verify cron secret
|
||||
const secret = request.headers.get('x-cron-secret') ?? request.nextUrl.searchParams.get('secret');
|
||||
if (secret !== process.env.CRON_SECRET) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const { data: expiring } = await supabase
|
||||
.from('rmp_io_extensions')
|
||||
.select('id, client_id, staff_id, rmp_clients(company_name), rmp_sales_staff(email, full_name)')
|
||||
.in('flight_status', ['active', 'scheduled'])
|
||||
.eq('end_date', today)
|
||||
.eq('auto_deactivate', true);
|
||||
|
||||
let count = 0;
|
||||
for (const io of (expiring ?? [])) {
|
||||
await supabase.from('rmp_io_extensions').update({ flight_status: 'expired', updated_at: new Date().toISOString() }).eq('id', io.id);
|
||||
|
||||
// Log notification
|
||||
await supabase.from('rmp_adops_notifications').insert({
|
||||
io_extension_id: io.id,
|
||||
notification_type: 'flight_expired',
|
||||
recipient_type: 'admin',
|
||||
recipient_email: process.env.NOTIFY_EMAIL,
|
||||
message: `IO ${io.id} for ${(io as any).rmp_clients?.company_name ?? 'unknown'} expired today`,
|
||||
sent_via: 'email',
|
||||
success: true,
|
||||
});
|
||||
|
||||
// Notify salesperson
|
||||
const staffEmail = (io as any).rmp_sales_staff?.email;
|
||||
if (staffEmail) {
|
||||
await supabase.from('rmp_adops_notifications').insert({
|
||||
io_extension_id: io.id,
|
||||
notification_type: 'flight_expired',
|
||||
recipient_type: 'salesperson',
|
||||
recipient_email: staffEmail,
|
||||
message: `Your IO for ${(io as any).rmp_clients?.company_name ?? 'unknown'} has expired`,
|
||||
sent_via: 'email',
|
||||
success: true,
|
||||
});
|
||||
}
|
||||
|
||||
count++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, deactivated: count });
|
||||
}
|
||||
54
src/app/api/adops/cron/rmp-renewal-warnings/route.ts
Normal file
54
src/app/api/adops/cron/rmp-renewal-warnings/route.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
// GET /api/adops/cron/rmp-renewal-warnings — run daily 9:00 AM
|
||||
export async function GET(request: NextRequest) {
|
||||
const secret = request.headers.get('x-cron-secret') ?? request.nextUrl.searchParams.get('secret');
|
||||
if (secret !== process.env.CRON_SECRET) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const in30 = new Date(Date.now() + 30 * 86400000).toISOString().split('T')[0];
|
||||
|
||||
const { data: expiring } = await supabase
|
||||
.from('rmp_io_extensions')
|
||||
.select('id, client_id, staff_id, rmp_clients(company_name), rmp_sales_staff(email, full_name)')
|
||||
.in('flight_status', ['active', 'scheduled'])
|
||||
.eq('end_date', in30)
|
||||
.eq('renewal_notice_sent', false);
|
||||
|
||||
let count = 0;
|
||||
for (const io of (expiring ?? [])) {
|
||||
await supabase.from('rmp_io_extensions').update({ renewal_notice_sent: true, renewal_notice_sent_at: new Date().toISOString() }).eq('id', io.id);
|
||||
|
||||
const staffEmail = (io as any).rmp_sales_staff?.email;
|
||||
const staffName = (io as any).rmp_sales_staff?.full_name ?? 'Salesperson';
|
||||
const clientName = (io as any).rmp_clients?.company_name ?? 'Unknown';
|
||||
|
||||
await supabase.from('rmp_adops_notifications').insert([
|
||||
{
|
||||
io_extension_id: io.id,
|
||||
notification_type: 'renewal_warning',
|
||||
recipient_type: 'admin',
|
||||
recipient_email: process.env.NOTIFY_EMAIL,
|
||||
message: `Renewal warning: IO for ${clientName} expires in 30 days`,
|
||||
sent_via: 'email',
|
||||
success: true,
|
||||
},
|
||||
...(staffEmail ? [{
|
||||
io_extension_id: io.id,
|
||||
notification_type: 'renewal_warning',
|
||||
recipient_type: 'salesperson',
|
||||
recipient_email: staffEmail,
|
||||
message: `Your IO for ${clientName} expires in 30 days — time to renew`,
|
||||
sent_via: 'email',
|
||||
success: true,
|
||||
}] : []),
|
||||
]);
|
||||
|
||||
count++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, warned: count });
|
||||
}
|
||||
96
src/app/api/adops/email-campaigns/route.ts
Normal file
96
src/app/api/adops/email-campaigns/route.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// GET /api/adops/email-campaigns
|
||||
export async function GET(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const publication = searchParams.get('publication');
|
||||
const status = searchParams.get('status');
|
||||
const isNewsletter = searchParams.get('newsletter');
|
||||
|
||||
let query = supabase
|
||||
.from('adops_email_campaigns')
|
||||
.select('*, email_lists(list_name, subscriber_count)')
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (publication) query = query.eq('publication_id', publication);
|
||||
if (status) query = query.eq('status', status);
|
||||
if (isNewsletter !== null) query = query.eq('is_newsletter', isNewsletter === 'true');
|
||||
|
||||
const { data, error } = await query;
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
return NextResponse.json({ campaigns: data });
|
||||
}
|
||||
|
||||
// POST /api/adops/email-campaigns
|
||||
export async function POST(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('adops_email_campaigns')
|
||||
.insert({
|
||||
campaign_name: body.campaign_name,
|
||||
client_name: body.client_name,
|
||||
publication_id: body.publication_id,
|
||||
list_id: body.list_id,
|
||||
subject: body.subject,
|
||||
from_name: body.from_name,
|
||||
from_email: body.from_email,
|
||||
reply_to: body.reply_to,
|
||||
html_content: body.html_content,
|
||||
send_date: body.send_date,
|
||||
send_time_et: body.send_time_et || '11:00',
|
||||
status: 'draft',
|
||||
agreed_rate: body.agreed_rate,
|
||||
is_newsletter: body.is_newsletter || false,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ campaign: data });
|
||||
}
|
||||
|
||||
// PATCH /api/adops/email-campaigns
|
||||
export async function PATCH(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
const { id, ...updates } = body;
|
||||
|
||||
if (!id) return NextResponse.json({ error: 'Campaign ID required' }, { status: 400 });
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('adops_email_campaigns')
|
||||
.update({ ...updates, updated_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ campaign: data });
|
||||
}
|
||||
34
src/app/api/adops/onboard/route.ts
Normal file
34
src/app/api/adops/onboard/route.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { jeffWelcomeEmail } from '@/lib/adops/emailTemplates';
|
||||
import { sendAdOpsEmail } from '@/lib/adops/adOpsEmailSender';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// POST /api/adops/onboard — send Jeff's welcome email
|
||||
export async function POST(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const welcome = jeffWelcomeEmail();
|
||||
const result = await sendAdOpsEmail({
|
||||
to: welcome.to,
|
||||
cc: [welcome.cc],
|
||||
subject: welcome.subject,
|
||||
html: welcome.html,
|
||||
alwaysCcRyan: false,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: result.success, error: result.error });
|
||||
}
|
||||
76
src/app/api/adops/poll/route.ts
Normal file
76
src/app/api/adops/poll/route.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { pollImapInbox, processInboundEmail } from '@/lib/adops/imapMonitor';
|
||||
import { retryPendingInvoices } from '@/lib/adops/adOpsInvoiceService';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// POST /api/adops/poll — trigger IMAP poll (called by cron or manually)
|
||||
export async function POST(request: NextRequest) {
|
||||
// Allow cron secret or admin auth
|
||||
const cronSecret = request.headers.get('x-cron-secret');
|
||||
const isValidCron = cronSecret && cronSecret === process.env.CRON_SECRET;
|
||||
|
||||
if (!isValidCron) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const action = body.action || 'poll';
|
||||
|
||||
if (action === 'retry_invoices') {
|
||||
await retryPendingInvoices();
|
||||
return NextResponse.json({ success: true, action: 'retry_invoices' });
|
||||
}
|
||||
|
||||
// Poll IMAP
|
||||
const emails = await pollImapInbox();
|
||||
let processed = 0;
|
||||
let errors = 0;
|
||||
|
||||
for (const email of emails) {
|
||||
try {
|
||||
await processInboundEmail(email);
|
||||
processed++;
|
||||
} catch (err: any) {
|
||||
console.error('[AdOps Poll] Error processing email:', err.message);
|
||||
errors++;
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
found: emails.length,
|
||||
processed,
|
||||
errors,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
// GET /api/adops/poll — get inbox log
|
||||
export async function GET(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const { data, error } = await supabase
|
||||
.from('adops_inbox_log')
|
||||
.select('*')
|
||||
.order('received_at', { ascending: false })
|
||||
.limit(50);
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ logs: data });
|
||||
}
|
||||
91
src/app/api/adops/preview/route.ts
Normal file
91
src/app/api/adops/preview/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
// GET /api/adops/preview — render banner preview HTML (screenshot fallback)
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const bannerUrl = searchParams.get('bannerUrl') || '';
|
||||
const w = searchParams.get('w') || '728';
|
||||
const h = searchParams.get('h') || '90';
|
||||
const campaignId = searchParams.get('campaignId') || '';
|
||||
|
||||
const html = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Banner Preview</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: Arial, sans-serif; background: #1a1a2e; color: #eee; min-height: 100vh; }
|
||||
.site-header { background: #0f0f1a; border-bottom: 2px solid #333; padding: 16px 24px; display: flex; align-items: center; gap: 12px; }
|
||||
.site-logo { font-size: 22px; font-weight: bold; color: #e87722; }
|
||||
.site-nav { display: flex; gap: 16px; margin-left: 24px; }
|
||||
.site-nav a { color: #aaa; text-decoration: none; font-size: 14px; }
|
||||
.content { max-width: 1200px; margin: 0 auto; padding: 24px; display: flex; gap: 24px; }
|
||||
.main { flex: 1; }
|
||||
.sidebar { width: 300px; }
|
||||
.ad-wrapper { text-align: center; margin-bottom: 24px; }
|
||||
.ad-label { font-size: 10px; color: #888; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
|
||||
.ad-frame { display: inline-block; border: 3px solid #e74c3c; position: relative; }
|
||||
.ad-badge { position: absolute; top: -1px; right: -1px; background: #e74c3c; color: white; font-size: 10px; padding: 2px 6px; font-weight: bold; }
|
||||
.article-card { background: #252535; border-radius: 8px; padding: 16px; margin-bottom: 16px; }
|
||||
.article-card h2 { font-size: 18px; margin-bottom: 8px; color: #fff; }
|
||||
.article-card p { font-size: 14px; color: #aaa; line-height: 1.5; }
|
||||
.preview-info { background: #1e1e30; border: 1px solid #333; border-radius: 8px; padding: 16px; margin-bottom: 16px; font-size: 13px; }
|
||||
.preview-info h3 { color: #e87722; margin-bottom: 8px; font-size: 14px; }
|
||||
.preview-info table { width: 100%; }
|
||||
.preview-info td { padding: 4px 0; color: #aaa; }
|
||||
.preview-info td:first-child { color: #888; width: 120px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="site-header">
|
||||
<div class="site-logo">Broadcast Beat</div>
|
||||
<nav class="site-nav">
|
||||
<a href="#">News</a>
|
||||
<a href="#">Reviews</a>
|
||||
<a href="#">Features</a>
|
||||
<a href="#">Forum</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="main">
|
||||
<div class="ad-wrapper">
|
||||
<div class="ad-label">Advertisement</div>
|
||||
<div class="ad-frame">
|
||||
<div class="ad-badge">AD PREVIEW</div>
|
||||
${bannerUrl
|
||||
? `<img src="${bannerUrl}" width="${w}" height="${h}" alt="Banner Ad" style="display:block;">`
|
||||
: `<div style="width:${w}px;height:${h}px;background:#2a2a3e;display:flex;align-items:center;justify-content:center;color:#666;font-size:14px;">Banner Image (${w}×${h})</div>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="article-card">
|
||||
<h2>Sample Article: Industry News Headline</h2>
|
||||
<p>This is a sample article to show how the banner appears in context on the publication page. The actual page will have real content from the publication's CMS.</p>
|
||||
</div>
|
||||
<div class="article-card">
|
||||
<h2>Another Recent Story</h2>
|
||||
<p>Additional content to demonstrate the banner placement in a realistic editorial environment.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sidebar">
|
||||
<div class="preview-info">
|
||||
<h3>Preview Info</h3>
|
||||
<table>
|
||||
<tr><td>Dimensions:</td><td>${w}×${h}px</td></tr>
|
||||
<tr><td>Campaign ID:</td><td style="font-size:11px;word-break:break-all;">${campaignId}</td></tr>
|
||||
<tr><td>Status:</td><td style="color:#f39c12;">Pending Approval</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
return new NextResponse(html, {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
});
|
||||
}
|
||||
20
src/app/api/adops/rmp/email-schedule/route.ts
Normal file
20
src/app/api/adops/rmp/email-schedule/route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireAdopsAccess } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('rmp_io_extensions')
|
||||
.select('*, rmp_clients(company_name), rmp_products(name, product_type), rmp_orders(site)')
|
||||
.not('email_scheduled_date', 'is', null)
|
||||
.order('email_scheduled_date', { ascending: true });
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
return NextResponse.json({ schedule: data ?? [] });
|
||||
}
|
||||
29
src/app/api/adops/rmp/flights/route.ts
Normal file
29
src/app/api/adops/rmp/flights/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireAdopsAccess } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const status = searchParams.get('status');
|
||||
const site = searchParams.get('site');
|
||||
|
||||
let query = supabase
|
||||
.from('rmp_io_extensions')
|
||||
.select('*, rmp_clients(company_name), rmp_products(name), rmp_sales_staff(full_name), rmp_orders(site)')
|
||||
.in('flight_status', ['active', 'scheduled'])
|
||||
.order('start_date', { ascending: false });
|
||||
|
||||
if (status) query = query.eq('flight_status', status);
|
||||
|
||||
const { data, error } = await query;
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
let filtered = data ?? [];
|
||||
if (site) filtered = filtered.filter((io: any) => io.rmp_orders?.site === site);
|
||||
|
||||
return NextResponse.json({ flights: filtered });
|
||||
}
|
||||
26
src/app/api/adops/rmp/ios/[id]/status/route.ts
Normal file
26
src/app/api/adops/rmp/ios/[id]/status/route.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireAdopsAccess } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
|
||||
const updates: Record<string, any> = { flight_status: body.flight_status, updated_at: new Date().toISOString() };
|
||||
if (body.flight_status === 'active' && body.reactivation_reason) {
|
||||
updates.reactivated_at = new Date().toISOString();
|
||||
updates.reactivation_reason = body.reactivation_reason;
|
||||
}
|
||||
|
||||
const { error } = await supabase.from('rmp_io_extensions').update(updates).eq('id', id);
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
72
src/app/api/adops/rmp/ios/route.ts
Normal file
72
src/app/api/adops/rmp/ios/route.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireAdopsAccess } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const status = searchParams.get('status');
|
||||
const site = searchParams.get('site');
|
||||
|
||||
let query = supabase
|
||||
.from('rmp_io_extensions')
|
||||
.select('*, rmp_clients(company_name), rmp_products(name, product_type, dimensions), rmp_sales_staff(full_name), rmp_orders(site)')
|
||||
.order('start_date', { ascending: false });
|
||||
|
||||
if (status) query = query.eq('flight_status', status);
|
||||
|
||||
const { data, error } = await query;
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
// Filter by site via joined order
|
||||
let filtered = data ?? [];
|
||||
if (site) filtered = filtered.filter((io: any) => io.rmp_orders?.site === site);
|
||||
|
||||
// Hide pricing for adops_uploader
|
||||
if (auth.role === 'adops_uploader') {
|
||||
filtered = filtered.map((io: any) => {
|
||||
const { is_paid, ...rest } = io;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ ios: filtered });
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const body = await request.json();
|
||||
|
||||
const { data, error } = await supabase.from('rmp_io_extensions').insert({
|
||||
existing_io_id: body.existing_io_id,
|
||||
order_id: body.order_id || null,
|
||||
product_id: body.product_id || null,
|
||||
staff_id: body.staff_id || null,
|
||||
client_id: body.client_id || null,
|
||||
is_comp: body.is_comp ?? false,
|
||||
comp_reason: body.comp_reason || null,
|
||||
is_paid: body.is_paid ?? false,
|
||||
flight_status: body.flight_status ?? 'scheduled',
|
||||
start_date: body.start_date,
|
||||
end_date: body.end_date || null,
|
||||
auto_deactivate: body.auto_deactivate ?? true,
|
||||
banner_image_url: body.banner_image_url || null,
|
||||
click_through_url: body.click_through_url || null,
|
||||
alt_text: body.alt_text || null,
|
||||
email_html_url: body.email_html_url || null,
|
||||
email_scheduled_date: body.email_scheduled_date || null,
|
||||
email_list_segment: body.email_list_segment || null,
|
||||
page_url: body.page_url || null,
|
||||
newsletter_issue_date: body.newsletter_issue_date || null,
|
||||
notes: body.notes || null,
|
||||
}).select().single();
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
return NextResponse.json({ io: data });
|
||||
}
|
||||
20
src/app/api/adops/rmp/notifications/route.ts
Normal file
20
src/app/api/adops/rmp/notifications/route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireAdopsAccess } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAdopsAccess();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('rmp_adops_notifications')
|
||||
.select('*')
|
||||
.order('sent_at', { ascending: false })
|
||||
.limit(100);
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
|
||||
return NextResponse.json({ notifications: data ?? [] });
|
||||
}
|
||||
31
src/app/api/adops/rmp/stats/route.ts
Normal file
31
src/app/api/adops/rmp/stats/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { requireRmpAdmin } from '@/lib/accounting/rmpService';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireRmpAdmin();
|
||||
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const supabase = await createClient();
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
const in30 = new Date(Date.now() + 30 * 86400000).toISOString().split('T')[0];
|
||||
const monthStart = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-01`;
|
||||
|
||||
const [activeR, expiring30R, expiredMonthR, compedR, unpaidR, emailR] = await Promise.all([
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('flight_status', 'active'),
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).in('flight_status', ['active', 'scheduled']).lte('end_date', in30).gte('end_date', today),
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('flight_status', 'expired').gte('end_date', monthStart),
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('is_comp', true).eq('flight_status', 'active'),
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('is_paid', false).eq('flight_status', 'active'),
|
||||
supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).not('email_scheduled_date', 'is', null).is('email_sent_at', null),
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
active: activeR.count ?? 0,
|
||||
expiring_30d: expiring30R.count ?? 0,
|
||||
expired_month: expiredMonthR.count ?? 0,
|
||||
comped: compedR.count ?? 0,
|
||||
unpaid_active: unpaidR.count ?? 0,
|
||||
email_scheduled: emailR.count ?? 0,
|
||||
});
|
||||
}
|
||||
64
src/app/api/adops/stats/route.ts
Normal file
64
src/app/api/adops/stats/route.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
async function requireAdmin(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return null;
|
||||
const { data: profile } = await supabase
|
||||
.from('user_profiles')
|
||||
.select('role')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
// GET /api/adops/stats — overview stats for dashboard
|
||||
export async function GET(request: NextRequest) {
|
||||
const user = await requireAdmin(request);
|
||||
if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const supabase = await createClient();
|
||||
|
||||
const [
|
||||
{ data: activeCampaigns },
|
||||
{ data: pendingApprovals },
|
||||
{ data: endingSoon },
|
||||
{ data: recentCampaigns },
|
||||
{ data: emailCampaigns },
|
||||
] = await Promise.all([
|
||||
supabase.from('ad_campaigns').select('id', { count: 'exact' }).eq('status', 'active'),
|
||||
supabase.from('ad_campaigns').select('id', { count: 'exact' }).in('status', ['pending_approval', 'pending_info']),
|
||||
supabase.from('ad_campaigns')
|
||||
.select('id', { count: 'exact' })
|
||||
.eq('status', 'active')
|
||||
.lte('end_date', new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]),
|
||||
supabase.from('ad_campaigns')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10),
|
||||
supabase.from('adops_email_campaigns')
|
||||
.select('id', { count: 'exact' })
|
||||
.gte('send_date', new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0]),
|
||||
]);
|
||||
|
||||
// Revenue this month
|
||||
const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
|
||||
const { data: monthRevenue } = await supabase
|
||||
.from('ad_campaigns')
|
||||
.select('agreed_rate')
|
||||
.eq('status', 'active')
|
||||
.gte('start_date', startOfMonth);
|
||||
|
||||
const totalMonthRevenue = monthRevenue?.reduce((sum, c) => sum + (c.agreed_rate || 0), 0) || 0;
|
||||
|
||||
return NextResponse.json({
|
||||
activeCampaigns: activeCampaigns?.length || 0,
|
||||
pendingApprovals: pendingApprovals?.length || 0,
|
||||
endingSoon: endingSoon?.length || 0,
|
||||
emailsSentThisMonth: emailCampaigns?.length || 0,
|
||||
revenueThisMonth: totalMonthRevenue,
|
||||
recentActivity: recentCampaigns || [],
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user