Paid detailed analyses with per-kind units; example analysis page

- Credits become analysis units (migration 0006): a natal analysis uses
  one 'natal' unit, a synastry analysis one 'synastry' unit. No monthly
  free credits, no model tiers: ANALYSIS_MODEL (default Opus 5.5) writes
  every paid analysis. Admins grant units per kind; the worker refunds
  the right unit on failure.
- Chart page: the detailed analysis card (offer with units left and a
  confirmation, progress while writing, the finished six sections).
- Public /pelda page: a full Opus analysis of a made-up chart, with the
  free summary and a login call to action.
- The worker sends the JSON schema with properties in 'required' order.
  serde_json sorted them, so the title came after ~9000 tokens of text
  and Opus sometimes left it empty (3 failed attempts in a live test);
  with the order fixed the same analysis succeeded at the first try.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-16 17:39:15 +00:00
co-authored by Claude Opus 5.5
parent 450174c273
commit ce3d3804a7
29 changed files with 1309 additions and 349 deletions
@@ -0,0 +1,62 @@
import type { AnalysisContent } from "@/lib/types";
import { Paragraphs, Rich } from "./Rich";
const NATAL_ORDER = ["personality", "emotions", "mind", "love", "work", "growth"];
const SYNASTRY_ORDER = ["attraction", "communication", "emotional_bond", "friction", "long_term"];
/** A finished detailed analysis (natal or synastry). */
export function AnalysisView({ content, kind = "natal" }: { content: AnalysisContent; kind?: "natal" | "synastry" }) {
const order = kind === "synastry" ? SYNASTRY_ORDER : NATAL_ORDER;
const sections = order.map((key) => content.sections?.[key]).filter((s) => s !== undefined);
return (
<article className="analysis">
<header className="analysis-head">
<h2>{content.title}</h2>
{content.summary && (
<p className="analysis-lead">
<Rich text={content.summary} />
</p>
)}
</header>
{sections.map((s, i) => (
<section key={i} className="analysis-section">
<h3>{s.title}</h3>
<Paragraphs text={s.body} />
</section>
))}
<div className="analysis-lists">
{content.strengths && content.strengths.length > 0 && (
<section>
<h3>Erősségek</h3>
<ul>
{content.strengths.map((t, i) => (
<li key={i}>
<Rich text={t} />
</li>
))}
</ul>
</section>
)}
{content.challenges && content.challenges.length > 0 && (
<section>
<h3>Kihívások</h3>
<ul>
{content.challenges.map((t, i) => (
<li key={i}>
<Rich text={t} />
</li>
))}
</ul>
</section>
)}
</div>
{content.advice && (
<section className="analysis-section analysis-advice">
<h3>Útravaló</h3>
<Paragraphs text={content.advice} />
</section>
)}
</article>
);
}
@@ -5,20 +5,11 @@ import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import type { Analysis } from "@/lib/types";
import { Rich } from "./Rich";
const POLL_MS = 3000;
const MAX_POLLS = 60;
/** `**bold**` → <strong>; the rest is plain text. */
function Rich({ text }: { text: string }) {
return (
<>
{text.split(/(\*\*[^*]+\*\*)/g).map((part, i) =>
part.startsWith("**") && part.endsWith("**") ? <strong key={i}>{part.slice(2, -2)}</strong> : part,
)}
</>
);
}
/**
* The free short summary of a chart. The backend queues it when the chart is
* saved; this asks for it (queueing it again if it failed) and polls until the
@@ -0,0 +1,145 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import type { Analysis } from "@/lib/types";
import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000;
const MAX_POLLS = 120; // 10 minutes
/**
* The paid detailed analysis of a chart: offer (with the units left),
* confirmation, progress while the worker writes it, and the finished text.
*/
export function DetailedAnalysis({
chartId,
initial,
left,
}: {
chartId: string;
initial: Analysis | null;
left: number;
}) {
const [analysis, setAnalysis] = useState<Analysis | null>(initial);
const [remaining, setRemaining] = useState(left);
const [confirming, setConfirming] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const waiting = analysis?.status === "pending" || analysis?.status === "running";
useEffect(() => {
if (!waiting || !analysis) return;
let polls = 0;
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
const next = await api<Analysis>(`/analyses/${analysis.id}`);
if (stopped) return;
setAnalysis(next);
if (next.status === "done" || next.status === "failed") return;
} catch {
// try again on the next tick
}
if (++polls < MAX_POLLS) timer = setTimeout(tick, POLL_MS);
};
timer = setTimeout(tick, POLL_MS);
return () => {
stopped = true;
clearTimeout(timer);
};
}, [waiting, analysis]);
async function request() {
setBusy(true);
setError(null);
try {
const next = await api<Analysis>(`/charts/${chartId}/analyses`, { method: "POST" });
setAnalysis(next);
if (next.credits_charged > 0) setRemaining((n) => n - 1);
setConfirming(false);
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}
if (analysis?.status === "done" && analysis.content) {
return (
<section className="card analysis-card" aria-label="Részletes elemzés">
<span className="eyebrow">Részletes elemzés</span>
<AnalysisView content={analysis.content} />
</section>
);
}
return (
<section className="card analysis-card" aria-labelledby="detailed-title" aria-busy={waiting}>
<span className="eyebrow">Részletes elemzés</span>
{waiting ? (
<>
<h2 id="detailed-title">Készül az elemzésed</h2>
<p className="muted" role="status">
A mesterséges intelligencia most írja meg a hat fejezetet a képleted alapján. Ez általában 1–2 perc; nyugodtan
elhagyhatod az oldalt, az elemzés elkészül és itt vár.
</p>
<div className="skeleton" aria-hidden="true">
<span />
<span />
<span />
</div>
</>
) : (
<>
<h2 id="detailed-title">Az egész képleted, fejezetekre bontva</h2>
<p className="muted">
Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési
út. A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
</p>
{analysis?.status === "failed" && (
<p className="msg msg-error" role="alert">
Az előző kérés nem sikerült, az elemzést visszaadtuk a keretedbe. Próbáld újra.
</p>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{remaining > 0 ? (
confirming ? (
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={request} disabled={busy}>
{busy ? "Indítás…" : "Igen, kérem az elemzést"}
</button>
<button type="button" className="btn btn-ghost" onClick={() => setConfirming(false)} disabled={busy}>
Mégse
</button>
<span className="hint">Ez felhasznál 1-et a {remaining} képletelemzésedből.</span>
</div>
) : (
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={() => setConfirming(true)}>
Részletes elemzés kérése
</button>
<span className="hint">Még {remaining} képletelemzésed van.</span>
</div>
)
) : (
<div className="form-actions">
<Link href="/pelda" className="btn">
Példa megtekintése
</Link>
<span className="hint">A részletes elemzés fizetős; a csomagok hamarosan elérhetők.</span>
</div>
)}
</>
)}
</section>
);
}
+27
View File
@@ -0,0 +1,27 @@
/** Model text: `**bold**` becomes <strong>, the rest stays plain text. */
export function Rich({ text }: { text: string }) {
return (
<>
{text.split(/(\*\*[^*]+\*\*)/g).map((part, i) =>
part.startsWith("**") && part.endsWith("**") ? <strong key={i}>{part.slice(2, -2)}</strong> : part,
)}
</>
);
}
/** Paragraphs separated by blank lines. */
export function Paragraphs({ text }: { text: string }) {
return (
<>
{text
.split(/\n\s*\n/)
.map((p) => p.trim())
.filter(Boolean)
.map((p, i) => (
<p key={i}>
<Rich text={p} />
</p>
))}
</>
);
}