Spaces:
Build error
Build error
File size: 9,297 Bytes
333c51a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import ZAI from "z-ai-web-dev-sdk";
// GET - Listar publicaciones
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const status = searchParams.get("status");
const platform = searchParams.get("platform");
const type = searchParams.get("type");
const limit = parseInt(searchParams.get("limit") || "50");
const where: Record<string, unknown> = {};
if (status) where.status = status;
if (type) where.type = type;
if (platform) where.platformId = platform;
const posts = await db.post.findMany({
where,
include: {
content: true,
platform: true,
story: true,
},
orderBy: { scheduledAt: "asc" },
take: limit,
});
// Estad铆sticas
const stats = {
total: await db.post.count(),
draft: await db.post.count({ where: { status: "draft" } }),
scheduled: await db.post.count({ where: { status: "scheduled" } }),
published: await db.post.count({ where: { status: "published" } }),
failed: await db.post.count({ where: { status: "failed" } }),
};
// Pr贸ximas publicaciones
const upcoming = await db.post.findMany({
where: {
status: "scheduled",
scheduledAt: { gte: new Date() }
},
orderBy: { scheduledAt: "asc" },
take: 5,
});
return NextResponse.json({
success: true,
posts,
stats,
upcoming
});
} catch (error) {
console.error("Error fetching posts:", error);
return NextResponse.json(
{ success: false, error: "Error al obtener publicaciones" },
{ status: 500 }
);
}
}
// POST - Crear nueva publicaci贸n
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const {
title,
caption,
type, // reel, photo, carousel, story, post
contentId,
platformId,
scheduledAt,
hashtags,
storyId,
autoGenerateCaption,
optimizeForPlatform,
} = body;
if (!type) {
return NextResponse.json(
{ success: false, error: "El tipo de publicaci贸n es requerido" },
{ status: 400 }
);
}
let finalCaption = caption;
let finalHashtags = hashtags;
// Generar caption con IA si se solicita
if (autoGenerateCaption && contentId) {
const content = await db.content.findUnique({
where: { id: contentId }
});
if (content) {
const zai = await ZAI.create();
const platform = await db.monetizationPlatform.findUnique({
where: { id: platformId }
});
const platformName = platform?.name || "general";
const platformRules = PLATFORM_RULES[platformName.toLowerCase()] || {};
const completion = await zai.chat.completions.create({
messages: [
{
role: "system",
content: `Eres un experto en marketing de contenidos para ${platformName}.
Genera captions atractivos que:
${platformRules.maxCaptionLength ? `- No excedan ${platformRules.maxCaptionLength} caracteres` : ''}
- Incluyan emojis relevantes
- Tengan un CTA (call to action) efectivo
- Sean ${platformRules.tone || 'profesionales pero cercanos'}
- Maximizen el engagement
${platformRules.hashtagLimit ? `- Incluyan m谩ximo ${platformRules.hashtagLimit} hashtags relevantes` : ''}`
},
{
role: "user",
content: `Genera un caption para este contenido:
Tipo: ${type}
T铆tulo: ${title || content.title}
Descripci贸n: ${content.description || content.prompt}
Plataforma: ${platformName}`
}
],
temperature: 0.8,
});
finalCaption = completion.choices[0]?.message?.content || caption;
}
}
// Optimizar hashtags si se solicita
if (optimizeForPlatform && !hashtags) {
const zai = await ZAI.create();
const platform = await db.monetizationPlatform.findUnique({
where: { id: platformId }
});
const completion = await zai.chat.completions.create({
messages: [
{
role: "system",
content: `Eres un experto en SEO de redes sociales. Genera hashtags optimizados.
Responde SOLO con un JSON array de hashtags sin el s铆mbolo #.
Ejemplo: ["tendencias", "viral", "lifestyle"]`
},
{
role: "user",
content: `Genera hashtags para un ${type} en ${platform?.name || "redes sociales"}.
Tema: ${title || "contenido general"}
M谩ximo 10 hashtags.`
}
],
temperature: 0.7,
});
try {
const response = completion.choices[0]?.message?.content || "[]";
const match = response.match(/\[[\s\S]*\]/);
if (match) {
finalHashtags = match[0];
}
} catch {
finalHashtags = "[]";
}
}
// Crear publicaci贸n
const post = await db.post.create({
data: {
title: title || null,
caption: finalCaption,
hashtags: finalHashtags,
type,
status: scheduledAt ? "scheduled" : "draft",
contentId: contentId || null,
platformId: platformId || null,
scheduledAt: scheduledAt ? new Date(scheduledAt) : null,
storyId: storyId || null,
},
include: {
content: true,
platform: true,
}
});
// Crear tarea de agente
await db.agentTask.create({
data: {
type: "create_post",
status: "completed",
input: `Crear ${type}: ${title || "sin t铆tulo"}`,
output: `Post creado con ID: ${post.id}`,
completedAt: new Date(),
}
});
return NextResponse.json({
success: true,
post,
message: scheduledAt
? `Publicaci贸n programada para ${new Date(scheduledAt).toLocaleString()}`
: "Publicaci贸n creada como borrador"
});
} catch (error) {
console.error("Error creating post:", error);
return NextResponse.json(
{ success: false, error: "Error al crear publicaci贸n" },
{ status: 500 }
);
}
}
// PUT - Actualizar publicaci贸n
export async function PUT(request: NextRequest) {
try {
const body = await request.json();
const { id, status, scheduledAt, caption, hashtags, publishedAt, engagementStats } = body;
if (!id) {
return NextResponse.json(
{ success: false, error: "ID requerido" },
{ status: 400 }
);
}
const updateData: Record<string, unknown> = {};
if (status) updateData.status = status;
if (scheduledAt) updateData.scheduledAt = new Date(scheduledAt);
if (caption) updateData.caption = caption;
if (hashtags) updateData.hashtags = hashtags;
if (publishedAt) updateData.publishedAt = new Date(publishedAt);
if (engagementStats) updateData.engagementStats = engagementStats;
const post = await db.post.update({
where: { id },
data: updateData,
});
return NextResponse.json({
success: true,
post
});
} catch (error) {
console.error("Error updating post:", error);
return NextResponse.json(
{ success: false, error: "Error al actualizar publicaci贸n" },
{ status: 500 }
);
}
}
// DELETE - Eliminar publicaci贸n
export async function DELETE(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (!id) {
return NextResponse.json(
{ success: false, error: "ID requerido" },
{ status: 400 }
);
}
await db.post.delete({
where: { id }
});
return NextResponse.json({
success: true,
message: "Publicaci贸n eliminada"
});
} catch (error) {
console.error("Error deleting post:", error);
return NextResponse.json(
{ success: false, error: "Error al eliminar publicaci贸n" },
{ status: 500 }
);
}
}
// Reglas espec铆ficas por plataforma
const PLATFORM_RULES: Record<string, {
maxCaptionLength?: number;
hashtagLimit?: number;
tone?: string;
bestPostingTimes?: string[];
}> = {
instagram: {
maxCaptionLength: 2200,
hashtagLimit: 30,
tone: "inspirador y visual",
bestPostingTimes: ["11:00", "14:00", "19:00", "21:00"]
},
tiktok: {
maxCaptionLength: 300,
hashtagLimit: 5,
tone: "casual y divertido",
bestPostingTimes: ["09:00", "12:00", "19:00"]
},
youtube: {
maxCaptionLength: 5000,
tone: "profesional e informativo",
bestPostingTimes: ["15:00", "16:00", "17:00"]
},
onlyfans: {
maxCaptionLength: 1000,
tone: "personal y exclusivo",
bestPostingTimes: ["10:00", "18:00", "22:00"]
},
patreon: {
maxCaptionLength: 5000,
tone: "profesional y cercano",
bestPostingTimes: ["10:00", "14:00", "18:00"]
},
twitter: {
maxCaptionLength: 280,
hashtagLimit: 3,
tone: "conciso y directo",
bestPostingTimes: ["09:00", "12:00", "17:00", "20:00"]
}
};
|