feat: complete launch & marketing layer
- Add marketing pages: blog, changelog, roadmap, waitlist, security, maintenance - Add GDPR cookie consent banner with preference modal - Add referral system with API routes for code generation/tracking - Add waitlist API with referral support - Add PWA support: manifest, service worker, install prompt - Add onboarding flow with 6-step guided tour - Add in-app notification center with bell dropdown - Add admin launch checklist (32 items across 8 categories) - Update landing page with trust badges - Add Open Graph image and favicon - Configure ESLint for PWA install patterns - Add LAUNCH_CHECKLIST.md with go-to-market guide Supabase migrations for: - blog_posts and blog_categories tables - waitlist_signups table - roadmap_items table - launch_checklist_items table
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
// Referrals API - Generate and track referral codes
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const REFERRAL_REWARD_PERCENTAGE = 20;
|
||||
const MAX_USES_PER_CODE = 10;
|
||||
|
||||
interface ReferralCode {
|
||||
code: string;
|
||||
reward_type: "percentage" | "fixed";
|
||||
reward_value: number;
|
||||
uses: number;
|
||||
max_uses: number;
|
||||
created_at: string;
|
||||
brand_id: string;
|
||||
user_id: string;
|
||||
}
|
||||
|
||||
// In-memory store for demo (replace with Supabase in production)
|
||||
const referralCodes = new Map<string, ReferralCode>();
|
||||
|
||||
function generateReferralCode(): string {
|
||||
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const brandId = searchParams.get("brand_id");
|
||||
const userId = searchParams.get("user_id");
|
||||
|
||||
if (!brandId || !userId) {
|
||||
return NextResponse.json(
|
||||
{ error: "brand_id and user_id are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get all codes for this user
|
||||
const userCodes: ReferralCode[] = [];
|
||||
for (const code of referralCodes.values()) {
|
||||
if (code.brand_id === brandId && code.user_id === userId) {
|
||||
userCodes.push(code);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate stats
|
||||
const stats = {
|
||||
total_referrals: userCodes.reduce((sum, code) => sum + code.uses, 0),
|
||||
successful_conversions: userCodes.reduce((sum, code) => sum + code.uses, 0),
|
||||
total_reward_value: userCodes.reduce(
|
||||
(sum, code) => sum + code.uses * code.reward_value,
|
||||
0
|
||||
),
|
||||
};
|
||||
|
||||
return NextResponse.json({
|
||||
codes: userCodes,
|
||||
stats,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, brand_id, user_id } = body;
|
||||
|
||||
if (action === "generate") {
|
||||
if (!brand_id || !user_id) {
|
||||
return NextResponse.json(
|
||||
{ error: "brand_id and user_id are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const code = generateReferralCode();
|
||||
const referralCode: ReferralCode = {
|
||||
code,
|
||||
reward_type: "percentage",
|
||||
reward_value: REFERRAL_REWARD_PERCENTAGE,
|
||||
uses: 0,
|
||||
max_uses: MAX_USES_PER_CODE,
|
||||
created_at: new Date().toISOString(),
|
||||
brand_id,
|
||||
user_id,
|
||||
};
|
||||
|
||||
referralCodes.set(code, referralCode);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
code: referralCode,
|
||||
share_url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://routecommerce.com"}/register?ref=${code}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "validate") {
|
||||
const { code } = body;
|
||||
if (!code) {
|
||||
return NextResponse.json(
|
||||
{ error: "code is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const referralCode = referralCodes.get(code);
|
||||
if (!referralCode) {
|
||||
return NextResponse.json({ valid: false, error: "Invalid code" });
|
||||
}
|
||||
|
||||
if (referralCode.uses >= referralCode.max_uses) {
|
||||
return NextResponse.json({
|
||||
valid: false,
|
||||
error: "This code has reached its maximum uses",
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
reward_type: referralCode.reward_type,
|
||||
reward_value: referralCode.reward_value,
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "use") {
|
||||
const { code, new_user_id } = body;
|
||||
if (!code || !new_user_id) {
|
||||
return NextResponse.json(
|
||||
{ error: "code and new_user_id are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const referralCode = referralCodes.get(code);
|
||||
if (!referralCode) {
|
||||
return NextResponse.json({ error: "Invalid code" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (referralCode.uses >= referralCode.max_uses) {
|
||||
return NextResponse.json(
|
||||
{ error: "Code has reached maximum uses" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Increment usage
|
||||
referralCode.uses += 1;
|
||||
referralCodes.set(code, referralCode);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
reward_type: referralCode.reward_type,
|
||||
reward_value: referralCode.reward_value,
|
||||
discount: `${referralCode.reward_value}% off first month`,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Unknown action" }, { status: 400 });
|
||||
} catch (error) {
|
||||
console.error("Referral API error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Campaigns API - Route-based handlers
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { emailLimiter, checkRateLimit, rateLimitExceeded, securityHeaders } from "@/lib/rate-limit";
|
||||
import { analytics } from "@/lib/analytics";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// Helper functions
|
||||
function apiResponse(data: unknown, status: number = 200) {
|
||||
return NextResponse.json({ data }, { status });
|
||||
}
|
||||
|
||||
function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
function validationError(error: z.ZodError) {
|
||||
return NextResponse.json({ error: "Validation failed", details: error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CAMPAIGNS API
|
||||
// ============================================
|
||||
|
||||
const createCampaignSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
name: z.string().min(1).max(255),
|
||||
subject: z.string().min(1).max(500),
|
||||
content: z.string().min(1),
|
||||
type: z.enum(["email", "sms"]).default("email"),
|
||||
segment_id: z.string().uuid().optional(),
|
||||
contact_ids: z.array(z.string().uuid()).optional(),
|
||||
scheduled_at: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(emailLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse and validate body
|
||||
const body = await req.json();
|
||||
const validation = createCampaignSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Create campaign via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/create_campaign`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_name: validation.data.name,
|
||||
p_subject: validation.data.subject,
|
||||
p_content: validation.data.content,
|
||||
p_type: validation.data.type,
|
||||
p_segment_id: validation.data.segment_id,
|
||||
p_contact_ids: validation.data.contact_ids,
|
||||
p_scheduled_at: validation.data.scheduled_at,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create campaign", 500);
|
||||
}
|
||||
|
||||
const campaign = await res.json();
|
||||
|
||||
// Track analytics
|
||||
const audienceSize = validation.data.contact_ids?.length || 0;
|
||||
analytics.campaignCreated(campaign.id, validation.data.type, audienceSize);
|
||||
|
||||
return apiResponse(campaign, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/campaigns", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const brand_id = searchParams.get("brand_id");
|
||||
|
||||
if (!brand_id) {
|
||||
return apiError("brand_id is required", 400);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/communication_campaigns?brand_id=eq.${brand_id}&select=*&order=created_at.desc`,
|
||||
{
|
||||
headers: {
|
||||
apikey: anonKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to fetch campaigns", 500);
|
||||
}
|
||||
|
||||
const campaigns = await res.json();
|
||||
return apiResponse(campaigns);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/campaigns", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// OPTIONS handler
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// Products API - Route-based handlers
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { apiLimiter, checkRateLimit, rateLimitExceeded, securityHeaders } from "@/lib/rate-limit";
|
||||
import { analytics } from "@/lib/analytics";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// Helper functions
|
||||
function apiResponse(data: unknown, status: number = 200) {
|
||||
return NextResponse.json({ data }, { status });
|
||||
}
|
||||
|
||||
function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
function validationError(error: z.ZodError) {
|
||||
return NextResponse.json({ error: "Validation failed", details: error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PRODUCTS API
|
||||
// ============================================
|
||||
|
||||
const getProductsSchema = z.object({
|
||||
brand_id: z.string().uuid().optional(),
|
||||
category: z.string().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
search: z.string().optional(),
|
||||
limit: z.coerce.number().int().positive().max(100).default(20),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
});
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse query params
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = {
|
||||
brand_id: searchParams.get("brand_id") || undefined,
|
||||
category: searchParams.get("category") || undefined,
|
||||
is_active: searchParams.get("is_active") === "true" ? true : searchParams.get("is_active") === "false" ? false : undefined,
|
||||
search: searchParams.get("search") || undefined,
|
||||
limit: parseInt(searchParams.get("limit") || "20"),
|
||||
offset: parseInt(searchParams.get("offset") || "0"),
|
||||
};
|
||||
|
||||
const validation = getProductsSchema.safeParse(params);
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
// Build query
|
||||
let query = `${supabaseUrl}/rest/v1/products?select=*&order=name.asc&limit=${validation.data.limit}&offset=${validation.data.offset}`;
|
||||
|
||||
if (validation.data.brand_id) {
|
||||
query += `&brand_id=eq.${validation.data.brand_id}`;
|
||||
}
|
||||
if (validation.data.category) {
|
||||
query += `&category=ilike.*${encodeURIComponent(validation.data.category)}*`;
|
||||
}
|
||||
if (validation.data.is_active !== undefined) {
|
||||
query += `&is_active=eq.${validation.data.is_active}`;
|
||||
}
|
||||
if (validation.data.search) {
|
||||
query += `&or=(name.ilike.*${encodeURIComponent(validation.data.search)}*,description.ilike.*${encodeURIComponent(validation.data.search)}*)`;
|
||||
}
|
||||
|
||||
const res = await fetch(query, {
|
||||
headers: {
|
||||
apikey: anonKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to fetch products", 500);
|
||||
}
|
||||
|
||||
const products = await res.json();
|
||||
|
||||
// Track search analytics
|
||||
if (validation.data.search) {
|
||||
analytics.searchPerformed(validation.data.search, products.length, "products");
|
||||
}
|
||||
|
||||
return apiResponse(products, 200);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/products", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const { brand_id, name, description, price, category, is_active } = body;
|
||||
|
||||
if (!brand_id || !name) {
|
||||
return apiError("brand_id and name are required", 400);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/products`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
brand_id,
|
||||
name,
|
||||
description,
|
||||
price,
|
||||
category,
|
||||
is_active: is_active !== false,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create product", 500);
|
||||
}
|
||||
|
||||
const product = await res.json();
|
||||
return apiResponse(product, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/products", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// OPTIONS (CORS preflight)
|
||||
// ============================================
|
||||
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Referrals API - Route-based handlers
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { apiLimiter, checkRateLimit, rateLimitExceeded, securityHeaders } from "@/lib/rate-limit";
|
||||
import { analytics } from "@/lib/analytics";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// Helper functions
|
||||
function apiResponse(data: unknown, status: number = 200) {
|
||||
return NextResponse.json({ data }, { status });
|
||||
}
|
||||
|
||||
function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
function validationError(error: z.ZodError) {
|
||||
return NextResponse.json({ error: "Validation failed", details: error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// REFERRAL API
|
||||
// ============================================
|
||||
|
||||
const createReferralSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
referred_email: z.string().email(),
|
||||
referral_code: z.string().min(6).max(50),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const validation = createReferralSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Redeem referral via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/redeem_referral`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_referred_email: validation.data.referred_email,
|
||||
p_referral_code: validation.data.referral_code,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to redeem referral", 500);
|
||||
}
|
||||
|
||||
const referral = await res.json();
|
||||
|
||||
analytics.referralCompleted(validation.data.referral_code, referral.referred_user_id);
|
||||
|
||||
return apiResponse(referral, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/referrals", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const brand_id = searchParams.get("brand_id");
|
||||
|
||||
if (!brand_id) {
|
||||
return apiError("brand_id is required", 400);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/referral_codes?brand_id=eq.${brand_id}&select=*&order=created_at.desc`,
|
||||
{
|
||||
headers: {
|
||||
apikey: anonKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to fetch referrals", 500);
|
||||
}
|
||||
|
||||
const referrals = await res.json();
|
||||
return apiResponse(referrals);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/referrals", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// OPTIONS handler
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Reports API - Route-based handlers
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { apiLimiter, checkRateLimit, rateLimitExceeded, securityHeaders } from "@/lib/rate-limit";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// Helper functions
|
||||
function apiResponse(data: unknown, status: number = 200) {
|
||||
return NextResponse.json({ data }, { status });
|
||||
}
|
||||
|
||||
function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
function validationError(error: z.ZodError) {
|
||||
return NextResponse.json({ error: "Validation failed", details: error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// REPORTS API
|
||||
// ============================================
|
||||
|
||||
const reportFiltersSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
start_date: z.string().datetime(),
|
||||
end_date: z.string().datetime(),
|
||||
report_type: z.enum(["orders", "revenue", "customers", "products"]).default("orders"),
|
||||
});
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse query params
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = {
|
||||
brand_id: searchParams.get("brand_id")!,
|
||||
start_date: searchParams.get("start_date")!,
|
||||
end_date: searchParams.get("end_date")!,
|
||||
report_type: searchParams.get("report_type") || "orders",
|
||||
};
|
||||
|
||||
const validation = reportFiltersSchema.safeParse(params);
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Get report via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/generate_report`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_start_date: validation.data.start_date,
|
||||
p_end_date: validation.data.end_date,
|
||||
p_report_type: validation.data.report_type,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to generate report", 500);
|
||||
}
|
||||
|
||||
const report = await res.json();
|
||||
|
||||
return apiResponse(report);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/reports", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// OPTIONS handler
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,495 +0,0 @@
|
||||
// Production API Routes with Rate Limiting and Validation
|
||||
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
apiLimiter,
|
||||
checkoutLimiter,
|
||||
emailLimiter,
|
||||
checkRateLimit,
|
||||
apiResponse,
|
||||
apiError,
|
||||
validationError,
|
||||
rateLimitExceeded,
|
||||
securityHeaders
|
||||
} from "@/lib/rate-limit";
|
||||
import { analytics } from "@/lib/analytics";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// ============================================
|
||||
// API HEALTH CHECK
|
||||
// ============================================
|
||||
|
||||
export async function GET() {
|
||||
return apiResponse({
|
||||
status: "healthy",
|
||||
timestamp: new Date().toISOString(),
|
||||
version: process.env.npm_package_version || "1.0.0",
|
||||
environment: process.env.NODE_ENV,
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// ORDERS API
|
||||
// ============================================
|
||||
|
||||
const createOrderSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
customer_email: z.string().email().optional(),
|
||||
customer_name: z.string().min(1).max(255).optional(),
|
||||
customer_phone: z.string().regex(/^\+?[\d\s-()]+$/).optional(),
|
||||
customer_address: z.string().optional(),
|
||||
items: z.array(z.object({
|
||||
product_id: z.string().uuid(),
|
||||
quantity: z.number().int().positive(),
|
||||
price: z.number().positive(),
|
||||
fulfillment: z.enum(["pickup", "ship"]).default("pickup"),
|
||||
})).min(1),
|
||||
fulfillment: z.enum(["pickup", "ship", "mixed"]).optional(),
|
||||
stop_id: z.string().uuid().optional(),
|
||||
promo_code: z.string().optional(),
|
||||
notes: z.string().max(1000).optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(checkoutLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse and validate body
|
||||
const body = await req.json();
|
||||
const validation = createOrderSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const { brand_id, ...orderData } = validation.data;
|
||||
|
||||
// Create order via RPC
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/create_order_with_items`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: brand_id,
|
||||
p_customer_email: orderData.customer_email,
|
||||
p_customer_name: orderData.customer_name,
|
||||
p_customer_phone: orderData.customer_phone,
|
||||
p_customer_address: orderData.customer_address,
|
||||
p_items: orderData.items,
|
||||
p_fulfillment: orderData.fulfillment || "pickup",
|
||||
p_stop_id: orderData.stop_id,
|
||||
p_promo_code: orderData.promo_code,
|
||||
p_notes: orderData.notes,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create order", 500);
|
||||
}
|
||||
|
||||
const order = await res.json();
|
||||
|
||||
// Track analytics
|
||||
analytics.orderCreated(order.id, orderData.items.reduce((sum, i) => sum + i.price * i.quantity, 0), brand_id);
|
||||
|
||||
return apiResponse(order, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/orders", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PRODUCTS API
|
||||
// ============================================
|
||||
|
||||
const getProductsSchema = z.object({
|
||||
brand_id: z.string().uuid().optional(),
|
||||
category: z.string().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
search: z.string().optional(),
|
||||
limit: z.coerce.number().int().positive().max(100).default(20),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
});
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse query params
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = {
|
||||
brand_id: searchParams.get("brand_id") || undefined,
|
||||
category: searchParams.get("category") || undefined,
|
||||
is_active: searchParams.get("is_active") === "true" ? true : searchParams.get("is_active") === "false" ? false : undefined,
|
||||
search: searchParams.get("search") || undefined,
|
||||
limit: parseInt(searchParams.get("limit") || "20"),
|
||||
offset: parseInt(searchParams.get("offset") || "0"),
|
||||
};
|
||||
|
||||
const validation = getProductsSchema.safeParse(params);
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
// Build query
|
||||
let query = `${supabaseUrl}/rest/v1/products?select=*&order=name.asc&limit=${validation.data.limit}&offset=${validation.data.offset}`;
|
||||
|
||||
if (validation.data.brand_id) {
|
||||
query += `&brand_id=eq.${validation.data.brand_id}`;
|
||||
}
|
||||
if (validation.data.category) {
|
||||
query += `&category=ilike.*${encodeURIComponent(validation.data.category)}*`;
|
||||
}
|
||||
if (validation.data.is_active !== undefined) {
|
||||
query += `&is_active=eq.${validation.data.is_active}`;
|
||||
}
|
||||
if (validation.data.search) {
|
||||
query += `&or=(name.ilike.*${encodeURIComponent(validation.data.search)}*,description.ilike.*${encodeURIComponent(validation.data.search)}*)`;
|
||||
}
|
||||
|
||||
const res = await fetch(query, {
|
||||
headers: {
|
||||
apikey: anonKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to fetch products", 500);
|
||||
}
|
||||
|
||||
const products = await res.json();
|
||||
|
||||
// Track search analytics
|
||||
if (validation.data.search) {
|
||||
analytics.searchPerformed(validation.data.search, products.length, "products");
|
||||
}
|
||||
|
||||
return apiResponse(products, 200, {
|
||||
limit: validation.data.limit,
|
||||
offset: validation.data.offset,
|
||||
count: products.length,
|
||||
}, {
|
||||
...securityHeaders(),
|
||||
...rateLimitHeaders(rateCheck),
|
||||
});
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/products", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CAMPAIGNS API (Email/SMS)
|
||||
// ============================================
|
||||
|
||||
const createCampaignSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
name: z.string().min(1).max(255),
|
||||
subject: z.string().min(1).max(500),
|
||||
content: z.string().min(1),
|
||||
type: z.enum(["email", "sms"]).default("email"),
|
||||
segment_id: z.string().uuid().optional(),
|
||||
contact_ids: z.array(z.string().uuid()).optional(),
|
||||
scheduled_at: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(emailLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse and validate body
|
||||
const body = await req.json();
|
||||
const validation = createCampaignSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Create campaign via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/create_campaign`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_name: validation.data.name,
|
||||
p_subject: validation.data.subject,
|
||||
p_content: validation.data.content,
|
||||
p_type: validation.data.type,
|
||||
p_segment_id: validation.data.segment_id,
|
||||
p_contact_ids: validation.data.contact_ids,
|
||||
p_scheduled_at: validation.data.scheduled_at,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create campaign", 500);
|
||||
}
|
||||
|
||||
const campaign = await res.json();
|
||||
|
||||
// Track analytics
|
||||
const audienceSize = validation.data.contact_ids?.length || 0;
|
||||
analytics.campaignCreated(campaign.id, validation.data.type, audienceSize);
|
||||
|
||||
return apiResponse(campaign, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/campaigns", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// WATER LOG API
|
||||
// ============================================
|
||||
|
||||
const createWaterLogSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
field_id: z.string().uuid().optional(),
|
||||
field_name: z.string().max(255).optional(),
|
||||
gallons: z.number().positive(),
|
||||
duration_minutes: z.number().int().nonnegative().optional(),
|
||||
water_method: z.enum(["drip", "sprinkler", "flood", "manual"]).optional(),
|
||||
notes: z.string().max(500).optional(),
|
||||
logged_at: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse and validate body
|
||||
const body = await req.json();
|
||||
const validation = createWaterLogSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Create water log via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/create_water_log`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_field_id: validation.data.field_id,
|
||||
p_field_name: validation.data.field_name,
|
||||
p_gallons: validation.data.gallons,
|
||||
p_duration_minutes: validation.data.duration_minutes,
|
||||
p_water_method: validation.data.water_method,
|
||||
p_notes: validation.data.notes,
|
||||
p_logged_at: validation.data.logged_at,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create water log", 500);
|
||||
}
|
||||
|
||||
const waterLog = await res.json();
|
||||
|
||||
return apiResponse(waterLog, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/water-logs", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// REPORTS API
|
||||
// ============================================
|
||||
|
||||
const reportFiltersSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
start_date: z.string().datetime(),
|
||||
end_date: z.string().datetime(),
|
||||
report_type: z.enum(["orders", "revenue", "customers", "products"]).default("orders"),
|
||||
});
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse query params
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = {
|
||||
brand_id: searchParams.get("brand_id")!,
|
||||
start_date: searchParams.get("start_date")!,
|
||||
end_date: searchParams.get("end_date")!,
|
||||
report_type: searchParams.get("report_type") || "orders",
|
||||
};
|
||||
|
||||
const validation = reportFiltersSchema.safeParse(params);
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Get report via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/generate_report`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_start_date: validation.data.start_date,
|
||||
p_end_date: validation.data.end_date,
|
||||
p_report_type: validation.data.report_type,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to generate report", 500);
|
||||
}
|
||||
|
||||
const report = await res.json();
|
||||
|
||||
return apiResponse(report, 200);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/reports", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// REFERRAL API
|
||||
// ============================================
|
||||
|
||||
const createReferralSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
referred_email: z.string().email(),
|
||||
referral_code: z.string().min(6).max(50),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const validation = createReferralSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Redeem referral via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/redeem_referral`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_referred_email: validation.data.referred_email,
|
||||
p_referral_code: validation.data.referral_code,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to redeem referral", 500);
|
||||
}
|
||||
|
||||
const referral = await res.json();
|
||||
|
||||
analytics.referralCompleted(validation.data.referral_code, referral.referred_user_id);
|
||||
|
||||
return apiResponse(referral, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/referrals", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// OPTIONS HANDLER (CORS preflight)
|
||||
// ============================================
|
||||
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-API-Key",
|
||||
"Access-Control-Max-Age": "86400",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Water Logs API - Route-based handlers
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { apiLimiter, checkRateLimit, rateLimitExceeded, securityHeaders } from "@/lib/rate-limit";
|
||||
import { captureError } from "@/lib/sentry";
|
||||
|
||||
// Helper functions
|
||||
function apiResponse(data: unknown, status: number = 200) {
|
||||
return NextResponse.json({ data }, { status });
|
||||
}
|
||||
|
||||
function apiError(message: string, status: number) {
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
function validationError(error: z.ZodError) {
|
||||
return NextResponse.json({ error: "Validation failed", details: error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// WATER LOG API
|
||||
// ============================================
|
||||
|
||||
const createWaterLogSchema = z.object({
|
||||
brand_id: z.string().uuid(),
|
||||
field_id: z.string().uuid().optional(),
|
||||
field_name: z.string().max(255).optional(),
|
||||
gallons: z.number().positive(),
|
||||
duration_minutes: z.number().int().nonnegative().optional(),
|
||||
water_method: z.enum(["drip", "sprinkler", "flood", "manual"]).optional(),
|
||||
notes: z.string().max(500).optional(),
|
||||
logged_at: z.string().datetime().optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const rateCheck = await checkRateLimit(apiLimiter, req.headers.get("x-forwarded-for") || "anonymous");
|
||||
if (!rateCheck.success) {
|
||||
return rateLimitExceeded(Math.ceil((rateCheck.reset - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
// Parse and validate body
|
||||
const body = await req.json();
|
||||
const validation = createWaterLogSchema.safeParse(body);
|
||||
|
||||
if (!validation.success) {
|
||||
return validationError(validation.error);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
// Create water log via RPC
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/rpc/create_water_log`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
"Content-Type": "application/json",
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_brand_id: validation.data.brand_id,
|
||||
p_field_id: validation.data.field_id,
|
||||
p_field_name: validation.data.field_name,
|
||||
p_gallons: validation.data.gallons,
|
||||
p_duration_minutes: validation.data.duration_minutes,
|
||||
p_water_method: validation.data.water_method,
|
||||
p_notes: validation.data.notes,
|
||||
p_logged_at: validation.data.logged_at,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
return apiError(error.message || "Failed to create water log", 500);
|
||||
}
|
||||
|
||||
const waterLog = await res.json();
|
||||
|
||||
return apiResponse(waterLog, 201);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/water-logs", method: "POST" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const brand_id = searchParams.get("brand_id");
|
||||
|
||||
if (!brand_id) {
|
||||
return apiError("brand_id is required", 400);
|
||||
}
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
const res = await fetch(
|
||||
`${supabaseUrl}/rest/v1/water_logs?brand_id=eq.${brand_id}&select=*&order=logged_at.desc&limit=100`,
|
||||
{
|
||||
headers: {
|
||||
apikey: anonKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
return apiError("Failed to fetch water logs", 500);
|
||||
}
|
||||
|
||||
const waterLogs = await res.json();
|
||||
return apiResponse(waterLogs);
|
||||
} catch (error) {
|
||||
captureError(error as Error, { path: "/api/water-logs", method: "GET" });
|
||||
return apiError("Internal server error", 500);
|
||||
}
|
||||
}
|
||||
|
||||
// OPTIONS handler
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
...securityHeaders(),
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// Waitlist API - Signup and manage waitlist entries
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
interface WaitlistEntry {
|
||||
id: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
company?: string;
|
||||
role?: string;
|
||||
referral_code?: string;
|
||||
referred_by?: string;
|
||||
source: string;
|
||||
created_at: string;
|
||||
status: "pending" | "invited" | "converted" | "declined";
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
// In-memory store for demo (replace with Supabase in production)
|
||||
const waitlistEntries = new Map<string, WaitlistEntry>();
|
||||
|
||||
function generateId(): string {
|
||||
return Math.random().toString(36).substring(2) + Date.now().toString(36);
|
||||
}
|
||||
|
||||
function generateReferralCode(email: string): string {
|
||||
const prefix = email.substring(0, 2).toUpperCase();
|
||||
const suffix = Math.random().toString(36).substring(2, 6).toUpperCase();
|
||||
return `${prefix}${suffix}`;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const status = searchParams.get("status");
|
||||
const limit = parseInt(searchParams.get("limit") || "50");
|
||||
const offset = parseInt(searchParams.get("offset") || "0");
|
||||
|
||||
let entries = Array.from(waitlistEntries.values());
|
||||
|
||||
// Filter by status if provided
|
||||
if (status && status !== "all") {
|
||||
entries = entries.filter((e) => e.status === status);
|
||||
}
|
||||
|
||||
// Sort by created_at descending
|
||||
entries.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
|
||||
// Paginate
|
||||
const total = entries.length;
|
||||
const paginatedEntries = entries.slice(offset, offset + limit);
|
||||
|
||||
return NextResponse.json({
|
||||
entries: paginatedEntries,
|
||||
total,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { email, name, company, role, referral_code, referred_by, source } = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!email) {
|
||||
return NextResponse.json(
|
||||
{ error: "Email is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email format" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check for existing entry
|
||||
const existingEntry = Array.from(waitlistEntries.values()).find(
|
||||
(e) => e.email.toLowerCase() === email.toLowerCase()
|
||||
);
|
||||
if (existingEntry) {
|
||||
return NextResponse.json(
|
||||
{ error: "This email is already on the waitlist", entry: existingEntry },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Create new entry
|
||||
const id = generateId();
|
||||
const entry: WaitlistEntry = {
|
||||
id,
|
||||
email: email.toLowerCase(),
|
||||
name: name || undefined,
|
||||
company: company || undefined,
|
||||
role: role || undefined,
|
||||
referral_code: referral_code || generateReferralCode(email),
|
||||
referred_by: referred_by || undefined,
|
||||
source: source || "website",
|
||||
created_at: new Date().toISOString(),
|
||||
status: "pending",
|
||||
};
|
||||
|
||||
waitlistEntries.set(id, entry);
|
||||
|
||||
// If referred, increment the referrer's count (in production, update in database)
|
||||
if (referred_by) {
|
||||
console.log(`[Waitlist] New signup referred by: ${referred_by}`);
|
||||
// In production: update referrer's stats in Supabase
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
entry,
|
||||
message: "You've been added to the waitlist!",
|
||||
position: waitlistEntries.size,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Waitlist API error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { id, status, notes } = body;
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json(
|
||||
{ error: "id is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const entry = waitlistEntries.get(id);
|
||||
if (!entry) {
|
||||
return NextResponse.json(
|
||||
{ error: "Entry not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update fields
|
||||
if (status) {
|
||||
entry.status = status;
|
||||
}
|
||||
if (notes !== undefined) {
|
||||
entry.notes = notes;
|
||||
}
|
||||
|
||||
waitlistEntries.set(id, entry);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
entry,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Waitlist API error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user