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 <cursoragent@cursor.com>
This commit is contained in:
@@ -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<string, unknown>;
|
||||
@@ -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<boolean> {
|
||||
const headers = serviceHeaders();
|
||||
const base = supabaseUrl();
|
||||
if (!headers || !base) return false;
|
||||
|
||||
const tid = encodeURIComponent(tenantId);
|
||||
const existing = await restGet<Array<{ id: string; content?: unknown }>>(
|
||||
`/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<Array<{ id: string }>>(
|
||||
`/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<CalendarPortfolioRow[]> {
|
||||
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<string>; 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<string>(),
|
||||
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,12 +170,16 @@ export default async function CalendarioPage({
|
||||
const agency = isAgencyRole(userRole(user));
|
||||
|
||||
if (ctx.portfolioWide) {
|
||||
if (!agency) {
|
||||
return (
|
||||
<p className="text-sm text-gray-500 border border-gray-200 rounded-xl p-6 bg-white">
|
||||
Selecciona un cliente en Contexto para ver su hub RRSS (privado).
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const rows = await loadPortfolioCalendarRows();
|
||||
return <CalendarPortfolioBoard rows={rows} />;
|
||||
}
|
||||
|
||||
let tenantSlug: string | null = null;
|
||||
if (ctx.tenantId) {
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
169
src/components/CalendarPortfolioBoard.tsx
Normal file
169
src/components/CalendarPortfolioBoard.tsx
Normal file
@@ -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<string | null>(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 (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
eyebrow="RRSS · portafolio"
|
||||
title="Calendarios editoriales"
|
||||
description={`${withPlans} de ${rows.length} clientes con plan RRSS. Elige un cliente para abrir su archivo mensual.`}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-600">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyWithPlans}
|
||||
onChange={(e) => setOnlyWithPlans(e.target.checked)}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
Solo con calendario
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
|
||||
{visible.map((row) => {
|
||||
const live = row.months.length > 0;
|
||||
const monthsSorted = [...row.months].sort();
|
||||
const busy = busyId === row.id && pending;
|
||||
return (
|
||||
<button
|
||||
key={row.id}
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => void openClient(row)}
|
||||
className={`text-left rounded-xl border bg-white p-4 transition-all hover:-translate-y-0.5 hover:border-sky-400/60 ${
|
||||
live
|
||||
? 'border-gray-200 shadow-sm'
|
||||
: 'border-dashed border-gray-200 opacity-80'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="text-[11px] font-bold uppercase tracking-wider text-sky-500">
|
||||
{row.slug}
|
||||
</p>
|
||||
<h3 className="text-base font-bold text-gray-900 truncate mt-0.5">
|
||||
{row.name}
|
||||
</h3>
|
||||
</div>
|
||||
{busy ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin text-sky-500 shrink-0" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{live ? (
|
||||
<>
|
||||
<p className="mt-3 text-xs text-gray-500 inline-flex items-center gap-1.5">
|
||||
<CalendarDays className="w-3.5 h-3.5" />
|
||||
{row.months.length} mes
|
||||
{row.months.length === 1 ? '' : 'es'} · {row.pieceCount}{' '}
|
||||
piezas
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{monthsSorted.slice(-6).map((m) => (
|
||||
<span
|
||||
key={m}
|
||||
className="text-[10px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full bg-sky-50 text-sky-800 border border-sky-100"
|
||||
>
|
||||
{monthLabel(m)}
|
||||
</span>
|
||||
))}
|
||||
{monthsSorted.length > 6 ? (
|
||||
<span className="text-[10px] text-gray-400 self-center">
|
||||
+{monthsSorted.length - 6}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="mt-3 text-xs text-gray-500">
|
||||
Sin plan RRSS todavía · abrir para crear
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<p className="text-sm text-gray-500 border border-gray-200 rounded-xl p-6 bg-white">
|
||||
Ningún cliente del portafolio tiene calendario con el filtro actual.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user