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:
92
scripts/dokploy_apply_content_collab.py
Normal file
92
scripts/dokploy_apply_content_collab.py
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply sql/content_collab.sql via Dokploy supabase-db terminal."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
ROOT = Path("/Users/4ventures/4ventures-client-portal")
|
||||||
|
BPS = Path("/Users/4ventures/Projects/bps-facturacion")
|
||||||
|
SQL = ROOT / "sql" / "content_collab.sql"
|
||||||
|
BASE = "https://dokploy.4ventures.es"
|
||||||
|
|
||||||
|
|
||||||
|
def env(key: str) -> str:
|
||||||
|
v = os.environ.get(key, "").strip()
|
||||||
|
if v:
|
||||||
|
return v
|
||||||
|
p = BPS / ".env"
|
||||||
|
if not p.is_file():
|
||||||
|
return ""
|
||||||
|
for line in p.read_text().splitlines():
|
||||||
|
if line.startswith(f"{key}="):
|
||||||
|
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
email = env("DOKPLOY_EMAIL") or "marketing@4ventures.es"
|
||||||
|
password = env("DOKPLOY_PASSWORD")
|
||||||
|
b64 = base64.b64encode(SQL.read_text(encoding="utf-8").encode()).decode()
|
||||||
|
chunks = [b64[i : i + 180] for i in range(0, len(b64), 180)]
|
||||||
|
|
||||||
|
with sync_playwright() as p:
|
||||||
|
browser = p.chromium.launch(headless=True)
|
||||||
|
page = browser.new_page(viewport={"width": 1400, "height": 1000})
|
||||||
|
page.goto(BASE + "/", wait_until="domcontentloaded", timeout=90000)
|
||||||
|
page.wait_for_timeout(800)
|
||||||
|
if "/dashboard" not in page.url:
|
||||||
|
page.locator('input[type="email"], input[name="email"]').first.fill(email)
|
||||||
|
page.locator('input[type="password"]').first.fill(password)
|
||||||
|
page.locator('button[type="submit"]').first.click()
|
||||||
|
page.wait_for_url(re.compile(r"/dashboard"), timeout=90000)
|
||||||
|
print("login ok", flush=True)
|
||||||
|
page.goto(f"{BASE}/dashboard/docker", wait_until="domcontentloaded", timeout=120000)
|
||||||
|
page.wait_for_timeout(800)
|
||||||
|
page.locator("input[placeholder*='ilter' i], input[placeholder*='earch' i]").first.fill(
|
||||||
|
"supabase-db"
|
||||||
|
)
|
||||||
|
page.wait_for_timeout(1000)
|
||||||
|
page.keyboard.press("Escape")
|
||||||
|
page.wait_for_timeout(200)
|
||||||
|
page.get_by_role("button", name=re.compile(r"Open menu", re.I)).first.click()
|
||||||
|
page.wait_for_timeout(400)
|
||||||
|
page.get_by_text("Terminal", exact=True).click()
|
||||||
|
page.wait_for_timeout(1000)
|
||||||
|
if page.locator("button", has_text="Bash").count():
|
||||||
|
page.locator("button", has_text="Bash").first.click()
|
||||||
|
page.wait_for_timeout(2800)
|
||||||
|
if page.locator("textarea.xterm-helper-textarea").count():
|
||||||
|
page.locator("textarea.xterm-helper-textarea").first.click()
|
||||||
|
|
||||||
|
def run(cmd: str, wait: int = 800) -> None:
|
||||||
|
page.keyboard.type(cmd, delay=1)
|
||||||
|
page.keyboard.press("Enter")
|
||||||
|
page.wait_for_timeout(wait)
|
||||||
|
|
||||||
|
run("rm -f /tmp/cc.b64 /tmp/cc.sql; echo READY", 1200)
|
||||||
|
for i, ch in enumerate(chunks):
|
||||||
|
op = ">" if i == 0 else ">>"
|
||||||
|
run(f"printf '%s' '{ch}' {op} /tmp/cc.b64", 400)
|
||||||
|
run(
|
||||||
|
"base64 -d /tmp/cc.b64 > /tmp/cc.sql && "
|
||||||
|
"psql -U postgres -d postgres -v ON_ERROR_STOP=1 -f /tmp/cc.sql; echo EXIT:$?",
|
||||||
|
14000,
|
||||||
|
)
|
||||||
|
text = page.evaluate(
|
||||||
|
"() => (document.querySelector('.xterm-rows')||{}).innerText||''"
|
||||||
|
)
|
||||||
|
browser.close()
|
||||||
|
ok = "EXIT:0" in text
|
||||||
|
print("SQL_OK", ok, flush=True)
|
||||||
|
print(text[-600:], flush=True)
|
||||||
|
return 0 if ok else 6
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
180
sql/content_collab.sql
Normal file
180
sql/content_collab.sql
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
-- Dual approval (agency + client) + threaded comments for calendar posts & assets
|
||||||
|
-- Idempotent. Private portal only (no public publish).
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Calendar posts (normalized; private per tenant)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
create table if not exists public.calendar_posts (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
tenant_id uuid not null references public.tenants(id) on delete cascade,
|
||||||
|
external_key text,
|
||||||
|
month text,
|
||||||
|
date date not null,
|
||||||
|
time_slot text,
|
||||||
|
platform text not null
|
||||||
|
check (platform in (
|
||||||
|
'instagram', 'facebook', 'linkedin', 'tiktok', 'youtube', 'x', 'other'
|
||||||
|
)),
|
||||||
|
format text,
|
||||||
|
pillar text,
|
||||||
|
title text not null,
|
||||||
|
hook text,
|
||||||
|
body text,
|
||||||
|
cta text,
|
||||||
|
hashtags text,
|
||||||
|
objective_metric text,
|
||||||
|
status text not null default 'draft'
|
||||||
|
check (status in ('draft', 'in_review', 'scheduled', 'published', 'archived')),
|
||||||
|
agency_approved_at timestamptz,
|
||||||
|
agency_approved_by uuid references auth.users(id),
|
||||||
|
client_approved_at timestamptz,
|
||||||
|
client_approved_by uuid references auth.users(id),
|
||||||
|
meta jsonb not null default '{}'::jsonb,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now(),
|
||||||
|
unique (tenant_id, external_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists calendar_posts_tenant_month_idx
|
||||||
|
on public.calendar_posts (tenant_id, month, date);
|
||||||
|
create index if not exists calendar_posts_tenant_platform_idx
|
||||||
|
on public.calendar_posts (tenant_id, platform, date);
|
||||||
|
|
||||||
|
alter table public.calendar_posts enable row level security;
|
||||||
|
|
||||||
|
drop policy if exists calendar_posts_tenant_select on public.calendar_posts;
|
||||||
|
drop policy if exists calendar_posts_tenant_write on public.calendar_posts;
|
||||||
|
|
||||||
|
create policy calendar_posts_tenant_select on public.calendar_posts
|
||||||
|
for select using (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy calendar_posts_tenant_write on public.calendar_posts
|
||||||
|
for all using (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
with check (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Shared comments (calendar_post | asset)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
create table if not exists public.content_comments (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
tenant_id uuid not null references public.tenants(id) on delete cascade,
|
||||||
|
resource_type text not null check (resource_type in ('calendar_post', 'asset')),
|
||||||
|
resource_id text not null,
|
||||||
|
body text not null,
|
||||||
|
author_id uuid references auth.users(id),
|
||||||
|
author_email text,
|
||||||
|
author_party text not null check (author_party in ('agency', 'client')),
|
||||||
|
created_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists content_comments_resource_idx
|
||||||
|
on public.content_comments (tenant_id, resource_type, resource_id, created_at);
|
||||||
|
|
||||||
|
alter table public.content_comments enable row level security;
|
||||||
|
|
||||||
|
drop policy if exists content_comments_tenant_select on public.content_comments;
|
||||||
|
drop policy if exists content_comments_tenant_insert on public.content_comments;
|
||||||
|
|
||||||
|
create policy content_comments_tenant_select on public.content_comments
|
||||||
|
for select using (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy content_comments_tenant_insert on public.content_comments
|
||||||
|
for insert with check (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Dual approval events (calendar_post | asset)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
create table if not exists public.content_approvals (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
tenant_id uuid not null references public.tenants(id) on delete cascade,
|
||||||
|
resource_type text not null check (resource_type in ('calendar_post', 'asset')),
|
||||||
|
resource_id text not null,
|
||||||
|
party text not null check (party in ('agency', 'client')),
|
||||||
|
approved boolean not null default true,
|
||||||
|
note text,
|
||||||
|
actor_id uuid references auth.users(id),
|
||||||
|
actor_email text,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
unique (tenant_id, resource_type, resource_id, party)
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.content_approvals enable row level security;
|
||||||
|
|
||||||
|
drop policy if exists content_approvals_tenant_select on public.content_approvals;
|
||||||
|
drop policy if exists content_approvals_tenant_write on public.content_approvals;
|
||||||
|
|
||||||
|
create policy content_approvals_tenant_select on public.content_approvals
|
||||||
|
for select using (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy content_approvals_tenant_write on public.content_approvals
|
||||||
|
for all using (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
with check (
|
||||||
|
tenant_id::text = coalesce(
|
||||||
|
auth.jwt() -> 'app_metadata' ->> 'tenant_id',
|
||||||
|
auth.jwt() -> 'user_metadata' ->> 'tenant_id'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Assets: dual validation columns
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
alter table public.asset_files
|
||||||
|
add column if not exists review_status text not null default 'in_review';
|
||||||
|
|
||||||
|
alter table public.asset_files
|
||||||
|
drop constraint if exists asset_files_review_status_check;
|
||||||
|
|
||||||
|
alter table public.asset_files
|
||||||
|
add constraint asset_files_review_status_check
|
||||||
|
check (review_status in ('draft', 'in_review', 'validated', 'archived'));
|
||||||
|
|
||||||
|
alter table public.asset_files
|
||||||
|
add column if not exists agency_approved_at timestamptz;
|
||||||
|
alter table public.asset_files
|
||||||
|
add column if not exists agency_approved_by uuid references auth.users(id);
|
||||||
|
alter table public.asset_files
|
||||||
|
add column if not exists client_approved_at timestamptz;
|
||||||
|
alter table public.asset_files
|
||||||
|
add column if not exists client_approved_by uuid references auth.users(id);
|
||||||
|
|
||||||
|
comment on table public.calendar_posts is
|
||||||
|
'Private RRSS calendar per tenant. Dual agency/client approval. No public publish.';
|
||||||
|
comment on table public.content_comments is
|
||||||
|
'Comments on calendar posts or assets (agency + client).';
|
||||||
|
comment on table public.content_approvals is
|
||||||
|
'Dual-check approvals: agency and client must both approve for full OK.';
|
||||||
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';
|
'use client';
|
||||||
|
|
||||||
import React, { useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
CalendarDays,
|
CalendarDays,
|
||||||
Instagram,
|
Instagram,
|
||||||
Linkedin,
|
Linkedin,
|
||||||
Facebook,
|
Facebook,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
Clock,
|
|
||||||
FileText,
|
|
||||||
Layers,
|
|
||||||
Tag,
|
|
||||||
ExternalLink,
|
|
||||||
X,
|
|
||||||
Copy,
|
Copy,
|
||||||
Check,
|
Check,
|
||||||
Eye,
|
Eye,
|
||||||
Sparkles
|
X,
|
||||||
|
MessageSquare,
|
||||||
|
ShieldCheck,
|
||||||
|
Music2,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
interface Post {
|
export type CalendarPost = {
|
||||||
id: string;
|
id: string;
|
||||||
date: string;
|
date: string;
|
||||||
time: string;
|
time: string;
|
||||||
platform: 'instagram' | 'linkedin' | 'facebook';
|
platform: string;
|
||||||
format: string;
|
format: string;
|
||||||
pillar: string;
|
pillar: string;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -31,378 +28,494 @@ interface Post {
|
|||||||
body: string;
|
body: string;
|
||||||
cta: string;
|
cta: string;
|
||||||
hashtags: 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 {
|
function DualBadge({ dual }: { dual?: Dual }) {
|
||||||
initialPosts: Post[];
|
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;
|
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');
|
||||||
const [platformFilter, setPlatformFilter] = useState<'all' | 'instagram' | 'linkedin' | 'facebook'>('all');
|
const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'scheduled' | 'draft'>(
|
||||||
const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'scheduled' | 'draft'>('all');
|
'all'
|
||||||
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
);
|
||||||
|
const [view, setView] = useState<'month' | 'list'>('month');
|
||||||
|
const [selectedPost, setSelectedPost] = useState<CalendarPost | null>(null);
|
||||||
const [copied, setCopied] = useState(false);
|
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 filteredPosts = initialPosts.filter((p) => {
|
||||||
const matchPlatform = platformFilter === 'all' || p.platform === platformFilter;
|
const matchPlatform = platformFilter === 'all' || p.platform === platformFilter;
|
||||||
const matchStatus = statusFilter === 'all' || p.status === statusFilter;
|
const matchStatus = statusFilter === 'all' || p.status === statusFilter;
|
||||||
return matchPlatform && matchStatus;
|
return matchPlatform && matchStatus;
|
||||||
});
|
});
|
||||||
|
|
||||||
// KPI counters
|
|
||||||
const totalPosts = initialPosts.length;
|
const totalPosts = initialPosts.length;
|
||||||
const instagramCount = initialPosts.filter((p) => p.platform === 'instagram').length;
|
const approvedCount = initialPosts.filter(
|
||||||
const linkedinCount = initialPosts.filter((p) => p.platform === 'linkedin').length;
|
(p) => dualMap[p.id]?.both || p.status === 'approved'
|
||||||
const facebookCount = initialPosts.filter((p) => p.platform === 'facebook').length;
|
).length;
|
||||||
const approvedCount = initialPosts.filter((p) => 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}`;
|
const text = `${post.hook}\n\n${post.body}\n\n${post.cta}\n\n${post.hashtags}`;
|
||||||
navigator.clipboard.writeText(text);
|
navigator.clipboard.writeText(text);
|
||||||
setCopied(true);
|
setCopied(true);
|
||||||
setTimeout(() => setCopied(false), 2000);
|
setTimeout(() => setCopied(false), 2000);
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPlatformBadge = (platform: string) => {
|
async function approve(action: 'approve' | 'revoke') {
|
||||||
switch (platform) {
|
if (!selectedPost) return;
|
||||||
case 'instagram':
|
setBusy(true);
|
||||||
return (
|
setCollabErr(null);
|
||||||
<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">
|
try {
|
||||||
<Instagram className="w-3.5 h-3.5" /> Instagram
|
const r = await fetch('/api/calendar/collab', {
|
||||||
</span>
|
method: 'POST',
|
||||||
);
|
headers: { 'Content-Type': 'application/json' },
|
||||||
case 'linkedin':
|
body: JSON.stringify({ action, postId: selectedPost.id }),
|
||||||
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">
|
const j = await r.json();
|
||||||
<Linkedin className="w-3.5 h-3.5" /> LinkedIn
|
if (!r.ok) throw new Error(j.error || 'Error');
|
||||||
</span>
|
setDualMap((prev) => ({ ...prev, [selectedPost.id]: j.dual }));
|
||||||
);
|
} catch (e) {
|
||||||
case 'facebook':
|
setCollabErr(e instanceof Error ? e.message : 'Error');
|
||||||
return (
|
} finally {
|
||||||
<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">
|
setBusy(false);
|
||||||
<Facebook className="w-3.5 h-3.5" /> Facebook
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
async function sendComment() {
|
||||||
switch (status) {
|
if (!selectedPost || !commentText.trim()) return;
|
||||||
case 'approved':
|
setBusy(true);
|
||||||
return (
|
setCollabErr(null);
|
||||||
<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">
|
try {
|
||||||
<CheckCircle2 className="w-3 h-3" /> Aprobado
|
const r = await fetch('/api/calendar/collab', {
|
||||||
</span>
|
method: 'POST',
|
||||||
);
|
headers: { 'Content-Type': 'application/json' },
|
||||||
case 'scheduled':
|
body: JSON.stringify({
|
||||||
return (
|
action: 'comment',
|
||||||
<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">
|
postId: selectedPost.id,
|
||||||
<Clock className="w-3 h-3" /> Programado
|
body: commentText.trim(),
|
||||||
</span>
|
}),
|
||||||
);
|
});
|
||||||
default:
|
const j = await r.json();
|
||||||
return (
|
if (!r.ok) throw new Error(j.error || 'Error');
|
||||||
<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">
|
setComments((prev) => [...prev, j.comment]);
|
||||||
<Sparkles className="w-3 h-3" /> En Revisión
|
setCommentText('');
|
||||||
</span>
|
} 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 (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* KPI Top Cards */}
|
<div className="flex flex-col sm:flex-row sm:items-end justify-between gap-3">
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3.5">
|
<p className="text-xs text-gray-500">
|
||||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
{calendarTitle} · privado (sin publicación pública) · doble check
|
||||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
agencia/cliente
|
||||||
<span>Total Posts</span>
|
</p>
|
||||||
<CalendarDays className="w-4 h-4 text-brand-400" />
|
<div className="flex gap-1 rounded-lg border border-gray-800 p-0.5 bg-black/20">
|
||||||
</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>
|
['month', 'Mes'],
|
||||||
</div>
|
['list', 'Lista'],
|
||||||
|
] as const
|
||||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
).map(([k, label]) => (
|
||||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
<button
|
||||||
<span>Instagram</span>
|
key={k}
|
||||||
<Instagram className="w-4 h-4 text-pink-400" />
|
type="button"
|
||||||
</div>
|
onClick={() => setView(k)}
|
||||||
<p className="text-2xl font-extrabold text-white">{instagramCount}</p>
|
className={`px-2.5 py-1 text-xs rounded-md ${
|
||||||
<p className="text-[10px] text-pink-400/80 mt-0.5">Carruseles & Reels</p>
|
view === k ? 'bg-brand-500/20 text-brand-300' : 'text-gray-400'
|
||||||
</div>
|
}`}
|
||||||
|
>
|
||||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
{label}
|
||||||
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
</button>
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filter Bar */}
|
<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 flex flex-col md:flex-row md:items-center justify-between gap-4">
|
<div className="bg-[#111827] border border-gray-800 rounded-xl p-4">
|
||||||
{/* Platform Tabs */}
|
<div className="flex items-center justify-between text-gray-400 text-xs mb-1">
|
||||||
<div className="flex items-center gap-1.5 overflow-x-auto pb-1 md:pb-0">
|
<span>Total piezas</span>
|
||||||
<button
|
<CalendarDays className="w-4 h-4 text-brand-400" />
|
||||||
onClick={() => setPlatformFilter('all')}
|
</div>
|
||||||
className={`px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all cursor-pointer ${
|
<p className="text-2xl font-extrabold text-white">{totalPosts}</p>
|
||||||
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>
|
</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">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-xs text-gray-400">Estado:</span>
|
<span className="text-xs text-gray-400">Estado:</span>
|
||||||
<select
|
<select
|
||||||
value={statusFilter}
|
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"
|
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="approved">Aprobados</option>
|
||||||
<option value="scheduled">Programados</option>
|
<option value="scheduled">Programados</option>
|
||||||
<option value="draft">Borradores en revisión</option>
|
<option value="draft">En revisión</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Posts Grid */}
|
{view === 'month' ? (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
<div className="space-y-3">
|
||||||
{filteredPosts.length === 0 ? (
|
{byDay.length === 0 ? (
|
||||||
<div className="col-span-full bg-[#111827] border border-gray-800 rounded-xl p-12 text-center text-gray-400">
|
<EmptyState />
|
||||||
<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>
|
byDay.map(([day, posts]) => (
|
||||||
<p className="text-xs text-gray-400 mt-1">Prueba a seleccionar «Todos los canales» o «Todos los estados».</p>
|
<div
|
||||||
</div>
|
key={day}
|
||||||
) : (
|
className="rounded-xl border border-gray-800 bg-[#111827] p-4"
|
||||||
filteredPosts.map((post) => (
|
>
|
||||||
<div
|
<p className="text-xs font-semibold text-brand-400 font-mono mb-3">
|
||||||
key={post.id}
|
{new Date(day).toLocaleDateString('es-ES', {
|
||||||
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"
|
weekday: 'long',
|
||||||
>
|
day: 'numeric',
|
||||||
<div>
|
month: 'long',
|
||||||
{/* 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}
|
|
||||||
</p>
|
</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>
|
||||||
|
) : (
|
||||||
|
<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 && (
|
{selectedPost && (
|
||||||
<div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex items-center justify-center p-4">
|
<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">
|
<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">
|
||||||
{/* Modal Header */}
|
|
||||||
<div className="p-5 border-b border-gray-800 flex items-center justify-between bg-[#111827]">
|
<div className="p-5 border-b border-gray-800 flex items-center justify-between bg-[#111827]">
|
||||||
<div className="flex items-center gap-3">
|
<div>
|
||||||
{getPlatformBadge(selectedPost.platform)}
|
<h3 className="text-base font-bold text-white">{selectedPost.title}</h3>
|
||||||
<div>
|
<p className="text-xs text-gray-400 font-mono mt-0.5">
|
||||||
<h3 className="text-base font-bold text-white">{selectedPost.title}</h3>
|
{selectedPost.platform} · {selectedPost.date} · {selectedPost.time}h
|
||||||
<p className="text-xs text-gray-400 font-mono">
|
</p>
|
||||||
Programado para: {new Date(selectedPost.date).toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' })} a las {selectedPost.time}h
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={() => setSelectedPost(null)}
|
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" />
|
<X className="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Modal Body */}
|
|
||||||
<div className="p-6 overflow-y-auto space-y-4 text-sm text-gray-200">
|
<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 flex-wrap items-center gap-2">
|
||||||
<div className="flex items-center gap-2">
|
<DualBadge dual={dualMap[selectedPost.id]} />
|
||||||
<span className="text-xs text-gray-400 font-medium">Pilar:</span>
|
<span className="text-[10px] text-gray-500">
|
||||||
<span className="text-xs font-semibold text-brand-400 bg-brand-950/60 px-2 py-0.5 rounded border border-brand-800/40">
|
Tú: {party === 'agency' ? 'Agencia' : 'Cliente'}
|
||||||
{selectedPost.pillar}
|
</span>
|
||||||
</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>
|
</div>
|
||||||
|
|
||||||
{/* Hook */}
|
<Block label="Hook" className="text-amber-300">
|
||||||
<div>
|
{selectedPost.hook}
|
||||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
</Block>
|
||||||
Gancho / Hook de Apertura
|
<Block label="Copy">{selectedPost.body}</Block>
|
||||||
</label>
|
<Block label="CTA" className="text-brand-300">
|
||||||
<div className="p-3.5 rounded-xl bg-gray-900 border border-gray-800 font-medium text-amber-300 text-sm">
|
{selectedPost.cta}
|
||||||
{selectedPost.hook}
|
</Block>
|
||||||
</div>
|
<Block label="Hashtags" className="text-blue-400 font-mono text-xs">
|
||||||
</div>
|
{selectedPost.hashtags}
|
||||||
|
</Block>
|
||||||
|
|
||||||
{/* Body */}
|
{canCollaborate && (
|
||||||
<div>
|
<div className="rounded-xl border border-gray-800 bg-black/20 p-4 space-y-3">
|
||||||
<label className="text-xs uppercase tracking-wider font-bold text-gray-400 block mb-1">
|
<div className="flex items-center gap-2 text-xs font-semibold text-white">
|
||||||
Cuerpo Persuasivo
|
<MessageSquare className="w-3.5 h-3.5 text-sky-400" />
|
||||||
</label>
|
Comentarios
|
||||||
<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">
|
</div>
|
||||||
{selectedPost.body}
|
<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>
|
||||||
</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>
|
</div>
|
||||||
|
|
||||||
{/* Modal Footer */}
|
<div className="p-4 border-t border-gray-800 bg-[#111827] flex flex-wrap items-center justify-between gap-2">
|
||||||
<div className="p-4 border-t border-gray-800 bg-[#111827] flex items-center justify-between">
|
<button
|
||||||
<span className="text-xs text-gray-400">Generado por Agente #07 Contenido</span>
|
type="button"
|
||||||
<div className="flex gap-2">
|
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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => copyFullCopy(selectedPost)}
|
disabled={busy}
|
||||||
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"
|
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" />}
|
<ShieldCheck className="w-3.5 h-3.5" />
|
||||||
<span>{copied ? '¡Copy Copiado!' : 'Copiar Texto para Publicar'}</span>
|
{myApproved ? 'Quitar mi OK' : `Aprobar (${party === 'agency' ? 'agencia' : 'cliente'})`}
|
||||||
</button>
|
</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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -410,3 +523,89 @@ export default function CalendarClient({ initialPosts, calendarTitle }: Calendar
|
|||||||
</div>
|
</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}
|
Calendario editorial — {ctx.label}
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-gray-400 mt-1 max-w-2xl">
|
<p className="text-sm text-gray-400 mt-1 max-w-2xl">
|
||||||
Plan de publicaciones (IG / FB / LinkedIn) guardado en{' '}
|
Plan RRSS privado por cliente: vista unificada + pestaña por red.
|
||||||
<code>documents</code> con <code>type=calendar</code>, generado por
|
Cliente y agencia pueden leer, comentar y dar OK (doble check). Sin
|
||||||
agentes / ops y ligado al tenant. No es el calendario de Google Ads.
|
publicación pública.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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 {
|
import {
|
||||||
AdDailyRow,
|
AdDailyRow,
|
||||||
KpiWeeklyRow,
|
KpiWeeklyRow,
|
||||||
|
buildChannelSeries,
|
||||||
buildComparisons,
|
buildComparisons,
|
||||||
sumDaily,
|
sumDaily,
|
||||||
sumWeekly,
|
sumWeekly,
|
||||||
@@ -70,6 +71,7 @@ export default async function KpisPage() {
|
|||||||
: sumWeekly(weekly); // fallback: all available weeks if current month empty
|
: sumWeekly(weekly); // fallback: all available weeks if current month empty
|
||||||
const dailyTotals = sumDaily(daily);
|
const dailyTotals = sumDaily(daily);
|
||||||
const sparse = weekly.length < 4;
|
const sparse = weekly.length < 4;
|
||||||
|
const channelSeries = buildChannelSeries(weekly);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MetricsDashboard
|
<MetricsDashboard
|
||||||
@@ -80,6 +82,8 @@ export default async function KpisPage() {
|
|||||||
deltas={comparisons.deltas}
|
deltas={comparisons.deltas}
|
||||||
daily={dailyTotals}
|
daily={dailyTotals}
|
||||||
sparse={sparse}
|
sparse={sparse}
|
||||||
|
weeklyRows={weekly}
|
||||||
|
channelPoints={channelSeries.points}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ type Asset = {
|
|||||||
created_at?: string;
|
created_at?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Dual = {
|
||||||
|
agency: boolean;
|
||||||
|
client: boolean;
|
||||||
|
both: boolean;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
type DriveFile = {
|
type DriveFile = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -39,6 +46,32 @@ function formatBytes(n?: number | null) {
|
|||||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
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) {
|
function iconHint(mime?: string | null) {
|
||||||
if (!mime) return 'FILE';
|
if (!mime) return 'FILE';
|
||||||
if (mime.startsWith('image/')) return 'IMG';
|
if (mime.startsWith('image/')) return 'IMG';
|
||||||
@@ -61,12 +94,30 @@ export default function AssetsLibrary({ tenantLabel }: { tenantLabel: string })
|
|||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
const [err, setErr] = useState<string | null>(null);
|
const [err, setErr] = useState<string | null>(null);
|
||||||
const [drag, setDrag] = useState(false);
|
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 loadPortal = useCallback(async () => {
|
||||||
const res = await fetch('/api/assets');
|
const res = await fetch('/api/assets');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setAssets(data.assets || []);
|
const list: Asset[] = data.assets || [];
|
||||||
|
setAssets(list);
|
||||||
if (data.warning) setWarning(data.warning);
|
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 () => {
|
const loadDrive = useCallback(async () => {
|
||||||
@@ -362,9 +413,34 @@ export default function AssetsLibrary({ tenantLabel }: { tenantLabel: string })
|
|||||||
: ''}
|
: ''}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="hidden sm:inline-flex items-center gap-1 text-[10px] text-emerald-400">
|
<button
|
||||||
<CheckCircle2 className="w-3 h-3" /> Validado
|
type="button"
|
||||||
</span>
|
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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => download(a.id)}
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import React from 'react';
|
'use client';
|
||||||
|
|
||||||
|
import React, { useMemo, useState } from 'react';
|
||||||
|
import Link from 'next/link';
|
||||||
import {
|
import {
|
||||||
ArrowDownRight,
|
ArrowDownRight,
|
||||||
ArrowUpRight,
|
ArrowUpRight,
|
||||||
@@ -9,13 +12,17 @@ import {
|
|||||||
Users,
|
Users,
|
||||||
MousePointerClick,
|
MousePointerClick,
|
||||||
Eye,
|
Eye,
|
||||||
|
CalendarRange,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
|
ChannelWeekPoint,
|
||||||
Delta,
|
Delta,
|
||||||
MetricTotals,
|
MetricTotals,
|
||||||
formatEur,
|
formatEur,
|
||||||
formatNum,
|
formatNum,
|
||||||
formatPct,
|
formatPct,
|
||||||
|
sumWeekly,
|
||||||
|
KpiWeeklyRow,
|
||||||
} from '@/lib/metrics';
|
} from '@/lib/metrics';
|
||||||
|
|
||||||
type Card = {
|
type Card = {
|
||||||
@@ -24,16 +31,12 @@ type Card = {
|
|||||||
hint: string;
|
hint: string;
|
||||||
format: (v: number) => string;
|
format: (v: number) => string;
|
||||||
icon: React.ReactNode;
|
icon: React.ReactNode;
|
||||||
invert?: boolean; // lower is better
|
invert?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function DeltaTriple({
|
type RangeKey = '7d' | '30d' | 'month' | 'all';
|
||||||
delta,
|
|
||||||
invert,
|
function DeltaTriple({ delta, invert }: { delta: Delta; invert?: boolean }) {
|
||||||
}: {
|
|
||||||
delta: Delta;
|
|
||||||
invert?: boolean;
|
|
||||||
}) {
|
|
||||||
const cells: { label: string; v: number | null }[] = [
|
const cells: { label: string; v: number | null }[] = [
|
||||||
{ label: 'WoW', v: delta.wow },
|
{ label: 'WoW', v: delta.wow },
|
||||||
{ label: 'MoM', v: delta.mom },
|
{ label: 'MoM', v: delta.mom },
|
||||||
@@ -43,11 +46,7 @@ function DeltaTriple({
|
|||||||
<div className="mt-3 grid grid-cols-3 gap-1.5">
|
<div className="mt-3 grid grid-cols-3 gap-1.5">
|
||||||
{cells.map((c) => {
|
{cells.map((c) => {
|
||||||
const good =
|
const good =
|
||||||
c.v === null
|
c.v === null ? null : invert ? c.v < 0 : c.v > 0;
|
||||||
? null
|
|
||||||
: invert
|
|
||||||
? c.v < 0
|
|
||||||
: c.v > 0;
|
|
||||||
const color =
|
const color =
|
||||||
c.v === null
|
c.v === null
|
||||||
? 'text-gray-500'
|
? '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({
|
export default function MetricsDashboard({
|
||||||
label,
|
label,
|
||||||
portfolioWide,
|
portfolioWide,
|
||||||
@@ -91,6 +113,8 @@ export default function MetricsDashboard({
|
|||||||
deltas,
|
deltas,
|
||||||
daily,
|
daily,
|
||||||
sparse,
|
sparse,
|
||||||
|
weeklyRows = [],
|
||||||
|
channelPoints = [],
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
portfolioWide: boolean;
|
portfolioWide: boolean;
|
||||||
@@ -104,26 +128,85 @@ export default function MetricsDashboard({
|
|||||||
clicks: number;
|
clicks: number;
|
||||||
};
|
};
|
||||||
sparse: boolean;
|
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[] = [
|
const cards: Card[] = [
|
||||||
{
|
{
|
||||||
key: 'spend',
|
key: 'spend',
|
||||||
label: 'Inversión ads',
|
label: 'Inversión ads',
|
||||||
hint: 'Mes en curso (kpi_weekly)',
|
hint: 'Paid del periodo',
|
||||||
format: formatEur,
|
format: formatEur,
|
||||||
icon: <DollarSign className="w-4 h-4 text-brand-500" />,
|
icon: <DollarSign className="w-4 h-4 text-brand-500" />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'leads',
|
key: 'leads',
|
||||||
label: 'Leads',
|
label: 'Leads',
|
||||||
hint: 'Cohorte · mes',
|
hint: 'Captación periodo',
|
||||||
format: formatNum,
|
format: formatNum,
|
||||||
icon: <Users className="w-4 h-4 text-blue-400" />,
|
icon: <Users className="w-4 h-4 text-blue-400" />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'cpl',
|
key: 'cpl',
|
||||||
label: 'CPL',
|
label: 'CPL',
|
||||||
hint: 'Coste por lead · mes',
|
hint: 'Coste por lead',
|
||||||
format: (v) => `${formatNum(v)} €`,
|
format: (v) => `${formatNum(v)} €`,
|
||||||
icon: <MousePointerClick className="w-4 h-4 text-violet-400" />,
|
icon: <MousePointerClick className="w-4 h-4 text-violet-400" />,
|
||||||
invert: true,
|
invert: true,
|
||||||
@@ -131,7 +214,7 @@ export default function MetricsDashboard({
|
|||||||
{
|
{
|
||||||
key: 'cac',
|
key: 'cac',
|
||||||
label: 'CAC cohorte',
|
label: 'CAC cohorte',
|
||||||
hint: 'Spend / clientes ganados',
|
hint: 'Paid / cierres (parcial v1)',
|
||||||
format: (v) => `${formatNum(v)} €`,
|
format: (v) => `${formatNum(v)} €`,
|
||||||
icon: <Target className="w-4 h-4 text-amber-400" />,
|
icon: <Target className="w-4 h-4 text-amber-400" />,
|
||||||
invert: true,
|
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 className="flex flex-col md:flex-row md:items-end md:justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-2xl font-bold tracking-tight text-white">
|
<h2 className="text-2xl font-bold tracking-tight text-white">
|
||||||
Dashboard de métricas
|
North Star · métricas
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-gray-400 mt-1">
|
<p className="text-sm text-gray-400 mt-1">
|
||||||
{label}
|
{label}
|
||||||
{portfolioWide
|
{portfolioWide
|
||||||
? ' · agrega todos los tenants (vista agencia)'
|
? ' · portafolio'
|
||||||
: ' · zoom al cliente del selector'}
|
: ' · zoom cliente'}
|
||||||
. Comparativas WoW / MoM / YoY sobre <code>kpi_weekly</code>.
|
. Paid unificado ahora; CRM/GEO en siguientes fases.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[11px] text-gray-500 bg-gray-900/50 border border-gray-800 rounded-lg px-3 py-2">
|
<div className="flex items-center gap-2">
|
||||||
Semana actual spend {formatEur(week.spend)} · leads {formatNum(week.leads)}
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{sparse && (
|
{sparse && (
|
||||||
<p className="text-xs text-amber-400/90 border border-amber-500/20 rounded-lg px-3 py-2">
|
<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
|
Histórico limitado: si faltan deltas o canales, el warehouse aún no
|
||||||
pipeline Windsor/n8n o semanas previas / año anterior.
|
tiene semanas suficientes.
|
||||||
</p>
|
</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">
|
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||||
{cards.map((c) => (
|
{cards.map((c) => (
|
||||||
<div
|
<div
|
||||||
@@ -192,7 +328,7 @@ export default function MetricsDashboard({
|
|||||||
{c.icon}
|
{c.icon}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-2xl font-bold text-white">
|
<p className="text-2xl font-bold text-white">
|
||||||
{c.format(month[c.key])}
|
{c.format(periodTotals[c.key])}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-[11px] text-gray-500 mt-1">{c.hint}</p>
|
<p className="text-[11px] text-gray-500 mt-1">{c.hint}</p>
|
||||||
<DeltaTriple delta={deltas[c.key]} invert={c.invert} />
|
<DeltaTriple delta={deltas[c.key]} invert={c.invert} />
|
||||||
@@ -200,41 +336,112 @@ export default function MetricsDashboard({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</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="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5">
|
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5">
|
||||||
<div className="flex items-center justify-between text-gray-400 mb-2">
|
<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" />
|
<Eye className="w-4 h-4 text-sky-400" />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-lg font-bold text-white">
|
<p className="text-lg font-bold text-white">{formatEur(daily.spend)}</p>
|
||||||
{formatEur(daily.spend)}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-500 mt-1">
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
{formatNum(daily.leads)} leads plataforma ·{' '}
|
{formatNum(daily.leads)} leads · {formatNum(daily.impressions)} impr.
|
||||||
{formatNum(daily.impressions)} impr. · {formatNum(daily.clicks)}{' '}
|
· {formatNum(daily.clicks)} clicks
|
||||||
clicks
|
</p>
|
||||||
|
<p className="text-[11px] text-gray-600 mt-2">
|
||||||
|
Semana actual: {formatEur(week.spend)} · {formatNum(week.leads)}{' '}
|
||||||
|
leads
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5 md:col-span-2">
|
<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">
|
<p className="text-xs uppercase tracking-wider text-gray-500 mb-2">
|
||||||
Cómo leer las deltas
|
Cómo leer
|
||||||
</p>
|
</p>
|
||||||
<ul className="text-xs text-gray-400 space-y-1 list-disc list-inside">
|
<ul className="text-xs text-gray-400 space-y-1 list-disc list-inside">
|
||||||
<li>
|
<li>
|
||||||
<strong className="text-gray-300">WoW</strong>: semana actual vs
|
El selector de fechas filtra inversión/leads del periodo; WoW/MoM/YoY
|
||||||
anterior
|
siguen siendo comparativas de calendario.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong className="text-gray-300">MoM</strong>: mes actual vs mes
|
CAC unificado con fee/tools y cierre CRM llega en v2.
|
||||||
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)
|
|
||||||
</li>
|
</li>
|
||||||
|
<li>GEO / LTV aparecen como stubs hasta tener pipeline de datos.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</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