From 0e8befe69add28262b7be28776093194ca19cb68 Mon Sep 17 00:00:00 2001 From: 4Ventures <4ventures@MacBook-Air-de-4Ventures.local> Date: Wed, 14 Oct 2026 13:20:18 +0200 Subject: [PATCH] Show all client RRSS calendars in portfolio and restore Agua Miia October. Agency vista global listed nothing; now cards per followed client. Persist bundled Oct 2026 for Agua Miia when missing so the operative plan is not hidden by a sole November row. Co-authored-by: Cursor --- src/app/dashboard/calendario/page.tsx | 156 +++++++++++++++++--- src/components/CalendarPortfolioBoard.tsx | 169 ++++++++++++++++++++++ 2 files changed, 307 insertions(+), 18 deletions(-) create mode 100644 src/components/CalendarPortfolioBoard.tsx diff --git a/src/app/dashboard/calendario/page.tsx b/src/app/dashboard/calendario/page.tsx index d785915..269c004 100644 --- a/src/app/dashboard/calendario/page.tsx +++ b/src/app/dashboard/calendario/page.tsx @@ -3,10 +3,18 @@ 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 { + isAgencyRole, + serviceHeaders, + supabaseUrl, + userRole, +} from '@/lib/agency'; import RrssMonthView, { RrssMonthPlan, RrssPiece } from '@/components/RrssMonthView'; import CalendarClient from './CalendarClient'; import RrssArchiveYear from '@/components/RrssArchiveYear'; +import CalendarPortfolioBoard, { + type CalendarPortfolioRow, +} from '@/components/CalendarPortfolioBoard'; import octPlan from '@/data/rrss-octubre-2026.json'; import { Instagram, Linkedin } from 'lucide-react'; import { PageHeader } from '@/components/ui'; @@ -17,9 +25,12 @@ import { mergePipelineIntoPlans, type PipelineCalendarRow, } from '@/lib/pipeline-calendar'; +import { asPlanObject } from '@/lib/calendar-documents'; export const dynamic = 'force-dynamic'; +const AGUA_MIIA_OCT_TITLE = `RRSS ${octPlan.label}`; + function asPlan(raw: unknown): RrssMonthPlan | null { if (!raw || typeof raw !== 'object') return null; const o = raw as Record; @@ -34,6 +45,115 @@ function asLegacyPosts(raw: unknown): RrssPiece[] { return []; } +function parseDocContent(content: unknown): unknown { + if (typeof content !== 'string') return content; + try { + return JSON.parse(content); + } catch { + return null; + } +} + +/** Persist bundled Oct 2026 plan for Agua Miia when missing from documents. */ +async function ensureAguaMiiaOctober(tenantId: string): Promise { + const headers = serviceHeaders(); + const base = supabaseUrl(); + if (!headers || !base) return false; + + const tid = encodeURIComponent(tenantId); + const existing = await restGet>( + `/rest/v1/documents?tenant_id=eq.${tid}&type=eq.calendar&select=id,content&order=created_at.desc&limit=50` + ); + const hasOct = (existing.data || []).some((doc) => { + const plan = asPlanObject(doc.content); + return plan && String(plan.month || '') === '2026-10'; + }); + if (hasOct) return false; + + const byTitle = await restGet>( + `/rest/v1/documents?tenant_id=eq.${tid}&type=eq.calendar&title=eq.${encodeURIComponent(AGUA_MIIA_OCT_TITLE)}&select=id&limit=1` + ); + + const payload = { + tenant_id: tenantId, + type: 'calendar', + title: AGUA_MIIA_OCT_TITLE, + content: octPlan, + }; + + if (byTitle.data?.[0]?.id) { + await fetch(`${base}/rest/v1/documents?id=eq.${byTitle.data[0].id}`, { + method: 'PATCH', + headers: { + ...headers, + 'Content-Type': 'application/json', + Prefer: 'return=minimal', + }, + body: JSON.stringify({ content: octPlan, title: AGUA_MIIA_OCT_TITLE }), + }); + } else { + await fetch(`${base}/rest/v1/documents`, { + method: 'POST', + headers: { + ...headers, + 'Content-Type': 'application/json', + Prefer: 'return=minimal', + }, + body: JSON.stringify(payload), + }); + } + return true; +} + +async function loadPortfolioCalendarRows(): Promise { + const tenants = await restGet< + Array<{ + id: string; + name?: string; + slug?: string; + agency_followed?: boolean; + }> + >('/rest/v1/tenants?select=id,name,slug,agency_followed&order=name.asc'); + const followed = (tenants.data || []).filter( + (t) => t.agency_followed !== false + ); + const docs = await restGet< + Array<{ tenant_id: string; title?: string; content?: unknown }> + >( + '/rest/v1/documents?type=eq.calendar&select=tenant_id,title,content&order=created_at.desc&limit=1000' + ); + + const byTenant = new Map< + string, + { months: Set; pieceCount: number } + >(); + for (const doc of docs.data || []) { + const plan = asPlanObject(parseDocContent(doc.content)); + if (!plan) continue; + const month = String(plan.month || '').slice(0, 7); + if (!/^\d{4}-\d{2}$/.test(month)) continue; + const pieces = Array.isArray(plan.pieces) ? plan.pieces.length : 0; + const bucket = byTenant.get(doc.tenant_id) || { + months: new Set(), + pieceCount: 0, + }; + bucket.months.add(month); + bucket.pieceCount += pieces; + byTenant.set(doc.tenant_id, bucket); + } + + return followed.map((t) => { + const bucket = byTenant.get(t.id); + return { + id: t.id, + name: t.name || t.slug || 'Cliente', + slug: t.slug || '', + months: bucket ? [...bucket.months].sort() : [], + pieceCount: bucket?.pieceCount || 0, + }; + }); +} + export default async function CalendarioPage({ searchParams, }: { @@ -50,11 +170,15 @@ export default async function CalendarioPage({ const agency = isAgencyRole(userRole(user)); if (ctx.portfolioWide) { - return ( -

- Selecciona un cliente en Contexto para ver su hub RRSS (privado). -

- ); + if (!agency) { + return ( +

+ Selecciona un cliente en Contexto para ver su hub RRSS (privado). +

+ ); + } + const rows = await loadPortfolioCalendarRows(); + return ; } let tenantSlug: string | null = null; @@ -66,6 +190,10 @@ export default async function CalendarioPage({ } const isAguaMiia = tenantSlug === 'agua-miia'; + if (isAguaMiia && ctx.tenantId && agency) { + await ensureAguaMiiaOctober(ctx.tenantId); + } + let calendarDocs: Array<{ title?: string; content?: unknown }> = []; if (agency && ctx.viaView && ctx.tenantId) { const tid = encodeURIComponent(ctx.tenantId); @@ -85,18 +213,9 @@ export default async function CalendarioPage({ const plans: RrssMonthPlan[] = []; for (const doc of calendarDocs) { - const raw = - typeof doc.content === 'string' - ? (() => { - try { - return JSON.parse(doc.content); - } catch { - return null; - } - })() - : doc.content; - const plan = asPlan(raw); + const plan = asPlan(parseDocContent(doc.content)); if (!plan) continue; + // Skip cross-tenant leak: Agua Miia branded plans must not appear under other clients. const blob = JSON.stringify(plan).toLowerCase(); if (!isAguaMiia && blob.includes('agua miia')) continue; // Normalize platform casing so IG/FB filter matches Drive imports ("Instagram"). @@ -106,7 +225,8 @@ export default async function CalendarioPage({ })); plans.push(plan); } - if (!plans.length && isAguaMiia) { + // Agua Miia: always surface the bundled Oct 2026 operative plan if DB lacks that month. + if (isAguaMiia && !plans.some((p) => p.month === '2026-10')) { plans.push(octPlan as unknown as RrssMonthPlan); } diff --git a/src/components/CalendarPortfolioBoard.tsx b/src/components/CalendarPortfolioBoard.tsx new file mode 100644 index 0000000..393dcac --- /dev/null +++ b/src/components/CalendarPortfolioBoard.tsx @@ -0,0 +1,169 @@ +'use client'; + +import React, { useMemo, useState, useTransition } from 'react'; +import { useRouter } from 'next/navigation'; +import { CalendarDays, Eye, Loader2 } from 'lucide-react'; +import { PageHeader } from '@/components/ui'; + +export type CalendarPortfolioRow = { + id: string; + name: string; + slug: string; + months: string[]; + pieceCount: number; +}; + +function monthLabel(ym: string): string { + const [y, m] = ym.split('-').map(Number); + if (!y || !m) return ym; + const names = [ + 'Ene', + 'Feb', + 'Mar', + 'Abr', + 'May', + 'Jun', + 'Jul', + 'Ago', + 'Sep', + 'Oct', + 'Nov', + 'Dic', + ]; + return `${names[m - 1] || m} ${y}`; +} + +export default function CalendarPortfolioBoard({ + rows, +}: { + rows: CalendarPortfolioRow[]; +}) { + const router = useRouter(); + const [pending, startTransition] = useTransition(); + const [busyId, setBusyId] = useState(null); + const [onlyWithPlans, setOnlyWithPlans] = useState(false); + + const visible = useMemo(() => { + const list = onlyWithPlans ? rows.filter((r) => r.months.length > 0) : rows; + return [...list].sort((a, b) => { + if (b.months.length !== a.months.length) { + return b.months.length - a.months.length; + } + return a.name.localeCompare(b.name, 'es'); + }); + }, [rows, onlyWithPlans]); + + const withPlans = rows.filter((r) => r.months.length > 0).length; + + async function openClient(row: CalendarPortfolioRow) { + setBusyId(row.id); + await fetch('/api/admin/active-tenant', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ tenantId: row.id }), + }); + const latest = [...row.months].sort().at(-1); + const href = latest + ? `/dashboard/calendario?view=archive&month=${latest}` + : '/dashboard/calendario?view=archive'; + startTransition(() => { + router.push(href); + router.refresh(); + }); + } + + return ( +
+ + +
+ +
+ +
+ {visible.map((row) => { + const live = row.months.length > 0; + const monthsSorted = [...row.months].sort(); + const busy = busyId === row.id && pending; + return ( + + ); + })} +
+ + {visible.length === 0 ? ( +

+ Ningún cliente del portafolio tiene calendario con el filtro actual. +

+ ) : null} +
+ ); +}