feat: dual agency/client approval on calendar and assets
Private RRSS calendar with unified + per-network tabs, comments, and double-check OK. Assets get review drawer with preview/comments. KPIs gain date presets, North Star strip, channel matrix and per-channel dash. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
135
src/app/api/assets/collab/route.ts
Normal file
135
src/app/api/assets/collab/route.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import {
|
||||
dualStatus,
|
||||
insertComment,
|
||||
listApprovals,
|
||||
listComments,
|
||||
partyFromUser,
|
||||
upsertApproval,
|
||||
} from '@/lib/content-collab';
|
||||
import { serviceHeaders, supabaseUrl } from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function gate() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
||||
}
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
if (!ctx.tenantId || ctx.portfolioWide) {
|
||||
return {
|
||||
error: NextResponse.json({ error: 'Selecciona un cliente' }, { status: 400 }),
|
||||
};
|
||||
}
|
||||
return { user, ctx, party: partyFromUser(user) };
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { ctx, party } = g as {
|
||||
ctx: { tenantId: string };
|
||||
party: 'agency' | 'client';
|
||||
};
|
||||
const ids = (req.nextUrl.searchParams.get('ids') || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const resourceId = req.nextUrl.searchParams.get('resourceId');
|
||||
const approvals = await listApprovals(ctx.tenantId, 'asset', ids);
|
||||
const dual: Record<string, ReturnType<typeof dualStatus>> = {};
|
||||
for (const id of ids) dual[id] = dualStatus(approvals[id] || []);
|
||||
let comments = null;
|
||||
if (resourceId) {
|
||||
comments = await listComments(ctx.tenantId, 'asset', resourceId);
|
||||
}
|
||||
return NextResponse.json({ dual, comments, party });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { user, ctx, party } = g as {
|
||||
user: { id: string; email?: string };
|
||||
ctx: { tenantId: string };
|
||||
party: 'agency' | 'client';
|
||||
};
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const assetId = String(body.assetId || '');
|
||||
if (!assetId) {
|
||||
return NextResponse.json({ error: 'assetId requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (body.action === 'approve' || body.action === 'revoke') {
|
||||
await upsertApproval({
|
||||
tenantId: ctx.tenantId,
|
||||
resourceType: 'asset',
|
||||
resourceId: assetId,
|
||||
party,
|
||||
approved: body.action === 'approve',
|
||||
actorId: user.id,
|
||||
actorEmail: user.email || null,
|
||||
});
|
||||
const approvals = await listApprovals(ctx.tenantId, 'asset', [assetId]);
|
||||
const dual = dualStatus(approvals[assetId] || []);
|
||||
|
||||
// Mirror to asset_files columns when both OK
|
||||
const headers = serviceHeaders();
|
||||
if (headers) {
|
||||
const patch: Record<string, unknown> = {
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
if (party === 'agency') {
|
||||
patch.agency_approved_at =
|
||||
body.action === 'approve' ? new Date().toISOString() : null;
|
||||
patch.agency_approved_by = body.action === 'approve' ? user.id : null;
|
||||
} else {
|
||||
patch.client_approved_at =
|
||||
body.action === 'approve' ? new Date().toISOString() : null;
|
||||
patch.client_approved_by = body.action === 'approve' ? user.id : null;
|
||||
}
|
||||
if (dual.both) patch.review_status = 'validated';
|
||||
else patch.review_status = 'in_review';
|
||||
|
||||
await fetch(
|
||||
`${supabaseUrl()}/rest/v1/asset_files?id=eq.${encodeURIComponent(assetId)}&tenant_id=eq.${encodeURIComponent(ctx.tenantId)}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=minimal',
|
||||
},
|
||||
body: JSON.stringify(patch),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, dual, party });
|
||||
}
|
||||
|
||||
if (body.action === 'comment') {
|
||||
const text = String(body.body || '').trim();
|
||||
if (!text) {
|
||||
return NextResponse.json({ error: 'Comentario vacío' }, { status: 400 });
|
||||
}
|
||||
const row = await insertComment({
|
||||
tenantId: ctx.tenantId,
|
||||
resourceType: 'asset',
|
||||
resourceId: assetId,
|
||||
body: text.slice(0, 4000),
|
||||
authorId: user.id,
|
||||
authorEmail: user.email || null,
|
||||
authorParty: party,
|
||||
});
|
||||
return NextResponse.json({ ok: true, comment: row });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: 'action inválida' }, { status: 400 });
|
||||
}
|
||||
127
src/app/api/calendar/collab/route.ts
Normal file
127
src/app/api/calendar/collab/route.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import {
|
||||
dualStatus,
|
||||
insertComment,
|
||||
listApprovals,
|
||||
listComments,
|
||||
partyFromUser,
|
||||
upsertApproval,
|
||||
} from '@/lib/content-collab';
|
||||
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function gate() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
||||
}
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
if (!ctx.tenantId || ctx.portfolioWide) {
|
||||
return {
|
||||
error: NextResponse.json(
|
||||
{ error: 'Selecciona un cliente para colaborar en el calendario.' },
|
||||
{ status: 400 }
|
||||
),
|
||||
};
|
||||
}
|
||||
return { user, ctx, party: partyFromUser(user) };
|
||||
}
|
||||
|
||||
/** GET ?ids=a,b,c — approvals map; &resourceId=x — also comments */
|
||||
export async function GET(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { ctx } = g as Awaited<ReturnType<typeof gate>> & {
|
||||
ctx: { tenantId: string };
|
||||
};
|
||||
|
||||
const ids = (req.nextUrl.searchParams.get('ids') || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const resourceId = req.nextUrl.searchParams.get('resourceId');
|
||||
|
||||
const approvals = await listApprovals(ctx.tenantId!, 'calendar_post', ids);
|
||||
const dual: Record<string, ReturnType<typeof dualStatus>> = {};
|
||||
for (const id of ids) {
|
||||
dual[id] = dualStatus(approvals[id] || []);
|
||||
}
|
||||
|
||||
let comments = null;
|
||||
if (resourceId) {
|
||||
comments = await listComments(ctx.tenantId!, 'calendar_post', resourceId);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
approvals,
|
||||
dual,
|
||||
comments,
|
||||
party: (g as { party: string }).party,
|
||||
isAgency: isAgencyRole(userRole((g as { user: unknown }).user as never)),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* POST actions:
|
||||
* { action: 'approve' | 'revoke', postId, note? }
|
||||
* { action: 'comment', postId, body }
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { user, ctx, party } = g as {
|
||||
user: { id: string; email?: string };
|
||||
ctx: { tenantId: string };
|
||||
party: 'agency' | 'client';
|
||||
};
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const postId = String(body.postId || '');
|
||||
if (!postId) {
|
||||
return NextResponse.json({ error: 'postId requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (body.action === 'approve' || body.action === 'revoke') {
|
||||
await upsertApproval({
|
||||
tenantId: ctx.tenantId,
|
||||
resourceType: 'calendar_post',
|
||||
resourceId: postId,
|
||||
party,
|
||||
approved: body.action === 'approve',
|
||||
actorId: user.id,
|
||||
actorEmail: user.email || null,
|
||||
note: body.note ? String(body.note) : null,
|
||||
});
|
||||
const approvals = await listApprovals(ctx.tenantId, 'calendar_post', [postId]);
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
dual: dualStatus(approvals[postId] || []),
|
||||
party,
|
||||
});
|
||||
}
|
||||
|
||||
if (body.action === 'comment') {
|
||||
const text = String(body.body || '').trim();
|
||||
if (!text) {
|
||||
return NextResponse.json({ error: 'Comentario vacío' }, { status: 400 });
|
||||
}
|
||||
const row = await insertComment({
|
||||
tenantId: ctx.tenantId,
|
||||
resourceType: 'calendar_post',
|
||||
resourceId: postId,
|
||||
body: text.slice(0, 4000),
|
||||
authorId: user.id,
|
||||
authorEmail: user.email || null,
|
||||
authorParty: party,
|
||||
});
|
||||
return NextResponse.json({ ok: true, comment: row });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: 'action inválida' }, { status: 400 });
|
||||
}
|
||||
@@ -1,29 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
CalendarDays,
|
||||
Instagram,
|
||||
Linkedin,
|
||||
Facebook,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
FileText,
|
||||
Layers,
|
||||
Tag,
|
||||
ExternalLink,
|
||||
X,
|
||||
Copy,
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
CalendarDays,
|
||||
Instagram,
|
||||
Linkedin,
|
||||
Facebook,
|
||||
CheckCircle2,
|
||||
Copy,
|
||||
Check,
|
||||
Eye,
|
||||
Sparkles
|
||||
X,
|
||||
MessageSquare,
|
||||
ShieldCheck,
|
||||
Music2,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface Post {
|
||||
export type CalendarPost = {
|
||||
id: string;
|
||||
date: string;
|
||||
time: string;
|
||||
platform: 'instagram' | 'linkedin' | 'facebook';
|
||||
platform: string;
|
||||
format: string;
|
||||
pillar: string;
|
||||
title: string;
|
||||
@@ -31,378 +28,494 @@ interface Post {
|
||||
body: string;
|
||||
cta: string;
|
||||
hashtags: string;
|
||||
status: 'approved' | 'scheduled' | 'draft';
|
||||
status: 'approved' | 'scheduled' | 'draft' | string;
|
||||
objective_metric?: string;
|
||||
};
|
||||
|
||||
type Dual = {
|
||||
agency: boolean;
|
||||
client: boolean;
|
||||
both: boolean;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type Comment = {
|
||||
id: string;
|
||||
body: string;
|
||||
author_email?: string | null;
|
||||
author_party: 'agency' | 'client';
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
const PLATFORM_META: Record<
|
||||
string,
|
||||
{ label: string; color: string; Icon: React.ComponentType<{ className?: string }> }
|
||||
> = {
|
||||
instagram: {
|
||||
label: 'Instagram',
|
||||
color: 'from-pink-500 to-purple-600',
|
||||
Icon: Instagram,
|
||||
},
|
||||
linkedin: { label: 'LinkedIn', color: 'bg-[#0A66C2]', Icon: Linkedin },
|
||||
facebook: { label: 'Facebook', color: 'bg-[#1877F2]', Icon: Facebook },
|
||||
tiktok: { label: 'TikTok', color: 'bg-gray-100 text-black', Icon: Music2 },
|
||||
};
|
||||
|
||||
function platformMeta(p: string) {
|
||||
return (
|
||||
PLATFORM_META[p] || {
|
||||
label: p.charAt(0).toUpperCase() + p.slice(1),
|
||||
color: 'bg-gray-700',
|
||||
Icon: CalendarDays,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
interface CalendarClientProps {
|
||||
initialPosts: Post[];
|
||||
function DualBadge({ dual }: { dual?: Dual }) {
|
||||
if (!dual) {
|
||||
return (
|
||||
<span className="text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full border border-gray-700 text-gray-500">
|
||||
Sin checks
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (dual.both) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 text-emerald-300">
|
||||
<ShieldCheck className="w-3 h-3" /> Doble OK
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full border border-amber-500/30 bg-amber-500/10 text-amber-300">
|
||||
{dual.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function CalendarClient({
|
||||
initialPosts,
|
||||
calendarTitle,
|
||||
canCollaborate = true,
|
||||
}: {
|
||||
initialPosts: CalendarPost[];
|
||||
calendarTitle: string;
|
||||
}
|
||||
canCollaborate?: boolean;
|
||||
}) {
|
||||
const platforms = useMemo(() => {
|
||||
const set = new Set(initialPosts.map((p) => p.platform).filter(Boolean));
|
||||
return ['all', ...[...set].sort()];
|
||||
}, [initialPosts]);
|
||||
|
||||
export default function CalendarClient({ initialPosts, calendarTitle }: CalendarClientProps) {
|
||||
const [platformFilter, setPlatformFilter] = useState<'all' | 'instagram' | 'linkedin' | 'facebook'>('all');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'scheduled' | 'draft'>('all');
|
||||
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
||||
const [platformFilter, setPlatformFilter] = useState('all');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'scheduled' | 'draft'>(
|
||||
'all'
|
||||
);
|
||||
const [view, setView] = useState<'month' | 'list'>('month');
|
||||
const [selectedPost, setSelectedPost] = useState<CalendarPost | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [dualMap, setDualMap] = useState<Record<string, Dual>>({});
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [commentText, setCommentText] = useState('');
|
||||
const [party, setParty] = useState<'agency' | 'client'>('client');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [collabErr, setCollabErr] = useState<string | null>(null);
|
||||
|
||||
const ids = useMemo(() => initialPosts.map((p) => p.id).filter(Boolean), [initialPosts]);
|
||||
|
||||
const refreshDual = useCallback(async () => {
|
||||
if (!canCollaborate || !ids.length) return;
|
||||
const r = await fetch(`/api/calendar/collab?ids=${ids.map(encodeURIComponent).join(',')}`);
|
||||
const j = await r.json();
|
||||
if (r.ok) {
|
||||
setDualMap(j.dual || {});
|
||||
if (j.party) setParty(j.party);
|
||||
}
|
||||
}, [canCollaborate, ids]);
|
||||
|
||||
useEffect(() => {
|
||||
refreshDual();
|
||||
}, [refreshDual]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedPost || !canCollaborate) {
|
||||
setComments([]);
|
||||
return;
|
||||
}
|
||||
(async () => {
|
||||
const r = await fetch(
|
||||
`/api/calendar/collab?ids=${encodeURIComponent(selectedPost.id)}&resourceId=${encodeURIComponent(selectedPost.id)}`
|
||||
);
|
||||
const j = await r.json();
|
||||
if (r.ok) {
|
||||
setComments(j.comments || []);
|
||||
if (j.dual?.[selectedPost.id]) {
|
||||
setDualMap((prev) => ({ ...prev, [selectedPost.id]: j.dual[selectedPost.id] }));
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [selectedPost, canCollaborate]);
|
||||
|
||||
// Filter posts
|
||||
const filteredPosts = initialPosts.filter((p) => {
|
||||
const matchPlatform = platformFilter === 'all' || p.platform === platformFilter;
|
||||
const matchStatus = statusFilter === 'all' || p.status === statusFilter;
|
||||
return matchPlatform && matchStatus;
|
||||
});
|
||||
|
||||
// KPI counters
|
||||
const totalPosts = initialPosts.length;
|
||||
const instagramCount = initialPosts.filter((p) => p.platform === 'instagram').length;
|
||||
const linkedinCount = initialPosts.filter((p) => p.platform === 'linkedin').length;
|
||||
const facebookCount = initialPosts.filter((p) => p.platform === 'facebook').length;
|
||||
const approvedCount = initialPosts.filter((p) => p.status === 'approved').length;
|
||||
const approvedCount = initialPosts.filter(
|
||||
(p) => dualMap[p.id]?.both || p.status === 'approved'
|
||||
).length;
|
||||
|
||||
const copyFullCopy = (post: Post) => {
|
||||
const byDay = useMemo(() => {
|
||||
const map = new Map<string, CalendarPost[]>();
|
||||
for (const p of filteredPosts) {
|
||||
const key = (p.date || '').slice(0, 10);
|
||||
if (!key) continue;
|
||||
const list = map.get(key) || [];
|
||||
list.push(p);
|
||||
map.set(key, list);
|
||||
}
|
||||
return [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
||||
}, [filteredPosts]);
|
||||
|
||||
const copyFullCopy = (post: CalendarPost) => {
|
||||
const text = `${post.hook}\n\n${post.body}\n\n${post.cta}\n\n${post.hashtags}`;
|
||||
navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const getPlatformBadge = (platform: string) => {
|
||||
switch (platform) {
|
||||
case 'instagram':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-bold text-white bg-gradient-to-r from-pink-500 via-purple-500 to-amber-500 shadow-sm shadow-pink-500/20">
|
||||
<Instagram className="w-3.5 h-3.5" /> Instagram
|
||||
</span>
|
||||
);
|
||||
case 'linkedin':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-bold text-white bg-[#0A66C2] shadow-sm shadow-blue-500/20">
|
||||
<Linkedin className="w-3.5 h-3.5" /> LinkedIn
|
||||
</span>
|
||||
);
|
||||
case 'facebook':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-bold text-white bg-[#1877F2] shadow-sm shadow-blue-600/20">
|
||||
<Facebook className="w-3.5 h-3.5" /> Facebook
|
||||
</span>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
async function approve(action: 'approve' | 'revoke') {
|
||||
if (!selectedPost) return;
|
||||
setBusy(true);
|
||||
setCollabErr(null);
|
||||
try {
|
||||
const r = await fetch('/api/calendar/collab', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action, postId: selectedPost.id }),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (!r.ok) throw new Error(j.error || 'Error');
|
||||
setDualMap((prev) => ({ ...prev, [selectedPost.id]: j.dual }));
|
||||
} catch (e) {
|
||||
setCollabErr(e instanceof Error ? e.message : 'Error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">
|
||||
<CheckCircle2 className="w-3 h-3" /> Aprobado
|
||||
</span>
|
||||
);
|
||||
case 'scheduled':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-blue-500/10 text-blue-400 border border-blue-500/30">
|
||||
<Clock className="w-3 h-3" /> Programado
|
||||
</span>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-amber-500/10 text-amber-400 border border-amber-500/30">
|
||||
<Sparkles className="w-3 h-3" /> En Revisión
|
||||
</span>
|
||||
);
|
||||
async function sendComment() {
|
||||
if (!selectedPost || !commentText.trim()) return;
|
||||
setBusy(true);
|
||||
setCollabErr(null);
|
||||
try {
|
||||
const r = await fetch('/api/calendar/collab', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'comment',
|
||||
postId: selectedPost.id,
|
||||
body: commentText.trim(),
|
||||
}),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (!r.ok) throw new Error(j.error || 'Error');
|
||||
setComments((prev) => [...prev, j.comment]);
|
||||
setCommentText('');
|
||||
} catch (e) {
|
||||
setCollabErr(e instanceof Error ? e.message : 'Error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const myApproved =
|
||||
selectedPost && dualMap[selectedPost.id]
|
||||
? party === 'agency'
|
||||
? dualMap[selectedPost.id].agency
|
||||
: dualMap[selectedPost.id].client
|
||||
: false;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* KPI Top Cards */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3.5">
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Total Posts</span>
|
||||
<CalendarDays className="w-4 h-4 text-brand-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{totalPosts}</p>
|
||||
<p className="text-[10px] text-gray-500 mt-0.5">Plan del mes</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Instagram</span>
|
||||
<Instagram className="w-4 h-4 text-pink-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{instagramCount}</p>
|
||||
<p className="text-[10px] text-pink-400/80 mt-0.5">Carruseles & Reels</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>LinkedIn</span>
|
||||
<Linkedin className="w-4 h-4 text-blue-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{linkedinCount}</p>
|
||||
<p className="text-[10px] text-blue-400/80 mt-0.5">Artículos & Casos B2B</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Facebook</span>
|
||||
<Facebook className="w-4 h-4 text-blue-500" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{facebookCount}</p>
|
||||
<p className="text-[10px] text-blue-500/80 mt-0.5">Comunidad & Ads</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4 col-span-2 sm:col-span-1">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Listos / Aprobados</span>
|
||||
<CheckCircle2 className="w-4 h-4 text-emerald-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-emerald-400">{approvedCount}</p>
|
||||
<p className="text-[10px] text-emerald-400/80 mt-0.5">{totalPosts > 0 ? Math.round((approvedCount / totalPosts) * 100) : 0}% validado</p>
|
||||
<div className="flex flex-col sm:flex-row sm:items-end justify-between gap-3">
|
||||
<p className="text-xs text-gray-500">
|
||||
{calendarTitle} · privado (sin publicación pública) · doble check
|
||||
agencia/cliente
|
||||
</p>
|
||||
<div className="flex gap-1 rounded-lg border border-gray-800 p-0.5 bg-black/20">
|
||||
{(
|
||||
[
|
||||
['month', 'Mes'],
|
||||
['list', 'Lista'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => setView(k)}
|
||||
className={`px-2.5 py-1 text-xs rounded-md ${
|
||||
view === k ? 'bg-brand-500/20 text-brand-300' : 'text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
{/* Platform Tabs */}
|
||||
<div className="flex items-center gap-1.5 overflow-x-auto pb-1 md:pb-0">
|
||||
<button
|
||||
onClick={() => setPlatformFilter('all')}
|
||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all cursor-pointer ${
|
||||
platformFilter === 'all'
|
||||
? 'bg-brand-500 text-white shadow-md shadow-brand-500/20'
|
||||
: 'bg-gray-800/60 text-gray-300 hover:text-white hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
Todos ({totalPosts})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPlatformFilter('instagram')}
|
||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all cursor-pointer ${
|
||||
platformFilter === 'instagram'
|
||||
? 'bg-gradient-to-r from-pink-500 to-purple-600 text-white shadow-md shadow-pink-500/20'
|
||||
: 'bg-gray-800/60 text-gray-300 hover:text-white hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
<Instagram className="w-3.5 h-3.5" /> Instagram ({instagramCount})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPlatformFilter('linkedin')}
|
||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all cursor-pointer ${
|
||||
platformFilter === 'linkedin'
|
||||
? 'bg-[#0A66C2] text-white shadow-md shadow-blue-500/20'
|
||||
: 'bg-gray-800/60 text-gray-300 hover:text-white hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
<Linkedin className="w-3.5 h-3.5" /> LinkedIn ({linkedinCount})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPlatformFilter('facebook')}
|
||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all cursor-pointer ${
|
||||
platformFilter === 'facebook'
|
||||
? 'bg-[#1877F2] text-white shadow-md shadow-blue-600/20'
|
||||
: 'bg-gray-800/60 text-gray-300 hover:text-white hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
<Facebook className="w-3.5 h-3.5" /> Facebook ({facebookCount})
|
||||
</button>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5">
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Total piezas</span>
|
||||
<CalendarDays className="w-4 h-4 text-brand-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{totalPosts}</p>
|
||||
</div>
|
||||
{platforms
|
||||
.filter((p) => p !== 'all')
|
||||
.slice(0, 2)
|
||||
.map((p) => {
|
||||
const meta = platformMeta(p);
|
||||
const n = initialPosts.filter((x) => x.platform === p).length;
|
||||
return (
|
||||
<div key={p} className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>{meta.label}</span>
|
||||
<meta.Icon className="w-4 h-4" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-white">{n}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||
<span>Doble OK</span>
|
||||
<CheckCircle2 className="w-4 h-4 text-emerald-400" />
|
||||
</div>
|
||||
<p className="text-2xl font-extrabold text-emerald-400">{approvedCount}</p>
|
||||
<p className="text-[10px] text-emerald-400/80 mt-0.5">
|
||||
{totalPosts > 0 ? Math.round((approvedCount / totalPosts) * 100) : 0}%
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Dropdown Filter */}
|
||||
{/* Unified + per-network tabs */}
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-1.5 overflow-x-auto pb-1 md:pb-0">
|
||||
{platforms.map((p) => {
|
||||
const count =
|
||||
p === 'all'
|
||||
? totalPosts
|
||||
: initialPosts.filter((x) => x.platform === p).length;
|
||||
const meta = p === 'all' ? null : platformMeta(p);
|
||||
const active = platformFilter === p;
|
||||
return (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
onClick={() => setPlatformFilter(p)}
|
||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all whitespace-nowrap ${
|
||||
active
|
||||
? p === 'all'
|
||||
? 'bg-brand-500 text-white'
|
||||
: p === 'instagram'
|
||||
? 'bg-gradient-to-r from-pink-500 to-purple-600 text-white'
|
||||
: `${meta?.color || 'bg-gray-700'} text-white`
|
||||
: 'bg-gray-800/60 text-gray-300 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{meta && <meta.Icon className="w-3.5 h-3.5" />}
|
||||
{p === 'all' ? 'Unificado' : meta?.label} ({count})
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-400">Estado:</span>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e: any) => setStatusFilter(e.target.value)}
|
||||
onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
|
||||
className="bg-gray-900 border border-gray-700 text-xs text-white rounded-lg px-2.5 py-1.5 focus:outline-none focus:border-brand-500"
|
||||
>
|
||||
<option value="all">Todos los estados</option>
|
||||
<option value="all">Todos</option>
|
||||
<option value="approved">Aprobados</option>
|
||||
<option value="scheduled">Programados</option>
|
||||
<option value="draft">Borradores en revisión</option>
|
||||
<option value="draft">En revisión</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Posts Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{filteredPosts.length === 0 ? (
|
||||
<div className="col-span-full bg-[#111827] border border-gray-800 rounded-xl p-12 text-center text-gray-400">
|
||||
<CalendarDays className="w-10 h-10 text-gray-600 mx-auto mb-3" />
|
||||
<p className="text-base font-semibold text-white">No hay publicaciones con este filtro.</p>
|
||||
<p className="text-xs text-gray-400 mt-1">Prueba a seleccionar «Todos los canales» o «Todos los estados».</p>
|
||||
</div>
|
||||
) : (
|
||||
filteredPosts.map((post) => (
|
||||
<div
|
||||
key={post.id}
|
||||
className="bg-[#111827] border border-gray-800 hover:border-gray-700 rounded-xl p-5 flex flex-col justify-between transition-all group hover:shadow-xl hover:shadow-black/40"
|
||||
>
|
||||
<div>
|
||||
{/* Header: Platform & Status */}
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
{getPlatformBadge(post.platform)}
|
||||
{getStatusBadge(post.status)}
|
||||
</div>
|
||||
|
||||
{/* Date & Time */}
|
||||
<div className="flex items-center gap-2 text-xs text-brand-400 font-mono mb-2">
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
<span>{new Date(post.date).toLocaleDateString('es-ES', { weekday: 'short', day: 'numeric', month: 'short' })} · {post.time}h</span>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<h4 className="font-bold text-white text-base mb-1.5 group-hover:text-brand-400 transition-colors">
|
||||
{post.title}
|
||||
</h4>
|
||||
|
||||
{/* Pillars & Format Badges */}
|
||||
<div className="flex flex-wrap gap-1.5 mb-3">
|
||||
<span className="text-[10px] px-2 py-0.5 rounded bg-gray-800 text-gray-300 border border-gray-700/50">
|
||||
{post.format}
|
||||
</span>
|
||||
<span className="text-[10px] px-2 py-0.5 rounded bg-brand-950/60 text-brand-400 border border-brand-800/40">
|
||||
{post.pillar}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Hook preview */}
|
||||
<div className="p-2.5 rounded-lg bg-gray-900/80 border border-gray-800/80 mb-3 text-xs text-gray-300 italic">
|
||||
«{post.hook}»
|
||||
</div>
|
||||
|
||||
{/* Truncated Body */}
|
||||
<p className="text-xs text-gray-400 line-clamp-3 whitespace-pre-wrap">
|
||||
{post.body}
|
||||
{view === 'month' ? (
|
||||
<div className="space-y-3">
|
||||
{byDay.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
byDay.map(([day, posts]) => (
|
||||
<div
|
||||
key={day}
|
||||
className="rounded-xl border border-gray-800 bg-[#111827] p-4"
|
||||
>
|
||||
<p className="text-xs font-semibold text-brand-400 font-mono mb-3">
|
||||
{new Date(day).toLocaleDateString('es-ES', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
})}
|
||||
</p>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{posts.map((post) => (
|
||||
<PostCard
|
||||
key={post.id}
|
||||
post={post}
|
||||
dual={dualMap[post.id]}
|
||||
onOpen={() => setSelectedPost(post)}
|
||||
onCopy={() => copyFullCopy(post)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{filteredPosts.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
filteredPosts.map((post) => (
|
||||
<PostCard
|
||||
key={post.id}
|
||||
post={post}
|
||||
dual={dualMap[post.id]}
|
||||
onOpen={() => setSelectedPost(post)}
|
||||
onCopy={() => copyFullCopy(post)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions Footer */}
|
||||
<div className="pt-4 border-t border-gray-800/80 mt-4 flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedPost(post)}
|
||||
className="text-xs text-brand-400 hover:text-brand-300 font-semibold flex items-center gap-1.5 transition-colors cursor-pointer"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" /> Ver Post Completo
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyFullCopy(post)}
|
||||
className="p-1.5 rounded-md hover:bg-gray-800 text-gray-400 hover:text-gray-200 transition-colors cursor-pointer"
|
||||
title="Copiar copy completo"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Detail Modal */}
|
||||
{selectedPost && (
|
||||
<div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex items-center justify-center p-4">
|
||||
<div className="bg-[#0D121F] border border-gray-800 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col animate-in fade-in zoom-in duration-200">
|
||||
{/* Modal Header */}
|
||||
<div className="bg-[#0D121F] border border-gray-800 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col">
|
||||
<div className="p-5 border-b border-gray-800 flex items-center justify-between bg-[#111827]">
|
||||
<div className="flex items-center gap-3">
|
||||
{getPlatformBadge(selectedPost.platform)}
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-white">{selectedPost.title}</h3>
|
||||
<p className="text-xs text-gray-400 font-mono">
|
||||
Programado para: {new Date(selectedPost.date).toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' })} a las {selectedPost.time}h
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-white">{selectedPost.title}</h3>
|
||||
<p className="text-xs text-gray-400 font-mono mt-0.5">
|
||||
{selectedPost.platform} · {selectedPost.date} · {selectedPost.time}h
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedPost(null)}
|
||||
className="text-gray-400 hover:text-white p-1 rounded-lg hover:bg-gray-800 transition-colors"
|
||||
className="text-gray-400 hover:text-white p-1 rounded-lg hover:bg-gray-800"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Modal Body */}
|
||||
<div className="p-6 overflow-y-auto space-y-4 text-sm text-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-400 font-medium">Pilar:</span>
|
||||
<span className="text-xs font-semibold text-brand-400 bg-brand-950/60 px-2 py-0.5 rounded border border-brand-800/40">
|
||||
{selectedPost.pillar}
|
||||
</span>
|
||||
<span className="text-xs text-gray-400 font-medium ml-2">Formato:</span>
|
||||
<span className="text-xs font-semibold text-gray-300 bg-gray-800 px-2 py-0.5 rounded border border-gray-700/50">
|
||||
{selectedPost.format}
|
||||
</span>
|
||||
</div>
|
||||
{getStatusBadge(selectedPost.status)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<DualBadge dual={dualMap[selectedPost.id]} />
|
||||
<span className="text-[10px] text-gray-500">
|
||||
Tú: {party === 'agency' ? 'Agencia' : 'Cliente'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Hook */}
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
||||
Gancho / Hook de Apertura
|
||||
</label>
|
||||
<div className="p-3.5 rounded-xl bg-gray-900 border border-gray-800 font-medium text-amber-300 text-sm">
|
||||
{selectedPost.hook}
|
||||
</div>
|
||||
</div>
|
||||
<Block label="Hook" className="text-amber-300">
|
||||
{selectedPost.hook}
|
||||
</Block>
|
||||
<Block label="Copy">{selectedPost.body}</Block>
|
||||
<Block label="CTA" className="text-brand-300">
|
||||
{selectedPost.cta}
|
||||
</Block>
|
||||
<Block label="Hashtags" className="text-blue-400 font-mono text-xs">
|
||||
{selectedPost.hashtags}
|
||||
</Block>
|
||||
|
||||
{/* Body */}
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
||||
Cuerpo Persuasivo
|
||||
</label>
|
||||
<div className="p-4 rounded-xl bg-gray-900/80 border border-gray-800 whitespace-pre-wrap leading-relaxed text-gray-200 font-sans text-sm">
|
||||
{selectedPost.body}
|
||||
{canCollaborate && (
|
||||
<div className="rounded-xl border border-gray-800 bg-black/20 p-4 space-y-3">
|
||||
<div className="flex items-center gap-2 text-xs font-semibold text-white">
|
||||
<MessageSquare className="w-3.5 h-3.5 text-sky-400" />
|
||||
Comentarios
|
||||
</div>
|
||||
<ul className="space-y-2 max-h-40 overflow-y-auto">
|
||||
{comments.length === 0 && (
|
||||
<li className="text-xs text-gray-500">Sin comentarios aún.</li>
|
||||
)}
|
||||
{comments.map((c) => (
|
||||
<li
|
||||
key={c.id}
|
||||
className="text-xs border border-gray-800 rounded-lg px-2.5 py-2"
|
||||
>
|
||||
<div className="flex justify-between gap-2 text-[10px] text-gray-500 mb-1">
|
||||
<span>
|
||||
{c.author_party === 'agency' ? 'Agencia' : 'Cliente'}
|
||||
{c.author_email ? ` · ${c.author_email}` : ''}
|
||||
</span>
|
||||
<span>
|
||||
{new Date(c.created_at).toLocaleString('es-ES', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-200 whitespace-pre-wrap">{c.body}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={commentText}
|
||||
onChange={(e) => setCommentText(e.target.value)}
|
||||
placeholder="Escribe un comentario…"
|
||||
className="flex-1 rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-xs text-white placeholder:text-gray-600 focus:outline-none focus:border-brand-500/50"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !commentText.trim()}
|
||||
onClick={sendComment}
|
||||
className="px-3 py-2 rounded-lg bg-sky-500/20 text-sky-300 border border-sky-500/30 text-xs font-semibold disabled:opacity-40"
|
||||
>
|
||||
Enviar
|
||||
</button>
|
||||
</div>
|
||||
{collabErr && (
|
||||
<p className="text-[11px] text-red-400">{collabErr}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CTA */}
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
||||
Llamada a la Acción (CTA)
|
||||
</label>
|
||||
<div className="p-3 rounded-xl bg-brand-500/10 border border-brand-500/30 text-brand-300 text-xs font-semibold">
|
||||
👉 {selectedPost.cta}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hashtags */}
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
||||
Hashtags Recomendados
|
||||
</label>
|
||||
<div className="p-2.5 rounded-xl bg-gray-900 border border-gray-800 text-xs text-blue-400 font-mono">
|
||||
{selectedPost.hashtags}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal Footer */}
|
||||
<div className="p-4 border-t border-gray-800 bg-[#111827] flex items-center justify-between">
|
||||
<span className="text-xs text-gray-400">Generado por Agente #07 Contenido</span>
|
||||
<div className="flex gap-2">
|
||||
<div className="p-4 border-t border-gray-800 bg-[#111827] flex flex-wrap items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyFullCopy(selectedPost)}
|
||||
className="px-3 py-2 rounded-xl bg-gray-800 hover:bg-gray-700 text-gray-200 text-xs font-semibold inline-flex items-center gap-1.5"
|
||||
>
|
||||
{copied ? <Check className="w-3.5 h-3.5 text-emerald-300" /> : <Copy className="w-3.5 h-3.5" />}
|
||||
Copiar copy
|
||||
</button>
|
||||
{canCollaborate && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyFullCopy(selectedPost)}
|
||||
className="px-4 py-2 rounded-xl bg-brand-500 hover:bg-brand-600 text-white text-xs font-semibold flex items-center gap-2 transition-all cursor-pointer shadow-lg shadow-brand-500/20"
|
||||
disabled={busy}
|
||||
onClick={() => approve(myApproved ? 'revoke' : 'approve')}
|
||||
className={`px-4 py-2 rounded-xl text-xs font-semibold inline-flex items-center gap-1.5 ${
|
||||
myApproved
|
||||
? 'bg-gray-800 text-gray-300 border border-gray-700'
|
||||
: 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40'
|
||||
}`}
|
||||
>
|
||||
{copied ? <Check className="w-4 h-4 text-emerald-300" /> : <Copy className="w-4 h-4" />}
|
||||
<span>{copied ? '¡Copy Copiado!' : 'Copiar Texto para Publicar'}</span>
|
||||
<ShieldCheck className="w-3.5 h-3.5" />
|
||||
{myApproved ? 'Quitar mi OK' : `Aprobar (${party === 'agency' ? 'agencia' : 'cliente'})`}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedPost(null)}
|
||||
className="px-4 py-2 rounded-xl bg-gray-800 hover:bg-gray-700 text-gray-200 text-xs font-semibold transition-all cursor-pointer"
|
||||
>
|
||||
Cerrar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -410,3 +523,89 @@ export default function CalendarClient({ initialPosts, calendarTitle }: Calendar
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState() {
|
||||
return (
|
||||
<div className="col-span-full bg-[#111827] border border-gray-800 rounded-xl p-12 text-center text-gray-400">
|
||||
<CalendarDays className="w-10 h-10 text-gray-600 mx-auto mb-3" />
|
||||
<p className="text-base font-semibold text-white">Sin piezas con este filtro.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Block({
|
||||
label,
|
||||
children,
|
||||
className = '',
|
||||
}: {
|
||||
label: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
||||
{label}
|
||||
</label>
|
||||
<div
|
||||
className={`p-3.5 rounded-xl bg-gray-900 border border-gray-800 whitespace-pre-wrap ${className}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PostCard({
|
||||
post,
|
||||
dual,
|
||||
onOpen,
|
||||
onCopy,
|
||||
}: {
|
||||
post: CalendarPost;
|
||||
dual?: Dual;
|
||||
onOpen: () => void;
|
||||
onCopy: () => void;
|
||||
}) {
|
||||
const meta = platformMeta(post.platform);
|
||||
return (
|
||||
<div className="bg-[#0D121F] border border-gray-800 hover:border-gray-700 rounded-xl p-4 flex flex-col justify-between">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2 gap-2">
|
||||
<span
|
||||
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[10px] font-bold text-white ${
|
||||
post.platform === 'instagram'
|
||||
? 'bg-gradient-to-r from-pink-500 to-purple-600'
|
||||
: meta.color
|
||||
}`}
|
||||
>
|
||||
<meta.Icon className="w-3 h-3" /> {meta.label}
|
||||
</span>
|
||||
<DualBadge dual={dual} />
|
||||
</div>
|
||||
<p className="text-[11px] text-brand-400 font-mono mb-1">
|
||||
{post.time ? `${post.time}h` : '—'} · {post.format}
|
||||
</p>
|
||||
<h4 className="font-bold text-white text-sm mb-1.5 line-clamp-2">{post.title}</h4>
|
||||
<p className="text-xs text-gray-400 line-clamp-2 italic">«{post.hook}»</p>
|
||||
</div>
|
||||
<div className="pt-3 mt-3 border-t border-gray-800/80 flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="text-xs text-brand-400 hover:text-brand-300 font-semibold inline-flex items-center gap-1"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" /> Ver / comentar
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCopy}
|
||||
className="p-1.5 rounded-md hover:bg-gray-800 text-gray-400"
|
||||
title="Copiar"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,9 +59,9 @@ export default async function CalendarioPage() {
|
||||
Calendario editorial — {ctx.label}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-1 max-w-2xl">
|
||||
Plan de publicaciones (IG / FB / LinkedIn) guardado en{' '}
|
||||
<code>documents</code> con <code>type=calendar</code>, generado por
|
||||
agentes / ops y ligado al tenant. No es el calendario de Google Ads.
|
||||
Plan RRSS privado por cliente: vista unificada + pestaña por red.
|
||||
Cliente y agencia pueden leer, comentar y dar OK (doble check). Sin
|
||||
publicación pública.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
126
src/app/dashboard/kpis/canal/[channel]/page.tsx
Normal file
126
src/app/dashboard/kpis/canal/[channel]/page.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { resolveActiveTenant, restGet } from '@/lib/tenant-context';
|
||||
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||
import {
|
||||
KpiWeeklyRow,
|
||||
buildChannelSeries,
|
||||
formatEur,
|
||||
formatNum,
|
||||
} from '@/lib/metrics';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function CanalDashPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ channel: string }>;
|
||||
}) {
|
||||
const { channel: raw } = await params;
|
||||
const channel = decodeURIComponent(raw).toLowerCase();
|
||||
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) redirect('/login');
|
||||
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
const agency = isAgencyRole(userRole(user));
|
||||
|
||||
if (ctx.portfolioWide) {
|
||||
return (
|
||||
<p className="text-sm text-gray-400">
|
||||
Selecciona un cliente para ver el dash de canal.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
let weekly: KpiWeeklyRow[] = [];
|
||||
if (agency && ctx.viaView && ctx.tenantId) {
|
||||
const tid = encodeURIComponent(ctx.tenantId);
|
||||
const w = await restGet<KpiWeeklyRow[]>(
|
||||
`/rest/v1/kpi_weekly?tenant_id=eq.${tid}&select=*&order=week.asc`
|
||||
);
|
||||
weekly = w.data || [];
|
||||
} else {
|
||||
const { data } = await supabase
|
||||
.from('kpi_weekly')
|
||||
.select('*')
|
||||
.order('week', { ascending: true });
|
||||
weekly = (data as KpiWeeklyRow[]) || [];
|
||||
}
|
||||
|
||||
const series = buildChannelSeries(weekly);
|
||||
const points = series.points.filter((p) => p.channel === channel);
|
||||
const spend = points.reduce((a, p) => a + p.spend, 0);
|
||||
const leads = points.reduce((a, p) => a + p.leads, 0);
|
||||
const revenue = points.reduce((a, p) => a + p.revenue, 0);
|
||||
const cpl = leads > 0 ? spend / leads : 0;
|
||||
const roas = spend > 0 ? revenue / spend : 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Link
|
||||
href="/dashboard/kpis"
|
||||
className="inline-flex items-center gap-1.5 text-xs text-gray-400 hover:text-white mb-3"
|
||||
>
|
||||
<ArrowLeft className="w-3.5 h-3.5" /> Volver a métricas
|
||||
</Link>
|
||||
<h2 className="text-2xl font-bold text-white capitalize">
|
||||
Canal · {channel}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
{ctx.label} · dash secundario (paid). CRM/GEO se añadirán aquí en v2.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
{[
|
||||
{ label: 'Inversión', value: formatEur(spend) },
|
||||
{ label: 'Leads', value: formatNum(leads) },
|
||||
{ label: 'CPL', value: cpl ? `${formatNum(cpl)} €` : '—' },
|
||||
{ label: 'ROAS', value: roas ? `${formatNum(roas)}x` : '—' },
|
||||
].map((s) => (
|
||||
<div
|
||||
key={s.label}
|
||||
className="rounded-xl border border-gray-800 bg-[#111827] px-4 py-3"
|
||||
>
|
||||
<p className="text-[10px] uppercase tracking-wider text-gray-500">
|
||||
{s.label}
|
||||
</p>
|
||||
<p className="text-xl font-bold text-white mt-1">{s.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-gray-800 bg-[#111827] p-5">
|
||||
<h3 className="text-sm font-semibold text-white mb-3">
|
||||
Semanas ({points.length})
|
||||
</h3>
|
||||
{points.length === 0 ? (
|
||||
<p className="text-xs text-gray-500">Sin datos para este canal.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{points.map((p) => (
|
||||
<li
|
||||
key={p.week}
|
||||
className="flex flex-wrap items-center justify-between gap-2 text-xs border border-gray-800 rounded-lg px-3 py-2"
|
||||
>
|
||||
<span className="font-mono text-brand-400">{p.week}</span>
|
||||
<span className="text-gray-300">
|
||||
{formatEur(p.spend)} · {formatNum(p.leads)} leads · CPL{' '}
|
||||
{p.cpl ? `${formatNum(p.cpl)} €` : '—'}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { resolveActiveTenant, restGet } from '@/lib/tenant-context';
|
||||
import {
|
||||
AdDailyRow,
|
||||
KpiWeeklyRow,
|
||||
buildChannelSeries,
|
||||
buildComparisons,
|
||||
sumDaily,
|
||||
sumWeekly,
|
||||
@@ -70,6 +71,7 @@ export default async function KpisPage() {
|
||||
: sumWeekly(weekly); // fallback: all available weeks if current month empty
|
||||
const dailyTotals = sumDaily(daily);
|
||||
const sparse = weekly.length < 4;
|
||||
const channelSeries = buildChannelSeries(weekly);
|
||||
|
||||
return (
|
||||
<MetricsDashboard
|
||||
@@ -80,6 +82,8 @@ export default async function KpisPage() {
|
||||
deltas={comparisons.deltas}
|
||||
daily={dailyTotals}
|
||||
sparse={sparse}
|
||||
weeklyRows={weekly}
|
||||
channelPoints={channelSeries.points}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,13 @@ type Asset = {
|
||||
created_at?: string;
|
||||
};
|
||||
|
||||
type Dual = {
|
||||
agency: boolean;
|
||||
client: boolean;
|
||||
both: boolean;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type DriveFile = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -39,6 +46,32 @@ function formatBytes(n?: number | null) {
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function AssetImagePreview({ assetId, alt }: { assetId: string; alt: string }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch(`/api/assets/download?id=${encodeURIComponent(assetId)}`);
|
||||
const j = await r.json();
|
||||
if (!cancelled && r.ok && j.url) setUrl(j.url);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [assetId]);
|
||||
if (!url) {
|
||||
return <p className="text-xs text-gray-500">Cargando preview…</p>;
|
||||
}
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={url}
|
||||
alt={alt}
|
||||
className="w-full max-h-48 object-contain rounded-lg border border-gray-800 bg-black/40"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function iconHint(mime?: string | null) {
|
||||
if (!mime) return 'FILE';
|
||||
if (mime.startsWith('image/')) return 'IMG';
|
||||
@@ -61,12 +94,30 @@ export default function AssetsLibrary({ tenantLabel }: { tenantLabel: string })
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [drag, setDrag] = useState(false);
|
||||
const [dualMap, setDualMap] = useState<Record<string, Dual>>({});
|
||||
const [detailId, setDetailId] = useState<string | null>(null);
|
||||
const [comments, setComments] = useState<
|
||||
{ id: string; body: string; author_party: string; author_email?: string; created_at: string }[]
|
||||
>([]);
|
||||
const [commentText, setCommentText] = useState('');
|
||||
const [party, setParty] = useState<'agency' | 'client'>('client');
|
||||
const [collabBusy, setCollabBusy] = useState(false);
|
||||
|
||||
const loadPortal = useCallback(async () => {
|
||||
const res = await fetch('/api/assets');
|
||||
const data = await res.json();
|
||||
setAssets(data.assets || []);
|
||||
const list: Asset[] = data.assets || [];
|
||||
setAssets(list);
|
||||
if (data.warning) setWarning(data.warning);
|
||||
if (list.length) {
|
||||
const ids = list.map((a) => a.id).join(',');
|
||||
const c = await fetch(`/api/assets/collab?ids=${ids}`);
|
||||
const cj = await c.json();
|
||||
if (c.ok) {
|
||||
setDualMap(cj.dual || {});
|
||||
if (cj.party) setParty(cj.party);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadDrive = useCallback(async () => {
|
||||
@@ -362,9 +413,34 @@ export default function AssetsLibrary({ tenantLabel }: { tenantLabel: string })
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
<span className="hidden sm:inline-flex items-center gap-1 text-[10px] text-emerald-400">
|
||||
<CheckCircle2 className="w-3 h-3" /> Validado
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
setDetailId(a.id);
|
||||
const r = await fetch(
|
||||
`/api/assets/collab?ids=${a.id}&resourceId=${a.id}`
|
||||
);
|
||||
const j = await r.json();
|
||||
if (r.ok) {
|
||||
setComments(j.comments || []);
|
||||
if (j.dual?.[a.id]) {
|
||||
setDualMap((prev) => ({ ...prev, [a.id]: j.dual[a.id] }));
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="hidden sm:inline-flex items-center gap-1 text-[10px] px-2 py-1 rounded border border-gray-700 text-gray-300 hover:text-white"
|
||||
title="Comentar / validar"
|
||||
>
|
||||
{dualMap[a.id]?.both ? (
|
||||
<span className="text-emerald-400 inline-flex items-center gap-1">
|
||||
<CheckCircle2 className="w-3 h-3" /> Doble OK
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-amber-300">
|
||||
{dualMap[a.id]?.label || 'En revisión'}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => download(a.id)}
|
||||
@@ -437,6 +513,135 @@ export default function AssetsLibrary({ tenantLabel }: { tenantLabel: string })
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{detailId && (
|
||||
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-lg rounded-2xl border border-gray-800 bg-[#0D121F] overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-gray-800 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-white">
|
||||
{assets.find((a) => a.id === detailId)?.file_name || 'Archivo'}
|
||||
</p>
|
||||
<p className="text-[11px] text-gray-500">
|
||||
Doble check · {dualMap[detailId]?.label || 'En revisión'} · tú:{' '}
|
||||
{party === 'agency' ? 'agencia' : 'cliente'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDetailId(null)}
|
||||
className="text-xs text-gray-400 hover:text-white"
|
||||
>
|
||||
Cerrar
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-4 space-y-3 max-h-[60vh] overflow-y-auto">
|
||||
{(() => {
|
||||
const a = assets.find((x) => x.id === detailId);
|
||||
const isImg = a?.mime_type?.startsWith('image/');
|
||||
return isImg ? (
|
||||
<AssetImagePreview assetId={detailId} alt={a?.file_name || ''} />
|
||||
) : (
|
||||
<p className="text-xs text-gray-500">
|
||||
Preview disponible para imágenes. Usa descargar para el resto.
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
<ul className="space-y-2">
|
||||
{comments.length === 0 && (
|
||||
<li className="text-xs text-gray-500">Sin comentarios.</li>
|
||||
)}
|
||||
{comments.map((c) => (
|
||||
<li
|
||||
key={c.id}
|
||||
className="text-xs border border-gray-800 rounded-lg px-2.5 py-2"
|
||||
>
|
||||
<p className="text-[10px] text-gray-500 mb-1">
|
||||
{c.author_party === 'agency' ? 'Agencia' : 'Cliente'}
|
||||
{c.author_email ? ` · ${c.author_email}` : ''}
|
||||
</p>
|
||||
<p className="text-gray-200 whitespace-pre-wrap">{c.body}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={commentText}
|
||||
onChange={(e) => setCommentText(e.target.value)}
|
||||
placeholder="Comentario…"
|
||||
className="flex-1 rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-xs text-white"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={collabBusy || !commentText.trim()}
|
||||
onClick={async () => {
|
||||
setCollabBusy(true);
|
||||
try {
|
||||
const r = await fetch('/api/assets/collab', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'comment',
|
||||
assetId: detailId,
|
||||
body: commentText.trim(),
|
||||
}),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (r.ok) {
|
||||
setComments((prev) => [...prev, j.comment]);
|
||||
setCommentText('');
|
||||
}
|
||||
} finally {
|
||||
setCollabBusy(false);
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 rounded-lg bg-sky-500/20 text-sky-300 border border-sky-500/30 text-xs"
|
||||
>
|
||||
Enviar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-4 py-3 border-t border-gray-800 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={collabBusy}
|
||||
onClick={async () => {
|
||||
const mine =
|
||||
party === 'agency'
|
||||
? dualMap[detailId]?.agency
|
||||
: dualMap[detailId]?.client;
|
||||
setCollabBusy(true);
|
||||
try {
|
||||
const r = await fetch('/api/assets/collab', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: mine ? 'revoke' : 'approve',
|
||||
assetId: detailId,
|
||||
}),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (r.ok) {
|
||||
setDualMap((prev) => ({ ...prev, [detailId]: j.dual }));
|
||||
}
|
||||
} finally {
|
||||
setCollabBusy(false);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 rounded-xl text-xs font-semibold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40"
|
||||
>
|
||||
{party === 'agency'
|
||||
? dualMap[detailId]?.agency
|
||||
? 'Quitar OK agencia'
|
||||
: 'Aprobar (agencia)'
|
||||
: dualMap[detailId]?.client
|
||||
? 'Quitar OK cliente'
|
||||
: 'Aprobar (cliente)'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import React from 'react';
|
||||
'use client';
|
||||
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
ArrowDownRight,
|
||||
ArrowUpRight,
|
||||
@@ -9,13 +12,17 @@ import {
|
||||
Users,
|
||||
MousePointerClick,
|
||||
Eye,
|
||||
CalendarRange,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
ChannelWeekPoint,
|
||||
Delta,
|
||||
MetricTotals,
|
||||
formatEur,
|
||||
formatNum,
|
||||
formatPct,
|
||||
sumWeekly,
|
||||
KpiWeeklyRow,
|
||||
} from '@/lib/metrics';
|
||||
|
||||
type Card = {
|
||||
@@ -24,16 +31,12 @@ type Card = {
|
||||
hint: string;
|
||||
format: (v: number) => string;
|
||||
icon: React.ReactNode;
|
||||
invert?: boolean; // lower is better
|
||||
invert?: boolean;
|
||||
};
|
||||
|
||||
function DeltaTriple({
|
||||
delta,
|
||||
invert,
|
||||
}: {
|
||||
delta: Delta;
|
||||
invert?: boolean;
|
||||
}) {
|
||||
type RangeKey = '7d' | '30d' | 'month' | 'all';
|
||||
|
||||
function DeltaTriple({ delta, invert }: { delta: Delta; invert?: boolean }) {
|
||||
const cells: { label: string; v: number | null }[] = [
|
||||
{ label: 'WoW', v: delta.wow },
|
||||
{ label: 'MoM', v: delta.mom },
|
||||
@@ -43,11 +46,7 @@ function DeltaTriple({
|
||||
<div className="mt-3 grid grid-cols-3 gap-1.5">
|
||||
{cells.map((c) => {
|
||||
const good =
|
||||
c.v === null
|
||||
? null
|
||||
: invert
|
||||
? c.v < 0
|
||||
: c.v > 0;
|
||||
c.v === null ? null : invert ? c.v < 0 : c.v > 0;
|
||||
const color =
|
||||
c.v === null
|
||||
? 'text-gray-500'
|
||||
@@ -83,6 +82,29 @@ function DeltaTriple({
|
||||
);
|
||||
}
|
||||
|
||||
function filterWeeklyByRange(
|
||||
rows: KpiWeeklyRow[],
|
||||
range: RangeKey
|
||||
): KpiWeeklyRow[] {
|
||||
if (range === 'all') return rows;
|
||||
const now = new Date();
|
||||
let from: Date;
|
||||
if (range === '7d') {
|
||||
from = new Date(now);
|
||||
from.setUTCDate(from.getUTCDate() - 7);
|
||||
} else if (range === '30d') {
|
||||
from = new Date(now);
|
||||
from.setUTCDate(from.getUTCDate() - 30);
|
||||
} else {
|
||||
from = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
||||
}
|
||||
return rows.filter((r) => {
|
||||
if (!r.week) return false;
|
||||
const d = new Date(r.week);
|
||||
return !Number.isNaN(d.getTime()) && d >= from;
|
||||
});
|
||||
}
|
||||
|
||||
export default function MetricsDashboard({
|
||||
label,
|
||||
portfolioWide,
|
||||
@@ -91,6 +113,8 @@ export default function MetricsDashboard({
|
||||
deltas,
|
||||
daily,
|
||||
sparse,
|
||||
weeklyRows = [],
|
||||
channelPoints = [],
|
||||
}: {
|
||||
label: string;
|
||||
portfolioWide: boolean;
|
||||
@@ -104,26 +128,85 @@ export default function MetricsDashboard({
|
||||
clicks: number;
|
||||
};
|
||||
sparse: boolean;
|
||||
weeklyRows?: KpiWeeklyRow[];
|
||||
channelPoints?: ChannelWeekPoint[];
|
||||
}) {
|
||||
const [range, setRange] = useState<RangeKey>('month');
|
||||
|
||||
const ranged = useMemo(
|
||||
() => filterWeeklyByRange(weeklyRows, range),
|
||||
[weeklyRows, range]
|
||||
);
|
||||
const periodTotals = useMemo(
|
||||
() => (ranged.length ? sumWeekly(ranged) : month),
|
||||
[ranged, month]
|
||||
);
|
||||
|
||||
const channelRows = useMemo(() => {
|
||||
const map = new Map<
|
||||
string,
|
||||
{ spend: number; leads: number; deals: number; revenue: number }
|
||||
>();
|
||||
const src =
|
||||
range === 'all'
|
||||
? channelPoints
|
||||
: channelPoints.filter((p) => {
|
||||
const d = new Date(p.week);
|
||||
if (Number.isNaN(d.getTime())) return false;
|
||||
if (range === 'month') {
|
||||
const now = new Date();
|
||||
return (
|
||||
d.getUTCFullYear() === now.getUTCFullYear() &&
|
||||
d.getUTCMonth() === now.getUTCMonth()
|
||||
);
|
||||
}
|
||||
const now = new Date();
|
||||
const from = new Date(now);
|
||||
from.setUTCDate(from.getUTCDate() - (range === '7d' ? 7 : 30));
|
||||
return d >= from;
|
||||
});
|
||||
for (const p of src) {
|
||||
const cur = map.get(p.channel) || {
|
||||
spend: 0,
|
||||
leads: 0,
|
||||
deals: 0,
|
||||
revenue: 0,
|
||||
};
|
||||
cur.spend += p.spend;
|
||||
cur.leads += p.leads;
|
||||
cur.deals += p.deals;
|
||||
cur.revenue += p.revenue;
|
||||
map.set(p.channel, cur);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.map(([channel, v]) => ({
|
||||
channel,
|
||||
...v,
|
||||
cpl: v.leads > 0 ? v.spend / v.leads : 0,
|
||||
roas: v.spend > 0 ? v.revenue / v.spend : 0,
|
||||
}))
|
||||
.sort((a, b) => b.spend - a.spend);
|
||||
}, [channelPoints, range]);
|
||||
|
||||
const cards: Card[] = [
|
||||
{
|
||||
key: 'spend',
|
||||
label: 'Inversión ads',
|
||||
hint: 'Mes en curso (kpi_weekly)',
|
||||
hint: 'Paid del periodo',
|
||||
format: formatEur,
|
||||
icon: <DollarSign className="w-4 h-4 text-brand-500" />,
|
||||
},
|
||||
{
|
||||
key: 'leads',
|
||||
label: 'Leads',
|
||||
hint: 'Cohorte · mes',
|
||||
hint: 'Captación periodo',
|
||||
format: formatNum,
|
||||
icon: <Users className="w-4 h-4 text-blue-400" />,
|
||||
},
|
||||
{
|
||||
key: 'cpl',
|
||||
label: 'CPL',
|
||||
hint: 'Coste por lead · mes',
|
||||
hint: 'Coste por lead',
|
||||
format: (v) => `${formatNum(v)} €`,
|
||||
icon: <MousePointerClick className="w-4 h-4 text-violet-400" />,
|
||||
invert: true,
|
||||
@@ -131,7 +214,7 @@ export default function MetricsDashboard({
|
||||
{
|
||||
key: 'cac',
|
||||
label: 'CAC cohorte',
|
||||
hint: 'Spend / clientes ganados',
|
||||
hint: 'Paid / cierres (parcial v1)',
|
||||
format: (v) => `${formatNum(v)} €`,
|
||||
icon: <Target className="w-4 h-4 text-amber-400" />,
|
||||
invert: true,
|
||||
@@ -157,28 +240,81 @@ export default function MetricsDashboard({
|
||||
<div className="flex flex-col md:flex-row md:items-end md:justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight text-white">
|
||||
Dashboard de métricas
|
||||
North Star · métricas
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
{label}
|
||||
{portfolioWide
|
||||
? ' · agrega todos los tenants (vista agencia)'
|
||||
: ' · zoom al cliente del selector'}
|
||||
. Comparativas WoW / MoM / YoY sobre <code>kpi_weekly</code>.
|
||||
? ' · portafolio'
|
||||
: ' · zoom cliente'}
|
||||
. Paid unificado ahora; CRM/GEO en siguientes fases.
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 bg-gray-900/50 border border-gray-800 rounded-lg px-3 py-2">
|
||||
Semana actual spend {formatEur(week.spend)} · leads {formatNum(week.leads)}
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarRange className="w-4 h-4 text-gray-500" />
|
||||
<div className="flex gap-1 rounded-lg border border-gray-800 p-0.5 bg-black/20">
|
||||
{(
|
||||
[
|
||||
['7d', '7d'],
|
||||
['30d', '30d'],
|
||||
['month', 'Mes'],
|
||||
['all', 'Todo'],
|
||||
] as [RangeKey, string][]
|
||||
).map(([k, lbl]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => setRange(k)}
|
||||
className={`px-2.5 py-1 text-xs rounded-md ${
|
||||
range === k
|
||||
? 'bg-brand-500/20 text-brand-300'
|
||||
: 'text-gray-400 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{lbl}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sparse && (
|
||||
<p className="text-xs text-amber-400/90 border border-amber-500/20 rounded-lg px-3 py-2">
|
||||
Histórico limitado en warehouse: si WoW/MoM/YoY salen «—», falta
|
||||
pipeline Windsor/n8n o semanas previas / año anterior.
|
||||
Histórico limitado: si faltan deltas o canales, el warehouse aún no
|
||||
tiene semanas suficientes.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* North Star strip */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
{[
|
||||
{ label: 'Inversión periodo', value: formatEur(periodTotals.spend) },
|
||||
{ label: 'Leads', value: formatNum(periodTotals.leads) },
|
||||
{
|
||||
label: 'CAC (paid)',
|
||||
value: periodTotals.cac
|
||||
? `${formatNum(periodTotals.cac)} €`
|
||||
: '—',
|
||||
},
|
||||
{
|
||||
label: 'ROAS cohorte',
|
||||
value: periodTotals.roas
|
||||
? `${formatNum(periodTotals.roas)}x`
|
||||
: '—',
|
||||
},
|
||||
].map((s) => (
|
||||
<div
|
||||
key={s.label}
|
||||
className="rounded-xl border border-brand-500/20 bg-brand-500/5 px-4 py-3"
|
||||
>
|
||||
<p className="text-[10px] uppercase tracking-wider text-brand-400/80">
|
||||
{s.label}
|
||||
</p>
|
||||
<p className="text-xl font-bold text-white mt-1">{s.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||
{cards.map((c) => (
|
||||
<div
|
||||
@@ -192,7 +328,7 @@ export default function MetricsDashboard({
|
||||
{c.icon}
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-white">
|
||||
{c.format(month[c.key])}
|
||||
{c.format(periodTotals[c.key])}
|
||||
</p>
|
||||
<p className="text-[11px] text-gray-500 mt-1">{c.hint}</p>
|
||||
<DeltaTriple delta={deltas[c.key]} invert={c.invert} />
|
||||
@@ -200,41 +336,112 @@ export default function MetricsDashboard({
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Channel matrix */}
|
||||
<section className="bg-[#111827] border border-gray-800 rounded-xl p-5 space-y-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
Matriz por canal
|
||||
</h3>
|
||||
<p className="text-[11px] text-gray-500">
|
||||
Clic → dash secundario del canal
|
||||
</p>
|
||||
</div>
|
||||
{channelRows.length === 0 ? (
|
||||
<p className="text-xs text-gray-500 py-6 text-center">
|
||||
Sin series de canal en el periodo. Cuando Windsor cargue
|
||||
`kpi_weekly.channel`, aparecerán aquí.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead className="text-gray-500 border-b border-gray-800">
|
||||
<tr>
|
||||
<th className="py-2 pr-3 font-medium">Canal</th>
|
||||
<th className="py-2 pr-3 font-medium">Inversión</th>
|
||||
<th className="py-2 pr-3 font-medium">Leads</th>
|
||||
<th className="py-2 pr-3 font-medium">CPL</th>
|
||||
<th className="py-2 pr-3 font-medium">Revenue</th>
|
||||
<th className="py-2 font-medium">ROAS</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{channelRows.map((row) => (
|
||||
<tr
|
||||
key={row.channel}
|
||||
className="border-b border-gray-900 hover:bg-white/[0.02]"
|
||||
>
|
||||
<td className="py-2.5 pr-3">
|
||||
<Link
|
||||
href={`/dashboard/kpis/canal/${encodeURIComponent(row.channel)}`}
|
||||
className="text-brand-400 hover:text-brand-300 font-semibold capitalize"
|
||||
>
|
||||
{row.channel}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="py-2.5 pr-3 text-gray-200">
|
||||
{formatEur(row.spend)}
|
||||
</td>
|
||||
<td className="py-2.5 pr-3 text-gray-200">
|
||||
{formatNum(row.leads)}
|
||||
</td>
|
||||
<td className="py-2.5 pr-3 text-gray-200">
|
||||
{row.cpl ? `${formatNum(row.cpl)} €` : '—'}
|
||||
</td>
|
||||
<td className="py-2.5 pr-3 text-gray-200">
|
||||
{formatEur(row.revenue)}
|
||||
</td>
|
||||
<td className="py-2.5 text-gray-200">
|
||||
{row.roas ? `${formatNum(row.roas)}x` : '—'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-2 pt-2">
|
||||
{['GEO', 'CRM close %', 'LTV'].map((soon) => (
|
||||
<div
|
||||
key={soon}
|
||||
className="rounded-lg border border-dashed border-gray-800 px-3 py-2 text-[11px] text-gray-500"
|
||||
>
|
||||
{soon} · fase 2 (stub)
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5">
|
||||
<div className="flex items-center justify-between text-gray-400 mb-2">
|
||||
<span className="text-xs uppercase tracking-wider">Ads · 30d (ad_daily)</span>
|
||||
<span className="text-xs uppercase tracking-wider">
|
||||
Ads · ventana diaria
|
||||
</span>
|
||||
<Eye className="w-4 h-4 text-sky-400" />
|
||||
</div>
|
||||
<p className="text-lg font-bold text-white">
|
||||
{formatEur(daily.spend)}
|
||||
</p>
|
||||
<p className="text-lg font-bold text-white">{formatEur(daily.spend)}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{formatNum(daily.leads)} leads plataforma ·{' '}
|
||||
{formatNum(daily.impressions)} impr. · {formatNum(daily.clicks)}{' '}
|
||||
clicks
|
||||
{formatNum(daily.leads)} leads · {formatNum(daily.impressions)} impr.
|
||||
· {formatNum(daily.clicks)} clicks
|
||||
</p>
|
||||
<p className="text-[11px] text-gray-600 mt-2">
|
||||
Semana actual: {formatEur(week.spend)} · {formatNum(week.leads)}{' '}
|
||||
leads
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5 md:col-span-2">
|
||||
<p className="text-xs uppercase tracking-wider text-gray-500 mb-2">
|
||||
Cómo leer las deltas
|
||||
Cómo leer
|
||||
</p>
|
||||
<ul className="text-xs text-gray-400 space-y-1 list-disc list-inside">
|
||||
<li>
|
||||
<strong className="text-gray-300">WoW</strong>: semana actual vs
|
||||
anterior
|
||||
El selector de fechas filtra inversión/leads del periodo; WoW/MoM/YoY
|
||||
siguen siendo comparativas de calendario.
|
||||
</li>
|
||||
<li>
|
||||
<strong className="text-gray-300">MoM</strong>: mes actual vs mes
|
||||
previo
|
||||
</li>
|
||||
<li>
|
||||
<strong className="text-gray-300">YoY</strong>: mismo mes vs hace
|
||||
un año
|
||||
</li>
|
||||
<li>
|
||||
En CPL/CAC, bajar es bueno (flecha verde si el % es negativo)
|
||||
CAC unificado con fee/tools y cierre CRM llega en v2.
|
||||
</li>
|
||||
<li>GEO / LTV aparecen como stubs hasta tener pipeline de datos.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
152
src/lib/content-collab.ts
Normal file
152
src/lib/content-collab.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
/** Dual agency/client approval + comments for calendar posts and assets. */
|
||||
|
||||
import { isAgencyRole, serviceHeaders, supabaseUrl, userRole } from '@/lib/agency';
|
||||
|
||||
export type ContentResourceType = 'calendar_post' | 'asset';
|
||||
export type Party = 'agency' | 'client';
|
||||
|
||||
export type ApprovalRow = {
|
||||
party: Party;
|
||||
approved: boolean;
|
||||
actor_email?: string | null;
|
||||
created_at?: string;
|
||||
note?: string | null;
|
||||
};
|
||||
|
||||
export type CommentRow = {
|
||||
id: string;
|
||||
body: string;
|
||||
author_email?: string | null;
|
||||
author_party: Party;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export function partyFromUser(user: {
|
||||
app_metadata?: Record<string, unknown>;
|
||||
user_metadata?: Record<string, unknown>;
|
||||
} | null): Party {
|
||||
return isAgencyRole(userRole(user)) ? 'agency' : 'client';
|
||||
}
|
||||
|
||||
export function dualStatus(approvals: ApprovalRow[]): {
|
||||
agency: boolean;
|
||||
client: boolean;
|
||||
both: boolean;
|
||||
label: string;
|
||||
} {
|
||||
const agency = approvals.some((a) => a.party === 'agency' && a.approved);
|
||||
const client = approvals.some((a) => a.party === 'client' && a.approved);
|
||||
const both = agency && client;
|
||||
let label = 'Pendiente';
|
||||
if (both) label = 'Doble OK';
|
||||
else if (agency && !client) label = 'OK agencia · falta cliente';
|
||||
else if (client && !agency) label = 'OK cliente · falta agencia';
|
||||
return { agency, client, both, label };
|
||||
}
|
||||
|
||||
export async function listApprovals(
|
||||
tenantId: string,
|
||||
resourceType: ContentResourceType,
|
||||
resourceIds: string[]
|
||||
): Promise<Record<string, ApprovalRow[]>> {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers || !resourceIds.length) return {};
|
||||
const ids = resourceIds.map(encodeURIComponent).join(',');
|
||||
const url =
|
||||
`${supabaseUrl()}/rest/v1/content_approvals?tenant_id=eq.${encodeURIComponent(tenantId)}` +
|
||||
`&resource_type=eq.${resourceType}&resource_id=in.(${ids})&select=*`;
|
||||
const r = await fetch(url, { headers, cache: 'no-store' });
|
||||
if (!r.ok) return {};
|
||||
const rows = (await r.json()) as (ApprovalRow & { resource_id: string })[];
|
||||
const map: Record<string, ApprovalRow[]> = {};
|
||||
for (const row of rows) {
|
||||
(map[row.resource_id] ||= []).push(row);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export async function listComments(
|
||||
tenantId: string,
|
||||
resourceType: ContentResourceType,
|
||||
resourceId: string
|
||||
): Promise<CommentRow[]> {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) return [];
|
||||
const url =
|
||||
`${supabaseUrl()}/rest/v1/content_comments?tenant_id=eq.${encodeURIComponent(tenantId)}` +
|
||||
`&resource_type=eq.${resourceType}&resource_id=eq.${encodeURIComponent(resourceId)}` +
|
||||
`&select=*&order=created_at.asc`;
|
||||
const r = await fetch(url, { headers, cache: 'no-store' });
|
||||
if (!r.ok) return [];
|
||||
return (await r.json()) as CommentRow[];
|
||||
}
|
||||
|
||||
export async function upsertApproval(opts: {
|
||||
tenantId: string;
|
||||
resourceType: ContentResourceType;
|
||||
resourceId: string;
|
||||
party: Party;
|
||||
approved: boolean;
|
||||
actorId?: string | null;
|
||||
actorEmail?: string | null;
|
||||
note?: string | null;
|
||||
}): Promise<void> {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) throw new Error('no service role');
|
||||
const body = {
|
||||
tenant_id: opts.tenantId,
|
||||
resource_type: opts.resourceType,
|
||||
resource_id: opts.resourceId,
|
||||
party: opts.party,
|
||||
approved: opts.approved,
|
||||
actor_id: opts.actorId || null,
|
||||
actor_email: opts.actorEmail || null,
|
||||
note: opts.note || null,
|
||||
};
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/content_approvals?on_conflict=tenant_id,resource_type,resource_id,party`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'resolution=merge-duplicates,return=minimal',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}
|
||||
);
|
||||
if (!r.ok) throw new Error(await r.text());
|
||||
}
|
||||
|
||||
export async function insertComment(opts: {
|
||||
tenantId: string;
|
||||
resourceType: ContentResourceType;
|
||||
resourceId: string;
|
||||
body: string;
|
||||
authorId?: string | null;
|
||||
authorEmail?: string | null;
|
||||
authorParty: Party;
|
||||
}): Promise<CommentRow> {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) throw new Error('no service role');
|
||||
const r = await fetch(`${supabaseUrl()}/rest/v1/content_comments`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
tenant_id: opts.tenantId,
|
||||
resource_type: opts.resourceType,
|
||||
resource_id: opts.resourceId,
|
||||
body: opts.body,
|
||||
author_id: opts.authorId || null,
|
||||
author_email: opts.authorEmail || null,
|
||||
author_party: opts.authorParty,
|
||||
}),
|
||||
});
|
||||
if (!r.ok) throw new Error(await r.text());
|
||||
const rows = await r.json();
|
||||
return Array.isArray(rows) ? rows[0] : rows;
|
||||
}
|
||||
Reference in New Issue
Block a user