diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
index 9c976db..40da6f7 100644
--- a/.gitea/workflows/ci.yml
+++ b/.gitea/workflows/ci.yml
@@ -59,7 +59,7 @@ jobs:
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
# data (scripts/fetch-deps.sh); their tests run locally.
- name: Test
- run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit
+ run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt
build:
needs: test
diff --git a/Cargo.lock b/Cargo.lock
index db51107..b25cdf5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,6 +17,13 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+[[package]]
+name = "analysis-prompt"
+version = "0.1.0"
+dependencies = [
+ "serde_json",
+]
+
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -156,6 +163,7 @@ dependencies = [
name = "backend"
version = "0.1.0"
dependencies = [
+ "analysis-prompt",
"anyhow",
"argon2",
"axum",
@@ -2856,6 +2864,7 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
name = "worker"
version = "0.1.0"
dependencies = [
+ "analysis-prompt",
"anyhow",
"axum",
"db",
diff --git a/Cargo.toml b/Cargo.toml
index eca0d9f..3d53720 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -7,6 +7,7 @@ members = [
"crates/service-kit",
"crates/db",
"crates/horoscope-client",
+ "crates/analysis-prompt",
"services/horoscope-api",
"services/backend",
"services/worker",
@@ -25,6 +26,7 @@ geo-tz = { path = "crates/geo-tz" }
service-kit = { path = "crates/service-kit" }
db = { path = "crates/db" }
horoscope-client = { path = "crates/horoscope-client" }
+analysis-prompt = { path = "crates/analysis-prompt" }
anyhow = "1"
argon2 = { version = "0.5", features = ["std"] }
diff --git a/crates/analysis-prompt/Cargo.toml b/crates/analysis-prompt/Cargo.toml
new file mode 100644
index 0000000..8126c3f
--- /dev/null
+++ b/crates/analysis-prompt/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "analysis-prompt"
+description = "Prompts and answer schemas of the Sorsfonalak LLM analyses (shared by backend and worker)"
+edition.workspace = true
+version.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[dependencies]
+serde_json.workspace = true
diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs
new file mode 100644
index 0000000..4cbc483
--- /dev/null
+++ b/crates/analysis-prompt/src/lib.rs
@@ -0,0 +1,383 @@
+//! Prompts and output schemas of the analyses (prompt version [`PROMPT_VERSION`]).
+//!
+//! The model answers with one JSON object (OpenRouter structured output);
+//! [`validate`] checks it against the same schema before it is stored.
+//!
+//! The system prompt ([`default_system`]) can be replaced by an admin-edited
+//! text; the user message (chart data, section list) and the schema stay fixed.
+
+use serde_json::{Value, json};
+
+/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
+pub const PROMPT_VERSION: &str = "v2";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ Natal,
+ Synastry,
+ /// A free teaser of a natal chart: a title and a few sentences.
+ Summary,
+}
+
+impl Kind {
+ pub const ALL: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Kind::Natal => "natal",
+ Kind::Synastry => "synastry",
+ Kind::Summary => "summary",
+ }
+ }
+
+ pub fn parse(s: &str) -> Option {
+ match s {
+ "natal" => Some(Kind::Natal),
+ "synastry" => Some(Kind::Synastry),
+ "summary" => Some(Kind::Summary),
+ _ => None,
+ }
+ }
+}
+
+pub struct Prompt {
+ pub system: String,
+ pub user: String,
+ pub schema_name: &'static str,
+ pub schema: Value,
+}
+
+/// (key, what the section covers) in reading order.
+const NATAL_SECTIONS: [(&str, &str); 6] = [
+ ("personality", "Core identity: the Sun, Moon, Ascendant and chart ruler read together"),
+ ("emotions", "Emotional needs, security and inner life (Moon, 4th house, water emphasis)"),
+ ("mind", "Thinking, communication and learning (Mercury, 3rd and 9th houses)"),
+ ("love", "Love, attraction and relationships (Venus, Mars, 5th and 7th houses, Descendant)"),
+ ("work", "Calling, career, money and daily work (MC, 10th, 2nd and 6th houses, Saturn, Jupiter)"),
+ (
+ "growth",
+ "Main inner tensions, life lessons and the path of growth (tight squares and oppositions, Saturn, Chiron, Nodes)",
+ ),
+];
+
+const SYNASTRY_SECTIONS: [(&str, &str); 5] = [
+ ("attraction", "What draws them together: Sun, Moon, Venus, Mars and Ascendant contacts"),
+ ("communication", "How they think and talk together (Mercury contacts, air emphasis, 3rd house overlays)"),
+ ("emotional_bond", "Emotional closeness, safety and care (Moon contacts, 4th and 8th house overlays)"),
+ ("friction", "Where they rub against each other and how to handle it (challenging aspects, Saturn, Pluto, Mars)"),
+ ("long_term", "Long-term potential and shared purpose, including the composite chart"),
+];
+
+fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
+ match kind {
+ Kind::Natal => &NATAL_SECTIONS,
+ Kind::Synastry => &SYNASTRY_SECTIONS,
+ Kind::Summary => &[],
+ }
+}
+
+/// The JSON schema of the answer (strict mode: every property required).
+pub fn schema(kind: Kind) -> Value {
+ if kind == Kind::Summary {
+ return json!({
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["title", "summary"],
+ "properties": {
+ "title": {"type": "string", "description": "Short, evocative title for this chart (at most 6 words)"},
+ "summary": {"type": "string", "description": "3-4 sentences, 60-100 words, one paragraph"}
+ }
+ });
+ }
+ let mut props = serde_json::Map::new();
+ for (key, about) in sections(kind) {
+ props.insert(
+ (*key).into(),
+ json!({
+ "type": "object",
+ "description": about,
+ "additionalProperties": false,
+ "required": ["title", "body"],
+ "properties": {
+ "title": {"type": "string", "description": "Short, specific section title (not just the topic name)"},
+ "body": {"type": "string", "description": "2-4 paragraphs separated by a blank line"}
+ }
+ }),
+ );
+ }
+ let keys: Vec<&str> = sections(kind).iter().map(|(k, _)| *k).collect();
+ json!({
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["title", "summary", "sections", "strengths", "challenges", "advice"],
+ "properties": {
+ "title": {"type": "string", "description": "Short, evocative title for this analysis (at most 8 words)"},
+ "summary": {"type": "string", "description": "3-4 sentence overview"},
+ "sections": {"type": "object", "additionalProperties": false, "required": keys, "properties": props},
+ "strengths": {"type": "array", "items": {"type": "string"}, "description": "3-5 key strengths, one sentence each"},
+ "challenges": {"type": "array", "items": {"type": "string"}, "description": "3-5 key challenges, one sentence each"},
+ "advice": {"type": "string", "description": "A closing, encouraging paragraph with concrete guidance"}
+ }
+ })
+}
+
+const HUNGARIAN_STYLE: &str = "\
+Write natural, idiomatic Hungarian, as a native Hungarian author would; it must not read like a translation from English. \
+Use correct Hungarian suffixes and vowel harmony, Hungarian quotation marks („…”) and the en dash (–). \
+Use the usual Hungarian astrological terms:
+- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
+- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
+Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
+- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció);
+- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
+Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
+- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
+
+fn language_name(language: &str) -> &'static str {
+ match language {
+ "hu" => "Hungarian",
+ _ => "English",
+ }
+}
+
+/// The built-in system prompt of an analysis kind in a language.
+pub fn default_system(kind: Kind, language: &str) -> String {
+ let (role, reader) = match kind {
+ Kind::Natal => (
+ "a personal natal chart interpretation",
+ "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
+ ),
+ Kind::Summary => (
+ "a short free summary of a natal chart (a teaser shown before the detailed, paid analysis)",
+ "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
+ ),
+ Kind::Synastry => (
+ "a relationship (synastry) interpretation for two people",
+ "Write for both people at once, in the informal second person plural (in Hungarian: \"ti\", \"kettőtök\"). \
+ When you must tell them apart, call them Person 1 and Person 2 (in Hungarian: \"az első fél\" and \"a második fél\"). \
+ Do not assume their genders or the type of relationship.",
+ ),
+ };
+ let mut text = format!(
+ "You are an experienced, warm and psychologically minded astrologer. You write {role} for the Sorsfonalak app.
+
+Write in {lang}.
+
+Rules:
+- Base every statement on the chart data given. Never invent positions, aspects or houses that are not listed.
+- When you interpret a placement, name its astrological basis in a short clause, but keep the focus on the person, not on jargon.
+- Synthesize: weave signs, houses, aspects and rulers into one coherent portrait; show how tensions can be integrated. \
+Give the most weight to the Sun, Moon, Ascendant, chart ruler, tight aspects (orb under 3°) and strong emphases or gaps in elements and modalities.
+- If a birth time is unknown, do not mention houses, the Ascendant or the Midheaven for that chart, and be careful with the Moon's sign.
+- {reader}
+- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \
+and no medical, legal or financial advice.
+- Avoid generic horoscope clichés and filler: every paragraph must say something specific to this chart.
+- Texts are plain paragraphs separated by a blank line, without headings or lists inside; **bold** may be used sparingly.
+- {length}
+- Answer with a single JSON object that matches the given schema, and nothing else.",
+ lang = language_name(language),
+ length = match kind {
+ Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
+ (if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
+ a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
+ no sales talk, and do not mention a longer analysis.",
+ _ => "Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.",
+ },
+ );
+ if language == "hu" {
+ text.push_str("\n\n");
+ text.push_str(HUNGARIAN_STYLE);
+ }
+ text
+}
+
+/// Splits a stored prompt version (`v2` or `v2-r`, the id of an admin-edited
+/// system prompt in `prompt_revisions`) into the code version and the revision id.
+pub fn split_version(version: &str) -> (&str, Option) {
+ match version.rsplit_once("-r") {
+ Some((base, id)) => match id.parse() {
+ Ok(id) => (base, Some(id)),
+ Err(_) => (version, None),
+ },
+ None => (version, None),
+ }
+}
+
+/// The built-in text of the user message around the chart data, for showing
+/// next to the editable system prompt (`{chart data}` stands for the data).
+pub fn user_template(kind: Kind) -> String {
+ build(kind, "hu", "{chart data}\n", None).user
+}
+
+/// The prompt for one analysis; `system` replaces [`default_system`].
+pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>) -> Prompt {
+ let mut user = String::from("Chart data:\n\n");
+ user.push_str(chart_text);
+ if kind == Kind::Summary {
+ user.push_str("\nWrite the short summary now.");
+ } else {
+ user.push_str("\nSections to write, in this order:\n");
+ for (key, about) in sections(kind) {
+ user.push_str(&format!("- {key}: {about}\n"));
+ }
+ user.push_str("\nWrite the analysis now.");
+ }
+ Prompt {
+ system: system.map_or_else(|| default_system(kind, language), str::to_owned),
+ user,
+ schema_name: match kind {
+ Kind::Natal => "natal_analysis",
+ Kind::Synastry => "synastry_analysis",
+ Kind::Summary => "chart_summary",
+ },
+ schema: schema(kind),
+ }
+}
+
+/// Checks an answer against our schema subset (objects with required
+/// properties, strings with at least three letters, string arrays with at
+/// least two items). A placeholder such as "x" counts as missing.
+pub fn validate(schema: &Value, value: &Value) -> Result<(), String> {
+ fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> {
+ match schema["type"].as_str() {
+ Some("object") => {
+ let obj = value.as_object().ok_or_else(|| format!("{path}: expected an object"))?;
+ for key in schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+ let child = obj.get(key).ok_or_else(|| format!("{path}.{key}: missing"))?;
+ walk(&schema["properties"][key], child, &format!("{path}.{key}"))?;
+ }
+ Ok(())
+ }
+ Some("array") => {
+ let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?;
+ if items.len() < 2 {
+ return Err(format!("{path}: too few items"));
+ }
+ items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]")))
+ }
+ Some("string") => match value.as_str() {
+ Some(s) if s.chars().filter(|c| c.is_alphabetic()).nth(2).is_some() => Ok(()),
+ _ => Err(format!("{path}: expected a non-empty string")),
+ },
+ _ => Ok(()),
+ }
+ }
+ walk(schema, value, "$")
+}
+
+/// Fixes typography the models often get wrong. In Hungarian, pairs of
+/// straight double quotes become „…” (only when they pair up evenly).
+pub fn polish(language: &str, content: &mut Value) {
+ fn hungarian_quotes(text: &str) -> Option {
+ if !text.contains('"') || !text.matches('"').count().is_multiple_of(2) {
+ return None;
+ }
+ let mut open = true;
+ Some(
+ text.chars()
+ .map(|c| match c {
+ '"' => {
+ let q = if open { '„' } else { '”' };
+ open = !open;
+ q
+ }
+ c => c,
+ })
+ .collect(),
+ )
+ }
+ match content {
+ Value::String(s) if language == "hu" => {
+ if let Some(fixed) = hungarian_quotes(s) {
+ *s = fixed;
+ }
+ }
+ Value::Array(items) => items.iter_mut().for_each(|v| polish(language, v)),
+ Value::Object(map) => map.values_mut().for_each(|v| polish(language, v)),
+ _ => {}
+ }
+}
+
+/// The analysis as Markdown (for reading and comparing outputs).
+pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String {
+ let (strengths, challenges, advice) = if language == "hu" {
+ ("Erősségek", "Kihívások", "Útravaló")
+ } else {
+ ("Strengths", "Challenges", "Advice")
+ };
+ let mut md =
+ format!("# {}\n\n_{}_\n\n", content["title"].as_str().unwrap_or(""), content["summary"].as_str().unwrap_or(""));
+ if kind == Kind::Summary {
+ return md;
+ }
+ for (key, _) in sections(kind) {
+ let s = &content["sections"][*key];
+ md.push_str(&format!("## {}\n\n{}\n\n", s["title"].as_str().unwrap_or(key), s["body"].as_str().unwrap_or("")));
+ }
+ for (title, key) in [(strengths, "strengths"), (challenges, "challenges")] {
+ md.push_str(&format!("## {title}\n\n"));
+ for item in content[key].as_array().into_iter().flatten().filter_map(Value::as_str) {
+ md.push_str(&format!("- {item}\n"));
+ }
+ md.push('\n');
+ }
+ md.push_str(&format!("## {advice}\n\n{}\n", content["advice"].as_str().unwrap_or("")));
+ md
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn summary_prompt_is_short() {
+ let p = build(Kind::Summary, "hu", "SUN: Cancer", None);
+ assert_eq!(p.schema_name, "chart_summary");
+ assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező"));
+ assert!(!p.user.contains("Sections to write"));
+ assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(()));
+ assert!(validate(&p.schema, &json!({"title": "Érzékeny mag"})).is_err());
+ let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."}));
+ assert_eq!(md, "# Cím\n\n_Szöveg._\n\n");
+ }
+
+ #[test]
+ fn custom_system_replaces_only_the_rules() {
+ let p = build(Kind::Natal, "hu", "SUN: Cancer", Some("Saját szabályok."));
+ assert_eq!(p.system, "Saját szabályok.");
+ assert!(p.user.contains("SUN: Cancer") && p.user.contains("- personality:"));
+ assert_eq!(p.schema, schema(Kind::Natal));
+ assert!(user_template(Kind::Natal).contains("{chart data}"));
+ assert_eq!(split_version("v2-r12"), ("v2", Some(12)));
+ assert_eq!(split_version("v2"), ("v2", None));
+ assert!(Kind::ALL.iter().all(|k| Kind::parse(k.as_str()) == Some(*k)));
+ }
+
+ #[test]
+ fn validate_rejects_placeholder_titles() {
+ let schema = schema(Kind::Synastry);
+ let section = json!({"title": "Rák-szívek", "body": "Két bekezdés szöveg."});
+ let mut answer = json!({
+ "title": "Két Rák-szív", "summary": "Összefoglaló.", "advice": "Útravaló.",
+ "strengths": ["Egyik erősség.", "Másik erősség."], "challenges": ["Egy kihívás.", "Még egy."],
+ "sections": {"attraction": section, "communication": section, "emotional_bond": section,
+ "friction": section, "long_term": section},
+ });
+ assert_eq!(validate(&schema, &answer), Ok(()));
+ answer["sections"]["attraction"]["title"] = json!("x");
+ assert_eq!(validate(&schema, &answer), Err("$.sections.attraction.title: expected a non-empty string".into()));
+ }
+
+ #[test]
+ fn polish_turns_straight_quotes_hungarian() {
+ let mut v = json!({"a": "a \"hazai pálya\" és a \"sorok\"", "b": ["egy \" pár nélkül"], "c": {"d": "nincs"}});
+ polish("hu", &mut v);
+ assert_eq!(v["a"], "a „hazai pálya” és a „sorok”");
+ assert_eq!(v["b"][0], "egy \" pár nélkül");
+ assert_eq!(v["c"]["d"], "nincs");
+ let mut en = json!({"a": "the \"home\" ground"});
+ polish("en", &mut en);
+ assert_eq!(en["a"], "the \"home\" ground");
+ }
+}
diff --git a/crates/db/migrations/0009_prompt_revisions.sql b/crates/db/migrations/0009_prompt_revisions.sql
new file mode 100644
index 0000000..d0505fe
--- /dev/null
+++ b/crates/db/migrations/0009_prompt_revisions.sql
@@ -0,0 +1,14 @@
+-- Admin-edited system prompts of the analyses. The newest row of a
+-- (kind, language) is in force; system NULL means the built-in default.
+-- An analysis records the revision it was written with in prompt_version
+-- ("v2-r"), so the worker uses exactly that text.
+CREATE TABLE prompt_revisions (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ kind text NOT NULL CHECK (kind IN ('summary', 'natal', 'synastry')),
+ language text NOT NULL,
+ system text CHECK (system IS NULL OR length(system) BETWEEN 1 AND 50000),
+ created_by uuid REFERENCES users ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX prompt_revisions_current ON prompt_revisions (kind, language, id DESC);
diff --git a/crates/db/migrations/0010_prompt_previews.sql b/crates/db/migrations/0010_prompt_previews.sql
new file mode 100644
index 0000000..d34e02d
--- /dev/null
+++ b/crates/db/migrations/0010_prompt_previews.sql
@@ -0,0 +1,29 @@
+-- Test runs of an edited (not yet saved) system prompt on one of the admin's
+-- charts. Kept apart from analyses: never shown to users, never cached, no
+-- credits, one attempt. Removed after 30 days by the cleanup job.
+CREATE TABLE prompt_previews (
+ id uuid PRIMARY KEY,
+ kind text NOT NULL CHECK (kind IN ('summary', 'natal')),
+ chart_id uuid NOT NULL REFERENCES charts ON DELETE CASCADE,
+ language text NOT NULL,
+ model text NOT NULL,
+ system text NOT NULL CHECK (length(system) BETWEEN 1 AND 50000),
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')),
+ content jsonb,
+ error text,
+ model_used text,
+ input_tokens integer,
+ output_tokens integer,
+ cost_usd double precision,
+ created_by uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ started_at timestamptz,
+ completed_at timestamptz
+);
+
+CREATE INDEX prompt_previews_pending_idx ON prompt_previews (created_at) WHERE status = 'pending';
+
+-- Wakes the analysis worker, like a new analysis.
+CREATE TRIGGER prompt_previews_notify
+ AFTER INSERT ON prompt_previews
+ FOR EACH STATEMENT EXECUTE FUNCTION notify_analyses();
diff --git a/crates/db/migrations/0011_synastry_previews.sql b/crates/db/migrations/0011_synastry_previews.sql
new file mode 100644
index 0000000..93a00ee
--- /dev/null
+++ b/crates/db/migrations/0011_synastry_previews.sql
@@ -0,0 +1,10 @@
+-- Prompt test runs of the relationship (synastry) analysis: on one of the
+-- admin's comparisons instead of a chart.
+ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_kind_check;
+ALTER TABLE prompt_previews ALTER COLUMN chart_id DROP NOT NULL;
+ALTER TABLE prompt_previews
+ ADD COLUMN synastry_id uuid REFERENCES synastries ON DELETE CASCADE,
+ ADD CONSTRAINT prompt_previews_target CHECK (
+ (kind IN ('summary', 'natal') AND chart_id IS NOT NULL AND synastry_id IS NULL)
+ OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
+ );
diff --git a/crates/db/migrations/0012_packages.sql b/crates/db/migrations/0012_packages.sql
new file mode 100644
index 0000000..cecd653
--- /dev/null
+++ b/crates/db/migrations/0012_packages.sql
@@ -0,0 +1,26 @@
+-- Packages: every purchase or admin grant of a package is an order; the units
+-- it gives are credit_ledger rows pointing at it (reason 'package'), and the
+-- unlimited package is a time-limited 'unlimited' entitlement.
+CREATE TABLE package_orders (
+ id uuid PRIMARY KEY,
+ user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
+ package text NOT NULL,
+ source text NOT NULL CHECK (source IN ('admin', 'mock', 'stripe')),
+ price_huf integer NOT NULL DEFAULT 0 CHECK (price_huf >= 0),
+ note text,
+ created_by uuid REFERENCES users ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX package_orders_user_idx ON package_orders (user_id, created_at DESC);
+
+ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_reason_check;
+ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_reason_check
+ CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase', 'person', 'package'));
+ALTER TABLE credit_ledger ADD COLUMN order_id uuid REFERENCES package_orders ON DELETE SET NULL;
+
+-- 'unlimited': analyses and persons without limit until expires_at.
+ALTER TABLE entitlements DROP CONSTRAINT entitlements_entitlement_check;
+ALTER TABLE entitlements ADD CONSTRAINT entitlements_entitlement_check
+ CHECK (entitlement IN ('unlimited_persons', 'unlimited'));
+ALTER TABLE entitlements ADD COLUMN expires_at timestamptz;
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 393d7aa..040a095 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -88,7 +88,7 @@ services:
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
- PERSON_PACK_SIZE: ${PERSON_PACK_SIZE:-5}
+ UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5}
depends_on:
postgres:
condition: service_healthy
diff --git a/docker-compose.yml b/docker-compose.yml
index 3136b2b..fb9d433 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -56,7 +56,7 @@ services:
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
- PERSON_PACK_SIZE: ${PERSON_PACK_SIZE:-5}
+ UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5}
depends_on:
postgres:
condition: service_healthy
diff --git a/docs/csomagok.md b/docs/csomagok.md
new file mode 100644
index 0000000..ce02437
--- /dev/null
+++ b/docs/csomagok.md
@@ -0,0 +1,39 @@
+# Csomagok és árazás
+
+A katalógus a kódban van: `services/backend/src/packages.rs` (`CATALOG`). Ár- vagy tartalomváltozás egy deploy.
+
+## Költség
+
+Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 80 Ft)** Opus 5.5-tel; a rövid összefoglaló kb. $0,01. A fizetési szolgáltató díja kb. 1,5% + 85 Ft tranzakciónként. Az árak bruttók (27% áfa).
+
+## A lépcső
+
+| Csomag | Tartalom | Ár | Elemzésenként | Külön megvéve | Megtakarítás |
+|---|---|---|---|---|---|
+| Egy elemzés | 1 képletelemzés | 2 990 Ft | 2 990 Ft | – | – |
+| Páros | 2 képletelemzés, 1 kapcsolati, 1 személy | 6 990 Ft | 2 330 Ft | 9 868 Ft | 29% |
+| **Család** (Legnépszerűbb) | 6 képletelemzés, 5 kapcsolati, 5 személy | 11 990 Ft | 1 090 Ft | 37 380 Ft | 68% |
+| Korlátlan | minden korlátlanul, 12 hónapig | 17 990 Ft | – | – | – |
+| +1 kapcsolati elemzés | kiegészítő | 3 490 Ft | | | |
+| +5 személy | kiegészítő | 1 990 Ft | | | |
+
+## Miért így (a nagyobb felé terelés)
+
+- **Horgony:** az Egy elemzés ára (2 990 Ft) az egységár. Minden más ehhez mérve látszik olcsónak; a kártyákon áthúzva ott a „külön megvéve” ár.
+- **Kis lépések, nagy ugrások:** minden szint csak egy kicsivel drágább az előzőnél, de sokkal többet ad. Páros: +4 000 Ft-ért háromszor annyi elemzés. Család: +5 000 Ft-ért majdnem négyszer annyi. Korlátlan: +6 000 Ft-ért nincs határ. A kártyán ki is írjuk: „Csak +5 000 Ft a Páros csomaghoz képest”.
+- **Csali:** a Páros szándékosan „csak jó” ajánlat (−29%), hogy mellette a Család (−68%) kiugorjon. A Család kapja a kiemelést és a „Legnépszerűbb” címkét.
+- **A Korlátlan mint felső horgony:** a Család ára mellette mérsékeltnek tűnik; aki sokakat venne fel, annak a 6 000 Ft különbség semmiség.
+- **Drága kiegészítők:** a +1 kapcsolati elemzés 3 490 Ft, többe kerül, mint egy képletelemzés, és a Páros már kettő árán ad egyet kettőtök képletével együtt. Aki darabonként venne, annak jobban megéri csomagot venni.
+- **A vásárlás pillanatában** (a „Részletes elemzés kérése” után) nem egy darabot kínálunk, hanem három csomagot egymás mellett, kiemelt Családdal.
+- **Nem jár le:** a megvett elemzések megmaradnak, ezért a nagyobb csomag nem kockázat a vevőnek.
+
+## Korlátlan csomag
+
+Egy év; ha még tart, egy újabb a lejárathoz ad hozzá egy évet. Méltányos használat: naponta legfeljebb `UNLIMITED_DAILY_LIMIT` (alapból 5) új részletes elemzés. Legrosszabb esetben is jóval a csomag ára alatt marad a költség, ha valaki nem visszaélésszerűen használja; a napi korlát a gépi tömeges lekérést fogja meg.
+
+## Későbbre
+
+- Stripe-bekötés: a `package_orders.source = 'stripe'` már helyet kapott.
+- Bevezető kedvezmény vagy kupon (pl. az első 100 vásárlónak).
+- Ajándékba adható csomag (karácsony, Valentin-nap): a Páros és a Család jó ajándék.
+- Számlázás (NAV Online Számla) a vásárlásokhoz.
diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml
index c568fa3..4ba6e9f 100644
--- a/services/backend/Cargo.toml
+++ b/services/backend/Cargo.toml
@@ -8,6 +8,7 @@ publish.workspace = true
[dependencies]
db.workspace = true
+analysis-prompt.workspace = true
horoscope-client.workspace = true
service-kit.workspace = true
anyhow.workspace = true
diff --git a/services/backend/README.md b/services/backend/README.md
index 30b7363..5970d43 100644
--- a/services/backend/README.md
+++ b/services/backend/README.md
@@ -14,9 +14,9 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `COOKIE_DOMAIN` | – | pl. `.sorsfonalak.hu`, ha a frontend és az API más aldomainen fut |
| `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama |
| `PASSWORD_LOGIN` | `false` | e-mail + jelszó regisztráció és belépés; élesben ki van kapcsolva (csak Google, Apple, Facebook), a jelszavas végpontok ilyenkor 403-at adnak |
-| `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` azonnal jóváír egy elemzési egységet (`{"unit": "natal"}`) vagy személycsomagot (`{"package": "persons"}` / `"persons_unlimited"`); a compose-fájlokban egyelőre `true` |
+| `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` `{"package": ""}` azonnal jóváírja a katalógus egy csomagját (`{"unit": "natal"}` rövidítés: a legkisebb ilyen csomag); a compose-fájlokban egyelőre `true` |
| `FREE_PERSON_SLOTS` | `0` | ennyi személyt vehet fel csomag nélkül egy felhasználó |
-| `PERSON_PACK_SIZE` | `5` | ennyi személy van egy személycsomagban |
+| `UNLIMITED_DAILY_LIMIT` | `5` | a Korlátlan csomaggal naponta ennyi új részletes elemzés kérhető (méltányos használat; utána 429 `fair_use_limit`) |
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
@@ -48,6 +48,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| Végpont | Guard | Leírás |
|---|---|---|
| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, nyelvek, elemző és összefoglaló modell |
+| `GET /v1/packages` | – | a csomagkatalógus árral, tartalommal, megtakarítással, elemzésenkénti árral (lásd `docs/csomagok.md`) |
| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?}` → munkamenet; megerősítő e-mailt küld |
| `POST /v1/auth/login` | – | `{email, password}` |
| `POST /v1/auth/google` | – | `{id_token}`; `created: true`, ha most jött létre a fiók |
@@ -76,7 +77,12 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
| `GET /v1/public/shares/{slug}` | – | a megosztott tartalom (oldal + OG-kép adatai) |
| `GET /v1/admin/users?q=` | admin | felhasználók kereséssel, szerepekkel, megmaradt elemzésekkel |
| `PATCH /v1/admin/users/{id}` | admin | `{roles: [...]}`; a saját admin szerep nem vehető el |
+| `POST /v1/admin/users/{id}/packages` | admin | `{package, note?}`: csomag kiosztása ajándékként (`package_orders`, ár 0) |
| `POST /v1/admin/users/{id}/credits` | admin | `{unit: natal\|synastry, delta, note?}`: elemzések jóváírása vagy levonása |
+| `GET /v1/admin/prompts` | admin | a tömör és a részletes elemzés system promptja nyelvenként: érvényes szöveg, alapértelmezett, változatok |
+| `PUT /v1/admin/prompts/{kind}/{language}` | admin | `{system}` új változatként menti (`null` vagy az alapértelmezett szöveg: vissza a beépítettre); az új elemzések `prompt_version`-je `v2-r` |
+| `POST /v1/admin/prompts/{kind}/{language}/preview` | admin | `{system, chart_id}`: próbafuttatás a (mentetlen) szöveggel egy saját képleten; nem kerül a képlethez, nem gyorsítótárazott, nem fogy egység; egyszerre legfeljebb 3 |
+| `GET /v1/admin/previews/{id}` | admin | a próbafuttatás állapota és eredménye (modell, token, költség) |
Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái (például ismeretlen hely, javaslatokkal együtt) változatlanul jönnek tovább a horoscope-api-ból.
@@ -118,5 +124,5 @@ A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket
## Korlátok
- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
-- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Egységet a személycsomag ad (`PERSON_PACK_SIZE` darab), a korlátlan csomag az `entitlements` tábla `unlimited_persons` sora. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`; részletes elemzés vagy szinasztria után sem. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
+- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
- **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység).
diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs
index 96536ea..12211c7 100644
--- a/services/backend/src/config.rs
+++ b/services/backend/src/config.rs
@@ -49,8 +49,8 @@ pub struct Config {
pub max_charts_per_user: i64,
/// `FREE_PERSON_SLOTS` (default 0): persons a user may add without a package.
pub free_person_slots: i64,
- /// `PERSON_PACK_SIZE` (default 5): persons in one person package.
- pub person_pack_size: i64,
+ /// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package.
+ pub unlimited_daily_limit: i64,
}
fn var(name: &str) -> Option {
@@ -105,7 +105,7 @@ impl Config {
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
- person_pack_size: parsed("PERSON_PACK_SIZE", 5)?,
+ unlimited_daily_limit: parsed("UNLIMITED_DAILY_LIMIT", 5)?,
};
if config.session_ttl_days < 1 {
bail!("SESSION_TTL_DAYS must be at least 1");
@@ -135,7 +135,7 @@ impl Config {
prompt_version: "v1".into(),
max_charts_per_user: 50,
free_person_slots: 5,
- person_pack_size: 5,
+ unlimited_daily_limit: 3,
}
}
}
diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs
index dc2f9ec..8f45927 100644
--- a/services/backend/src/main.rs
+++ b/services/backend/src/main.rs
@@ -13,6 +13,7 @@ mod config;
mod credits;
mod error;
mod google;
+mod packages;
mod persons;
mod routes;
#[cfg(test)]
diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs
new file mode 100644
index 0000000..9d6ffe2
--- /dev/null
+++ b/services/backend/src/packages.rs
@@ -0,0 +1,285 @@
+//! Packages: what a user can buy (or an admin can give). The catalog is
+//! fixed here; see `docs/csomagok.md` for the reasoning behind it.
+//!
+//! A package gives analysis units and person slots (`credit_ledger` rows
+//! with reason `package`) that never expire, or a time-limited `unlimited`
+//! entitlement: analyses and persons without limit, with a daily fair-use cap.
+
+use serde_json::{Value, json};
+use sqlx::PgConnection;
+use time::OffsetDateTime;
+use uuid::Uuid;
+
+use crate::credits::Unit;
+use crate::error::ApiError;
+
+/// List prices of the single items, for showing what a package saves.
+const NATAL_PRICE: i64 = 2_990;
+const SYNASTRY_PRICE: i64 = 3_490;
+const PERSON_PRICE: i64 = 398; // 1 990 Ft for five
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Tier {
+ /// The main ladder, shown side by side.
+ Main,
+ /// Top-ups for those who already have something.
+ Addon,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct Package {
+ pub id: &'static str,
+ pub name: &'static str,
+ pub tagline: &'static str,
+ pub tier: Tier,
+ /// Gross price (27% VAT included).
+ pub price_huf: i64,
+ pub natal: i64,
+ pub synastry: i64,
+ pub persons: i64,
+ /// Months of unlimited analyses and persons.
+ pub unlimited_months: Option,
+ /// Badge on the card ("Legnépszerűbb").
+ pub badge: Option<&'static str>,
+}
+
+pub const CATALOG: [Package; 6] = [
+ Package {
+ id: "single",
+ name: "Egy elemzés",
+ tagline: "Egy részletes képletelemzés: neked vagy egy felvett személynek.",
+ tier: Tier::Main,
+ price_huf: 2_990,
+ natal: 1,
+ synastry: 0,
+ persons: 0,
+ unlimited_months: None,
+ badge: None,
+ },
+ Package {
+ id: "couple",
+ name: "Páros",
+ tagline: "Te és ő: mindkettőtök képlete és a kapcsolati elemzés.",
+ tier: Tier::Main,
+ price_huf: 6_990,
+ natal: 2,
+ synastry: 1,
+ persons: 1,
+ unlimited_months: None,
+ badge: None,
+ },
+ Package {
+ id: "family",
+ name: "Család",
+ tagline: "Az egész család: öt személy, mindenki képlete, és öt kapcsolat.",
+ tier: Tier::Main,
+ price_huf: 11_990,
+ natal: 6,
+ synastry: 5,
+ persons: 5,
+ unlimited_months: None,
+ badge: Some("Legnépszerűbb"),
+ },
+ Package {
+ id: "unlimited",
+ name: "Korlátlan",
+ tagline: "Egy évig bárki, bármennyi elemzés és összevetés.",
+ tier: Tier::Main,
+ price_huf: 17_990,
+ natal: 0,
+ synastry: 0,
+ persons: 0,
+ unlimited_months: Some(12),
+ badge: None,
+ },
+ Package {
+ id: "addon_synastry",
+ name: "+1 kapcsolati elemzés",
+ tagline: "Egy újabb összevetés részletes elemzése.",
+ tier: Tier::Addon,
+ price_huf: 3_490,
+ natal: 0,
+ synastry: 1,
+ persons: 0,
+ unlimited_months: None,
+ badge: None,
+ },
+ Package {
+ id: "addon_persons",
+ name: "+5 személy",
+ tagline: "Még öt ember képlete (az elemzés külön jár).",
+ tier: Tier::Addon,
+ price_huf: 1_990,
+ natal: 0,
+ synastry: 0,
+ persons: 5,
+ unlimited_months: None,
+ badge: None,
+ },
+];
+
+pub fn find(id: &str) -> Option<&'static Package> {
+ CATALOG.iter().find(|p| p.id == id)
+}
+
+impl Package {
+ /// What the contents would cost one by one (`None` for the unlimited one).
+ fn list_price(&self) -> Option {
+ self.unlimited_months
+ .is_none()
+ .then(|| self.natal * NATAL_PRICE + self.synastry * SYNASTRY_PRICE + self.persons * PERSON_PRICE)
+ }
+
+ pub fn view(&self) -> Value {
+ let analyses = self.natal + self.synastry;
+ let savings = self
+ .list_price()
+ .filter(|&list| list > self.price_huf)
+ .map(|list| ((list - self.price_huf) * 100 + list / 2) / list);
+ json!({
+ "id": self.id,
+ "name": self.name,
+ "tagline": self.tagline,
+ "tier": match self.tier { Tier::Main => "main", Tier::Addon => "addon" },
+ "price_huf": self.price_huf,
+ "natal": self.natal,
+ "synastry": self.synastry,
+ "persons": self.persons,
+ "unlimited_months": self.unlimited_months,
+ "badge": self.badge,
+ "list_price_huf": self.list_price(),
+ "savings_percent": savings,
+ "per_analysis_huf": (analyses > 0).then(|| (self.price_huf + analyses / 2) / analyses),
+ })
+ }
+}
+
+/// Who gives the package.
+#[derive(Debug, Clone, Copy)]
+pub enum Source {
+ Admin,
+ Mock,
+}
+
+impl Source {
+ fn as_str(self) -> &'static str {
+ match self {
+ Source::Admin => "admin",
+ Source::Mock => "mock",
+ }
+ }
+}
+
+/// Records an order and gives its contents, inside the caller's transaction.
+pub async fn grant(
+ tx: &mut PgConnection,
+ user_id: Uuid,
+ package: &Package,
+ source: Source,
+ created_by: Option,
+ note: Option<&str>,
+) -> Result {
+ let order = Uuid::now_v7();
+ let price = match source {
+ Source::Admin => 0,
+ Source::Mock => package.price_huf,
+ };
+ sqlx::query(
+ "INSERT INTO package_orders (id, user_id, package, source, price_huf, note, created_by) \
+ VALUES ($1, $2, $3, $4, $5, $6, $7)",
+ )
+ .bind(order)
+ .bind(user_id)
+ .bind(package.id)
+ .bind(source.as_str())
+ .bind(price as i32)
+ .bind(note)
+ .bind(created_by)
+ .execute(&mut *tx)
+ .await?;
+ for (unit, n) in [(Unit::Natal, package.natal), (Unit::Synastry, package.synastry), (Unit::Person, package.persons)]
+ {
+ if n == 0 {
+ continue;
+ }
+ sqlx::query(
+ "INSERT INTO credit_ledger (id, user_id, unit, delta, reason, order_id, note, created_by) \
+ VALUES ($1, $2, $3, $4, 'package', $5, $6, $7)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(user_id)
+ .bind(unit.as_str())
+ .bind(n as i32)
+ .bind(order)
+ .bind(package.name)
+ .bind(created_by)
+ .execute(&mut *tx)
+ .await?;
+ }
+ if let Some(months) = package.unlimited_months {
+ // Buying again extends from the current end, not from today.
+ sqlx::query(
+ "INSERT INTO entitlements (user_id, entitlement, note, created_by, expires_at) \
+ VALUES ($1, 'unlimited', $2, $3, now() + make_interval(months => $4)) \
+ ON CONFLICT (user_id, entitlement) DO UPDATE SET \
+ expires_at = greatest(entitlements.expires_at, now()) + make_interval(months => $4), \
+ note = EXCLUDED.note, created_by = EXCLUDED.created_by",
+ )
+ .bind(user_id)
+ .bind(package.name)
+ .bind(created_by)
+ .bind(months as i32)
+ .execute(&mut *tx)
+ .await?;
+ }
+ Ok(order)
+}
+
+/// Until when the user's unlimited package runs (`None`: none, or it ended).
+pub async fn unlimited_until(conn: &mut PgConnection, user_id: Uuid) -> Result, ApiError> {
+ let until: Option = sqlx::query_scalar(
+ "SELECT expires_at FROM entitlements \
+ WHERE user_id = $1 AND entitlement = 'unlimited' AND expires_at > now()",
+ )
+ .bind(user_id)
+ .fetch_optional(conn)
+ .await?
+ .flatten();
+ Ok(until)
+}
+
+/// The fair-use cap of the unlimited package: new detailed analyses in 24 hours.
+pub async fn check_fair_use(conn: &mut PgConnection, user_id: Uuid, daily_limit: i64) -> Result<(), ApiError> {
+ let (count,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM analyses WHERE requested_by = $1 AND kind IN ('natal', 'synastry') \
+ AND created_at > now() - interval '24 hours'",
+ )
+ .bind(user_id)
+ .fetch_one(conn)
+ .await?;
+ if count >= daily_limit {
+ return Err(ApiError::Limited {
+ code: "fair_use_limit",
+ message: format!(
+ "A korlátlan csomaggal naponta legfeljebb {daily_limit} új részletes elemzés kérhető. Holnap folytathatod."
+ ),
+ });
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bigger_packages_are_cheaper_per_analysis() {
+ let per = |id: &str| find(id).unwrap().view()["per_analysis_huf"].as_i64().unwrap();
+ assert!(per("single") > per("couple") && per("couple") > per("family"));
+ assert_eq!(find("family").unwrap().view()["savings_percent"], 68);
+ assert_eq!(find("couple").unwrap().view()["savings_percent"], 29);
+ assert!(find("single").unwrap().view()["savings_percent"].is_null());
+ assert!(find("unlimited").unwrap().view()["list_price_huf"].is_null());
+ assert!(CATALOG.iter().all(|p| find(p.id).is_some()));
+ }
+}
diff --git a/services/backend/src/persons.rs b/services/backend/src/persons.rs
index 5ba6228..b17123a 100644
--- a/services/backend/src/persons.rs
+++ b/services/backend/src/persons.rs
@@ -1,7 +1,7 @@
//! Persons: charts of other people (name and birth data) a user adds next to
//! their own. Each new person uses one `person` unit, bought in packages;
-//! deleting a person does not give it back. An unlimited package
-//! (`unlimited_persons` entitlement) and admins have no limit.
+//! deleting a person does not give it back. The `unlimited_persons`
+//! entitlement, a running unlimited package and admins have no limit.
//!
//! A person's birth data can be corrected within an hour of adding them,
//! then it is locked (admins: any time).
@@ -53,7 +53,8 @@ pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Resul
(SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \
WHERE user_id = $1 AND unit = 'person' AND reason <> 'person'), \
- EXISTS (SELECT 1 FROM entitlements WHERE user_id = $1 AND entitlement = 'unlimited_persons')",
+ EXISTS (SELECT 1 FROM entitlements WHERE user_id = $1 \
+ AND (entitlement = 'unlimited_persons' OR (entitlement = 'unlimited' AND expires_at > now())))",
)
.bind(auth.id())
.fetch_one(conn)
diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs
index 286fef8..5f74b32 100644
--- a/services/backend/src/routes/account.rs
+++ b/services/backend/src/routes/account.rs
@@ -32,6 +32,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> {
let balance = credits::balance(&mut conn, auth.id()).await?;
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
+ let unlimited = crate::packages::unlimited_until(&mut conn, auth.id()).await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::>(),
@@ -39,6 +40,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> {
"analyses_left": balance.view(),
"birth_change": birth_change,
"persons": persons.view(),
+ "unlimited_until": rfc3339_opt(unlimited),
})))
}
diff --git a/services/backend/src/routes/admin.rs b/services/backend/src/routes/admin.rs
index e40b16c..0b58450 100644
--- a/services/backend/src/routes/admin.rs
+++ b/services/backend/src/routes/admin.rs
@@ -14,6 +14,7 @@ use super::{Body, IdPath, St};
use crate::auth::AdminUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
+use crate::packages::{self, Source};
use crate::views::{rfc3339, rfc3339_opt};
#[derive(Deserialize)]
@@ -32,12 +33,26 @@ pub async fn list_users(
let limit = query.limit.unwrap_or(50).clamp(1, 200);
let offset = query.offset.unwrap_or(0).max(0);
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
- type Row = (Uuid, String, Option, Vec, bool, OffsetDateTime, Option, i64, i64, i64);
+ type Row = (
+ Uuid,
+ String,
+ Option,
+ Vec,
+ bool,
+ OffsetDateTime,
+ Option,
+ i64,
+ i64,
+ i64,
+ Option,
+ );
let rows: Vec = sqlx::query_as(
"SELECT u.id, u.email, u.display_name, u.roles, u.email_verified_at IS NOT NULL, u.created_at, u.last_login_at, \
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'natal'), \
- (SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'synastry') \
+ (SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'synastry'), \
+ (SELECT e.expires_at FROM entitlements e \
+ WHERE e.user_id = u.id AND e.entitlement = 'unlimited' AND e.expires_at > now()) \
FROM users u \
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
@@ -49,11 +64,12 @@ pub async fn list_users(
.await?;
let users: Vec = rows
.into_iter()
- .map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry)| {
+ .map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, unlimited)| {
json!({
"id": id, "email": email, "display_name": name, "roles": roles, "email_verified": verified,
"created_at": rfc3339(created), "last_login_at": rfc3339_opt(last_login),
"charts": charts, "analyses_left": {"natal": natal, "synastry": synastry},
+ "unlimited_until": rfc3339_opt(unlimited),
})
})
.collect();
@@ -128,3 +144,37 @@ pub async fn adjust_credits(
let balance = credits::balance(&mut *state.db.acquire().await?, id).await?;
Ok((StatusCode::CREATED, Json(json!({ "user_id": id, "analyses_left": balance.view() }))))
}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GrantPackage {
+ package: String,
+ note: Option,
+}
+
+/// Gives a user a package from the catalog (a gift: no payment, price 0).
+pub async fn grant_package(
+ State(state): St,
+ AdminUser(admin): AdminUser,
+ WithRejection(Path(id), _): IdPath,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult<(StatusCode, Json)> {
+ let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
+ let exists: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM users WHERE id = $1").bind(id).fetch_optional(&state.db).await?;
+ exists.ok_or(ApiError::NotFound("user"))?;
+ let note = req.note.map(|n| n.trim().chars().take(500).collect::()).filter(|n| !n.is_empty());
+ let mut tx = state.db.begin().await?;
+ let order = packages::grant(&mut tx, id, package, Source::Admin, Some(admin.id()), note.as_deref()).await?;
+ let balance = credits::balance(&mut tx, id).await?;
+ let unlimited = packages::unlimited_until(&mut tx, id).await?;
+ tx.commit().await?;
+ tracing::info!(admin = %admin.id(), user = %id, package = package.id, "package granted");
+ Ok((
+ StatusCode::CREATED,
+ Json(json!({
+ "order_id": order, "user_id": id, "package": package.id,
+ "analyses_left": balance.view(), "unlimited_until": rfc3339_opt(unlimited),
+ })),
+ ))
+}
diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs
index f5d1417..853be1e 100644
--- a/services/backend/src/routes/analyses.rs
+++ b/services/backend/src/routes/analyses.rs
@@ -28,6 +28,7 @@ use crate::AppState;
use crate::auth::AuthUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
+use crate::packages;
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
use db::Role;
@@ -118,9 +119,18 @@ async fn request(
req: AnalysisRequest,
) -> ApiResult<(StatusCode, Json)> {
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
- // Admins get detailed analyses free of charge.
+ // Admins and a running unlimited package (within its daily cap) use no unit.
+ let admin = auth.user.has_role(Role::Admin);
+ let unlimited = !admin && {
+ let mut conn = state.db.acquire().await?;
+ let until = packages::unlimited_until(&mut conn, auth.id()).await?;
+ if until.is_some() {
+ packages::check_fair_use(&mut conn, auth.id(), state.config.unlimited_daily_limit).await?;
+ }
+ until.is_some()
+ };
let unit = match target {
- _ if auth.user.has_role(Role::Admin) => None,
+ _ if admin || unlimited => None,
Target::Synastry { .. } => Some(Unit::Synastry),
_ => Some(Unit::Natal),
};
@@ -145,8 +155,14 @@ async fn queue(
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
};
- let prompt_version = &state.config.prompt_version;
- let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}"));
+ // The cache key leaves out the admin-edited prompt revision, so a chart keeps
+ // its analysis when the prompt changes; copying from another chart needs the same revision.
+ let base_version = &state.config.prompt_version;
+ let cache_key = sha256_hex(&format!("{kind}|{hash}|{base_version}|{model}|{language}"));
+ let prompt_version = &match super::prompts::current_revision(&state.db, kind, language).await? {
+ Some(id) => format!("{base_version}-r{id}"),
+ None => base_version.clone(),
+ };
// Already requested for this chart/synastry: return it.
let existing: Option = sqlx::query_as(&format!(
@@ -172,9 +188,11 @@ async fn queue(
// The same chart elsewhere (another user, same birth data) was already analysed: copy it.
let cached: Option<(Value, Option, Option)> = sqlx::query_as(
- "SELECT content, input_tokens, output_tokens FROM analyses WHERE cache_key = $1 AND status = 'done' LIMIT 1",
+ "SELECT content, input_tokens, output_tokens FROM analyses \
+ WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1",
)
.bind(&cache_key)
+ .bind(prompt_version)
.fetch_optional(&state.db)
.await?;
if let Some((content, input_tokens, output_tokens)) = cached {
diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs
index ce0c105..649f076 100644
--- a/services/backend/src/routes/charts.rs
+++ b/services/backend/src/routes/charts.rs
@@ -273,8 +273,9 @@ pub async fn update(
};
let mut tx = state.db.begin().await?;
if let Some((birth, result, hash)) = &recalculated {
- // The old summary (and an admin's analyses) no longer match the chart.
+ // The old summary, the comparisons (and an admin's analyses) no longer match the chart.
sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?;
+ sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1").bind(id).execute(&mut *tx).await?;
sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4")
.bind(birth)
.bind(result)
@@ -322,11 +323,16 @@ async fn corrected_birth(
return Err(ApiError::conflict("person_locked", persons::LOCKED_MESSAGE));
}
let admin = auth.user.has_role(db::Role::Admin);
- let (analysed, in_synastry): (bool, bool) = sqlx::query_as(
- "SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed'), \
- EXISTS (SELECT 1 FROM synastries WHERE chart1_id = $1 OR chart2_id = $1)",
+ // The user's own comparisons with the person are deleted on correction (they
+ // no longer match), unless a paid analysis was written for one of them.
+ let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
+ "SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
+ OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
+ WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed'), \
+ EXISTS (SELECT 1 FROM synastries WHERE (chart1_id = $1 OR chart2_id = $1) AND owner_id <> $2)",
)
.bind(chart.id)
+ .bind(auth.id())
.fetch_one(&state.db)
.await?;
if analysed && !admin {
@@ -335,10 +341,10 @@ async fn corrected_birth(
"Ehhez a személyhez már készült részletes elemzés, ezért az adatai nem módosíthatók.",
));
}
- if in_synastry {
+ if foreign_synastry {
return Err(ApiError::conflict(
"person_in_synastry",
- "A személy szerepel egy összevetésben, ezért az adatai nem módosíthatók.",
+ "A személy szerepel valaki más összevetésében, ezért az adatai nem módosíthatók.",
));
}
calculate(state, birth).await
diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs
index 382c8d9..d01e11d 100644
--- a/services/backend/src/routes/mod.rs
+++ b/services/backend/src/routes/mod.rs
@@ -11,6 +11,7 @@ mod analyses;
mod auth;
mod charts;
mod payments;
+mod prompts;
mod shares;
mod synastries;
@@ -49,6 +50,7 @@ pub fn router(state: Arc) -> Router {
Router::new()
.route("/healthz", get(health))
.route("/v1/config", get(public_config))
+ .route("/v1/packages", get(payments::catalog))
// login
.route("/v1/auth/register", post(auth::register))
.route("/v1/auth/login", post(auth::login))
@@ -89,6 +91,11 @@ pub fn router(state: Arc) -> Router {
.route("/v1/admin/users", get(admin::list_users))
.route("/v1/admin/users/{id}", patch(admin::update_user))
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
+ .route("/v1/admin/users/{id}/packages", post(admin::grant_package))
+ .route("/v1/admin/prompts", get(prompts::list))
+ .route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
+ .route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
+ .route("/v1/admin/previews/{id}", get(prompts::get_preview))
.layer(cors(&state.config.cors_allowed_origins))
.layer(
TraceLayer::new_for_http()
@@ -122,7 +129,7 @@ async fn public_config(State(state): St) -> Json {
"summary_model": c.summary_model,
"password_login": c.password_login,
"mock_payments": c.mock_payments,
- "person_pack_size": c.person_pack_size,
+ "unlimited_daily_limit": c.unlimited_daily_limit,
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
}
diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs
index 9aa9acb..9b5a1ca 100644
--- a/services/backend/src/routes/payments.rs
+++ b/services/backend/src/routes/payments.rs
@@ -1,38 +1,49 @@
-//! Payments. Until Stripe is connected, `MOCK_PAYMENTS=true` turns on a
-//! stand-in: "paying" grants what was bought right away (an analysis unit or
-//! a person package), so the paid flow can be used end to end.
+//! Packages and payments. Until Stripe is connected, `MOCK_PAYMENTS=true`
+//! turns on a stand-in: "paying" grants the package right away, so the paid
+//! flow can be used end to end.
use axum::Json;
use axum::extract::State;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
-use uuid::Uuid;
use super::{Body, St};
use crate::auth::AuthUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
+use crate::packages::{self, CATALOG, Source};
use crate::persons;
+use crate::views::rfc3339;
+
+/// The package catalog (public).
+pub async fn catalog() -> Json {
+ Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::>() }))
+}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MockPayment {
- /// One analysis unit.
+ /// A package id from the catalog.
+ package: Option,
+ /// Shorthand: the cheapest package with one unit of this kind.
unit: Option,
- package: Option,
}
-#[derive(Debug, Clone, Copy, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum Package {
- /// `PERSON_PACK_SIZE` more persons.
- Persons,
- /// Any number of persons.
- PersonsUnlimited,
+/// What the user has now: units left, person slots, the unlimited package.
+pub async fn holdings(state: &crate::AppState, auth: &AuthUser) -> Result {
+ let mut conn = state.db.acquire().await?;
+ let balance = credits::balance(&mut conn, auth.id()).await?;
+ let persons = persons::slots(&mut conn, auth, state.config.free_person_slots).await?;
+ let until = packages::unlimited_until(&mut conn, auth.id()).await?;
+ Ok(json!({
+ "analyses_left": balance.view(),
+ "persons": persons.view(),
+ "unlimited_until": until.map(rfc3339),
+ }))
}
-/// Grants an analysis unit or a person package as a (pretend) purchase.
+/// Grants a package as a (pretend) purchase.
pub async fn mock(
State(state): St,
auth: AuthUser,
@@ -41,38 +52,17 @@ pub async fn mock(
if !state.config.mock_payments {
return Err(ApiError::NotFound("payment method"));
}
- let (unit, delta) = match (req.unit, req.package) {
- (Some(unit), None) => (Some(unit), 1),
- (None, Some(Package::Persons)) => (Some(Unit::Person), state.config.person_pack_size),
- (None, Some(Package::PersonsUnlimited)) => (None, 0),
- _ => return Err(ApiError::BadRequest("give either unit or package".into())),
+ let id = match (req.package.as_deref(), req.unit) {
+ (Some(id), None) => id,
+ (None, Some(Unit::Natal)) => "single",
+ (None, Some(Unit::Synastry)) => "addon_synastry",
+ (None, Some(Unit::Person)) => "addon_persons",
+ _ => return Err(ApiError::BadRequest("give either package or unit".into())),
};
+ let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
let mut tx = state.db.begin().await?;
- match unit {
- Some(unit) => {
- sqlx::query(
- "INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
- VALUES ($1, $2, $3, $4, 'purchase', 'mock payment')",
- )
- .bind(Uuid::now_v7())
- .bind(auth.id())
- .bind(unit.as_str())
- .bind(delta as i32)
- .execute(&mut *tx)
- .await?;
- }
- None => {
- sqlx::query(
- "INSERT INTO entitlements (user_id, entitlement, note) VALUES ($1, 'unlimited_persons', 'mock payment') \
- ON CONFLICT DO NOTHING",
- )
- .bind(auth.id())
- .execute(&mut *tx)
- .await?;
- }
- }
- let balance = credits::balance(&mut tx, auth.id()).await?;
- let persons = persons::slots(&mut tx, &auth, state.config.free_person_slots).await?;
+ packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?;
tx.commit().await?;
- Ok(Json(json!({ "analyses_left": balance.view(), "persons": persons.view() })))
+ tracing::info!(user = %auth.id(), package = package.id, "mock payment");
+ Ok(Json(holdings(&state, &auth).await?))
}
diff --git a/services/backend/src/routes/prompts.rs b/services/backend/src/routes/prompts.rs
new file mode 100644
index 0000000..512566e
--- /dev/null
+++ b/services/backend/src/routes/prompts.rs
@@ -0,0 +1,280 @@
+//! Editable system prompts of the analyses (admin only).
+//!
+//! Every save adds a row to `prompt_revisions`; the newest row of a
+//! (kind, language) is in force, `system` NULL meaning the built-in text.
+//! New analyses record the revision in `prompt_version`, so analyses that
+//! are already written or queued keep the text they were started with.
+//!
+//! A draft can be tried on one of the admin's own charts first: a row in
+//! `prompt_previews` that the worker writes like an analysis, but it is never
+//! shown to users, cached or charged.
+
+use analysis_prompt::{Kind, default_system, user_template};
+use axum::Json;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum_extra::extract::WithRejection;
+use serde::Deserialize;
+use serde_json::{Value, json};
+use sqlx::PgPool;
+use time::OffsetDateTime;
+use uuid::Uuid;
+
+use super::{Body, IdPath, St};
+use crate::AppState;
+use crate::auth::AdminUser;
+use crate::error::{ApiError, ApiResult};
+use crate::views::{rfc3339, rfc3339_opt};
+
+/// The kinds whose prompt the admin page edits.
+const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
+const MAX_CHARS: usize = 50_000;
+const HISTORY: i64 = 20;
+/// Test runs of one admin waiting or being written at the same time.
+const MAX_OPEN_PREVIEWS: i64 = 3;
+
+/// The revision id of an admin-edited prompt in force, `None` for the built-in one.
+pub async fn current_revision(db: &PgPool, kind: &str, language: &str) -> Result, sqlx::Error> {
+ let row: Option<(i64, bool)> = sqlx::query_as(
+ "SELECT id, system IS NOT NULL FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
+ )
+ .bind(kind)
+ .bind(language)
+ .fetch_optional(db)
+ .await?;
+ Ok(row.filter(|(_, custom)| *custom).map(|(id, _)| id))
+}
+
+type RevisionRow = (i64, Option, OffsetDateTime, Option);
+
+async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result {
+ let rows: Vec = sqlx::query_as(
+ "SELECT r.id, r.system, r.created_at, u.email FROM prompt_revisions r \
+ LEFT JOIN users u ON u.id = r.created_by \
+ WHERE r.kind = $1 AND r.language = $2 ORDER BY r.id DESC LIMIT $3",
+ )
+ .bind(kind.as_str())
+ .bind(language)
+ .bind(HISTORY)
+ .fetch_all(db)
+ .await?;
+ let default = default_system(kind, language);
+ let current = rows.first();
+ let history: Vec = rows
+ .iter()
+ .map(|(id, system, at, by)| {
+ json!({"id": id, "custom": system.is_some(), "system": system, "created_at": rfc3339(*at), "created_by": by})
+ })
+ .collect();
+ Ok(json!({
+ "kind": kind.as_str(),
+ "language": language,
+ "system": current.and_then(|r| r.1.clone()).unwrap_or_else(|| default.clone()),
+ "custom": current.is_some_and(|r| r.1.is_some()),
+ "updated_at": current.map(|r| rfc3339(r.2)),
+ "updated_by": current.and_then(|r| r.3.clone()),
+ "default": default,
+ "user_template": user_template(kind),
+ "history": history,
+ }))
+}
+
+pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> {
+ let mut prompts = Vec::new();
+ for kind in EDITABLE {
+ for language in &state.config.supported_locales {
+ prompts.push(entry(&state.db, kind, language).await?);
+ }
+ }
+ Ok(Json(json!({ "prompts": prompts })))
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SavePrompt {
+ /// The new system prompt; `null` restores the built-in one.
+ system: Option,
+}
+
+fn parse_target(state: &AppState, kind: &str, language: &str) -> Result {
+ let kind = Kind::parse(kind).filter(|k| EDITABLE.contains(k)).ok_or(ApiError::NotFound("prompt"))?;
+ if !state.config.supported_locales.iter().any(|l| l == language) {
+ return Err(ApiError::NotFound("prompt"));
+ }
+ Ok(kind)
+}
+
+/// Trims a submitted prompt and checks its length.
+fn clean_system(text: &str) -> Result {
+ let text = text.trim().replace("\r\n", "\n");
+ if text.is_empty() {
+ return Err(ApiError::BadRequest("the prompt must not be empty".into()));
+ }
+ if text.chars().count() > MAX_CHARS {
+ return Err(ApiError::BadRequest(format!("the prompt is longer than {MAX_CHARS} characters")));
+ }
+ Ok(text)
+}
+
+pub async fn save(
+ State(state): St,
+ AdminUser(admin): AdminUser,
+ WithRejection(Path((kind, language)), _): WithRejection, ApiError>,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult> {
+ let kind = parse_target(&state, &kind, &language)?;
+ let default = default_system(kind, &language);
+ // The built-in text is stored as NULL, so later code changes reach it.
+ let system = match req.system.as_deref().map(clean_system).transpose()? {
+ Some(s) if s == default.trim() => None,
+ other => other,
+ };
+ let current: Option<(Option,)> = sqlx::query_as(
+ "SELECT system FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
+ )
+ .bind(kind.as_str())
+ .bind(&language)
+ .fetch_optional(&state.db)
+ .await?;
+ let unchanged = match ¤t {
+ Some((text,)) => *text == system,
+ None => system.is_none(),
+ };
+ if !unchanged {
+ sqlx::query("INSERT INTO prompt_revisions (kind, language, system, created_by) VALUES ($1, $2, $3, $4)")
+ .bind(kind.as_str())
+ .bind(&language)
+ .bind(&system)
+ .bind(admin.id())
+ .execute(&state.db)
+ .await?;
+ tracing::info!(admin = %admin.id(), kind = kind.as_str(), %language, custom = system.is_some(), "prompt changed");
+ }
+ Ok(Json(entry(&state.db, kind, &language).await?))
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct StartPreview {
+ /// The draft to try (it need not be saved).
+ system: String,
+ /// One of the admin's own charts (own or a person), for a summary or natal analysis.
+ chart_id: Option,
+ /// One of the admin's own comparisons, for a synastry analysis.
+ synastry_id: Option,
+}
+
+#[derive(sqlx::FromRow)]
+struct PreviewRow {
+ id: Uuid,
+ kind: String,
+ chart_id: Option,
+ synastry_id: Option,
+ language: String,
+ model: String,
+ status: String,
+ content: Option,
+ error: Option,
+ model_used: Option,
+ input_tokens: Option,
+ output_tokens: Option,
+ cost_usd: Option,
+ created_at: OffsetDateTime,
+ started_at: Option,
+ completed_at: Option,
+}
+
+const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
+ input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
+
+impl PreviewRow {
+ fn view(self) -> Value {
+ let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
+ json!({
+ "id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
+ "language": self.language, "model": self.model, "status": self.status, "content": self.content,
+ "error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
+ "output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
+ "completed_at": rfc3339_opt(self.completed_at), "seconds": seconds,
+ })
+ }
+}
+
+pub async fn start_preview(
+ State(state): St,
+ AdminUser(admin): AdminUser,
+ WithRejection(Path((kind, language)), _): WithRejection, ApiError>,
+ WithRejection(Json(req), _): Body,
+) -> ApiResult<(StatusCode, Json)> {
+ let kind = parse_target(&state, &kind, &language)?;
+ let system = clean_system(&req.system)?;
+ // The target must be the admin's own: a chart, or for a synastry analysis a comparison.
+ let (chart_id, synastry_id, found) = match (kind, req.chart_id, req.synastry_id) {
+ (Kind::Synastry, None, Some(id)) => {
+ let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2")
+ .bind(id)
+ .bind(admin.id())
+ .fetch_optional(&state.db)
+ .await?;
+ (None, Some(id), row.map(|_| "synastry"))
+ }
+ (Kind::Summary | Kind::Natal, Some(id), None) => {
+ let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
+ .bind(id)
+ .bind(admin.id())
+ .fetch_optional(&state.db)
+ .await?;
+ (Some(id), None, row.map(|_| "chart"))
+ }
+ (Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
+ _ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
+ };
+ if found.is_none() {
+ return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
+ }
+ let (open,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
+ )
+ .bind(admin.id())
+ .fetch_one(&state.db)
+ .await?;
+ if open >= MAX_OPEN_PREVIEWS {
+ return Err(ApiError::conflict(
+ "too_many_previews",
+ "Egyszerre legfeljebb három próba futhat. Várd meg, amíg valamelyik elkészül.",
+ ));
+ }
+ let model = match kind {
+ Kind::Summary => &state.config.summary_model,
+ _ => &state.config.analysis_model,
+ };
+ let row: PreviewRow = sqlx::query_as(&format!(
+ "INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, language, model, system, created_by) \
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {PREVIEW_COLUMNS}"
+ ))
+ .bind(Uuid::now_v7())
+ .bind(kind.as_str())
+ .bind(chart_id)
+ .bind(synastry_id)
+ .bind(&language)
+ .bind(model)
+ .bind(&system)
+ .bind(admin.id())
+ .fetch_one(&state.db)
+ .await?;
+ Ok((StatusCode::ACCEPTED, Json(row.view())))
+}
+
+pub async fn get_preview(
+ State(state): St,
+ AdminUser(admin): AdminUser,
+ WithRejection(Path(id), _): IdPath,
+) -> ApiResult> {
+ let row: Option =
+ sqlx::query_as(&format!("SELECT {PREVIEW_COLUMNS} FROM prompt_previews WHERE id = $1 AND created_by = $2"))
+ .bind(id)
+ .bind(admin.id())
+ .fetch_optional(&state.db)
+ .await?;
+ Ok(Json(row.ok_or(ApiError::NotFound("preview"))?.view()))
+}
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index f985a86..a6b6bf4 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -755,11 +755,7 @@ async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn persons_use_package_slots(pool: PgPool) {
- let app = TestApp::with_config(pool, |c| {
- c.free_person_slots = 1;
- c.person_pack_size = 2;
- })
- .await;
+ let app = TestApp::with_config(pool, |c| c.free_person_slots = 1).await;
let anna = app.register("anna@example.com", "Anna").await;
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
assert_eq!(own["kind"], "own");
@@ -780,16 +776,15 @@ async fn persons_use_package_slots(pool: PgPool) {
assert_eq!(r.status, StatusCode::NO_CONTENT);
assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 0);
- // a package adds two slots
- let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "persons"})).await;
- assert_eq!(r.body["persons"], json!({"used": 1, "limit": 3, "left": 2, "unlimited": false}), "{}", r.body);
+ // a person package adds five slots
+ let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "addon_persons"})).await;
+ assert_eq!(r.body["persons"], json!({"used": 1, "limit": 6, "left": 5, "unlimited": false}), "{}", r.body);
let second = app.chart(&anna, "Cili", false, "1986-01-01").await;
app.chart(&anna, "Dani", false, "1987-01-01").await;
- let r = app.post("/v1/charts", Some(&anna), new_person("1988-01-01")).await;
- assert_eq!(r.status, StatusCode::CONFLICT);
+ assert_eq!(persons(app.get("/v1/me", Some(&anna)).await.body)["left"], 3);
// the unlimited package
- let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "persons_unlimited"})).await;
+ let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "unlimited"})).await;
assert_eq!(r.body["persons"], json!({"used": 3, "limit": null, "left": null, "unlimited": true}));
app.chart(&anna, "Emma", false, "1988-01-01").await;
let list = app.get("/v1/charts", Some(&anna)).await.body;
@@ -827,3 +822,249 @@ async fn persons_use_package_slots(pool: PgPool) {
let r = app.call("PATCH", &format!("/v1/charts/{pid}"), Some(&admin), Some(corrected)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn admins_edit_analysis_prompts(pool: PgPool) {
+ let app = TestApp::new(pool.clone()).await;
+ let admin = app.register("admin@example.com", "Admin").await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ assert_eq!(app.get("/v1/admin/prompts", Some(&anna)).await.status, StatusCode::FORBIDDEN);
+
+ let r = app.get("/v1/admin/prompts", Some(&admin)).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ let prompts = r.body["prompts"].as_array().unwrap();
+ let keys: Vec =
+ prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
+ assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en", "synastry/hu", "synastry/en"]);
+ let natal = &prompts[2];
+ assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
+ assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
+ let default = natal["default"].as_str().unwrap().to_string();
+
+ let put = |body: Value, uri: &'static str| app.call("PUT", uri, Some(&admin), Some(body));
+ assert_eq!(put(json!({"system": " "}), "/v1/admin/prompts/natal/hu").await.status, StatusCode::BAD_REQUEST);
+ assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/composite/hu").await.status, StatusCode::NOT_FOUND);
+ assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/natal/de").await.status, StatusCode::NOT_FOUND);
+ // saving the built-in text keeps the built-in prompt
+ let r = put(json!({"system": default}), "/v1/admin/prompts/natal/hu").await;
+ assert_eq!(
+ (r.status, &r.body["custom"], r.body["history"].as_array().unwrap().len()),
+ (StatusCode::OK, &json!(false), 0)
+ );
+
+ // an analysis written with the built-in prompt
+ let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
+ let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
+ grant_units(&app, &anna, "natal", 1).await;
+ let r = app.call("POST", &uri, Some(&anna), None).await;
+ assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some("v1")));
+ let first = r.body["id"].as_str().unwrap().to_string();
+ sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid")
+ .bind(&first)
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let r = put(json!({"system": "Saját szabályok.\r\n"}), "/v1/admin/prompts/natal/hu").await;
+ assert_eq!(
+ (&r.body["custom"], r.body["system"].as_str(), r.body["updated_by"].as_str()),
+ (&json!(true), Some("Saját szabályok."), Some("admin@example.com"))
+ );
+ let revision = r.body["history"][0]["id"].as_i64().unwrap();
+ let r = put(json!({"system": "Saját szabályok."}), "/v1/admin/prompts/natal/hu").await;
+ assert_eq!(r.body["history"].as_array().unwrap().len(), 1); // unchanged: no new revision
+
+ // the chart keeps its analysis; the same birth data elsewhere is written anew with the edited prompt
+ let r = app.call("POST", &uri, Some(&anna), None).await;
+ assert_eq!((r.status, r.body["id"].as_str()), (StatusCode::OK, Some(first.as_str())));
+ let bela = app.register("bela@example.com", "Béla").await;
+ let same = app.chart(&bela, "Saját", true, "1990-03-15").await;
+ grant_units(&app, &bela, "natal", 1).await;
+ let r = app.call("POST", &format!("/v1/charts/{}/analyses", same["id"].as_str().unwrap()), Some(&bela), None).await;
+ let expected = format!("v1-r{revision}");
+ assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some(expected.as_str())));
+
+ // back to the built-in prompt
+ let r = put(json!({"system": null}), "/v1/admin/prompts/natal/hu").await;
+ assert_eq!((&r.body["custom"], r.body["system"].as_str()), (&json!(false), Some(default.as_str())));
+ assert_eq!(r.body["history"].as_array().unwrap().len(), 2);
+}
+
+/// Starts a summary prompt test run on `chart`.
+async fn start_preview(app: &TestApp, chart: &Value, token: &str) -> Response {
+ let body = json!({"system": " Próba szabályok. ", "chart_id": chart["id"]});
+ app.call("POST", "/v1/admin/prompts/summary/hu/preview", Some(token), Some(body)).await
+}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn admins_try_prompt_drafts_on_own_charts(pool: PgPool) {
+ let app = TestApp::new(pool.clone()).await;
+ let admin = app.register("admin@example.com", "Admin").await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ let own = app.chart(&admin, "Saját", true, "1990-03-15").await;
+ let annas = app.chart(&anna, "Saját", true, "1991-05-01").await;
+
+ assert_eq!(start_preview(&app, &own, &anna).await.status, StatusCode::FORBIDDEN);
+ assert_eq!(start_preview(&app, &annas, &admin).await.status, StatusCode::NOT_FOUND); // only own charts
+ let r = start_preview(&app, &own, &admin).await;
+ assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
+ assert_eq!(
+ (r.body["status"].as_str(), r.body["kind"].as_str(), r.body["model"].as_str()),
+ (Some("pending"), Some("summary"), Some("anthropic/claude-summary"))
+ );
+ let id = r.body["id"].as_str().unwrap().to_string();
+ let (system,): (String,) = sqlx::query_as("SELECT system FROM prompt_previews WHERE id = $1::uuid")
+ .bind(&id)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(system, "Próba szabályok.");
+
+ // nothing reaches the chart's analyses, and the saved prompt is unchanged
+ let r = app.get(&format!("/v1/charts/{}/analyses", own["id"].as_str().unwrap()), Some(&admin)).await;
+ assert!(
+ r.body["analyses"].as_array().unwrap().iter().all(|a| a["kind"] == "summary" && a["prompt_version"] == "v1")
+ );
+ assert_eq!(app.get("/v1/admin/prompts", Some(&admin)).await.body["prompts"][0]["custom"], json!(false));
+
+ let r = app.get(&format!("/v1/admin/previews/{id}"), Some(&admin)).await;
+ assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::OK, Some("pending")));
+ assert_eq!(app.get(&format!("/v1/admin/previews/{id}"), Some(&anna)).await.status, StatusCode::FORBIDDEN);
+
+ // at most three at a time
+ start_preview(&app, &own, &admin).await;
+ start_preview(&app, &own, &admin).await;
+ let r = start_preview(&app, &own, &admin).await;
+ assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("too_many_previews")));
+ let body = json!({"system": "Részletes próba.", "chart_id": own["id"]});
+ sqlx::query("UPDATE prompt_previews SET status = 'done'").execute(&pool).await.unwrap();
+ let r = app.call("POST", "/v1/admin/prompts/natal/hu/preview", Some(&admin), Some(body)).await;
+ assert_eq!((r.status, r.body["model"].as_str()), (StatusCode::ACCEPTED, Some("anthropic/claude-test")));
+
+ // a relationship analysis is tried on one of the admin's comparisons
+ let other = app.chart(&admin, "Béla", false, "1985-08-02").await;
+ let syn = app.post("/v1/synastries", Some(&admin), json!({"chart1_id": own["id"], "chart2_id": other["id"]})).await;
+ let uri = "/v1/admin/prompts/synastry/hu/preview";
+ let r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "chart_id": own["id"]}))).await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST);
+ let r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "synastry_id": syn.body["id"]}))).await;
+ assert_eq!(
+ (r.status, r.body["synastry_id"].as_str()),
+ (StatusCode::ACCEPTED, syn.body["id"].as_str()),
+ "{}",
+ r.body
+ );
+}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn comparisons_with_persons(pool: PgPool) {
+ let app = TestApp::new(pool).await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
+ let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
+ let compare = || app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": bela["id"]}));
+ let r = compare().await;
+ assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
+ let first = r.body["id"].as_str().unwrap().to_string();
+ assert_eq!((&r.body["chart1"]["is_primary"], &r.body["chart2"]["label"]), (&json!(true), &json!("Béla")));
+
+ // correcting the person removes the comparison that no longer matches
+ let uri = format!("/v1/charts/{}", bela["id"].as_str().unwrap());
+ let corrected = |date: &str| json!({"birth": {"date": date, "time": "10:00", "country": "HU", "place": "Szeged"}});
+ let r = app.call("PATCH", &uri, Some(&anna), Some(corrected("1985-08-03"))).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ assert_eq!(app.get(&format!("/v1/synastries/{first}"), Some(&anna)).await.status, StatusCode::NOT_FOUND);
+
+ // after a paid relationship analysis the person is fixed
+ let r = compare().await;
+ assert_eq!(r.status, StatusCode::CREATED);
+ let id = r.body["id"].as_str().unwrap();
+ grant_units(&app, &anna, "synastry", 1).await;
+ let r = app.call("POST", &format!("/v1/synastries/{id}/analyses"), Some(&anna), None).await;
+ assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
+ let r = app.call("PATCH", &uri, Some(&anna), Some(corrected("1985-08-04"))).await;
+ assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_analysed")));
+ assert_eq!(app.get("/v1/synastries", Some(&anna)).await.body["synastries"].as_array().unwrap().len(), 1);
+}
+
+/// An admin (or not) gives `user` a package.
+async fn grant_package(app: &TestApp, token: &str, user: &str, package: &str) -> Response {
+ let body = json!({"package": package, "note": "ajándék"});
+ app.call("POST", &format!("/v1/admin/users/{user}/packages"), Some(token), Some(body)).await
+}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn packages_grant_units_and_unlimited(pool: PgPool) {
+ let app = TestApp::new(pool.clone()).await;
+ let admin = app.register("admin@example.com", "Admin").await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string();
+
+ // the catalog is public
+ let r = app.get("/v1/packages", None).await;
+ let ids: Vec<&str> = r.body["packages"].as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap()).collect();
+ assert_eq!(ids, ["single", "couple", "family", "unlimited", "addon_synastry", "addon_persons"]);
+ assert_eq!(
+ (&r.body["packages"][2]["badge"], &r.body["packages"][2]["per_analysis_huf"]),
+ (&json!("Legnépszerűbb"), &json!(1090))
+ );
+
+ // an admin gives a package as a gift
+ assert_eq!(grant_package(&app, &anna, &anna_id, "family").await.status, StatusCode::FORBIDDEN);
+ assert_eq!(grant_package(&app, &admin, &anna_id, "gold").await.status, StatusCode::NOT_FOUND);
+ let r = grant_package(&app, &admin, &anna_id, "family").await;
+ assert_eq!(
+ (r.status, &r.body["analyses_left"]),
+ (StatusCode::CREATED, &json!({"natal": 6, "synastry": 5})),
+ "{}",
+ r.body
+ );
+ let me = app.get("/v1/me", Some(&anna)).await.body;
+ assert_eq!((&me["persons"]["limit"], &me["unlimited_until"]), (&json!(10), &Value::Null)); // 5 free + 5
+ let (source, price): (String, i32) =
+ sqlx::query_as("SELECT source, price_huf FROM package_orders WHERE package = 'family'")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!((source.as_str(), price), ("admin", 0));
+
+ // a (mock) purchase adds to it and records the price
+ let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "couple"})).await;
+ assert_eq!(r.body["analyses_left"], json!({"natal": 8, "synastry": 6}), "{}", r.body);
+ let (price,): (i32,) =
+ sqlx::query_as("SELECT price_huf FROM package_orders WHERE package = 'couple'").fetch_one(&pool).await.unwrap();
+ assert_eq!(price, 6990);
+
+ // unlimited: a year, and a second one extends it
+ let bela = app.register("bela@example.com", "Béla").await;
+ let bela_id = app.get("/v1/me", Some(&bela)).await.body["user"]["id"].as_str().unwrap().to_string();
+ grant_package(&app, &admin, &bela_id, "unlimited").await;
+ let r = grant_package(&app, &admin, &bela_id, "unlimited").await;
+ let until = time::OffsetDateTime::parse(
+ r.body["unlimited_until"].as_str().unwrap(),
+ &time::format_description::well_known::Rfc3339,
+ )
+ .unwrap();
+ let days = (until - time::OffsetDateTime::now_utc()).whole_days();
+ assert!((725..=733).contains(&days), "{days}");
+ assert_eq!(app.get("/v1/me", Some(&bela)).await.body["persons"]["unlimited"], true);
+
+ // analyses use no unit, up to the daily cap (3 in tests)
+ for (i, date) in ["1980-01-01", "1981-01-01", "1982-01-01"].into_iter().enumerate() {
+ let chart = app.chart(&bela, &format!("P{i}"), i == 0, date).await;
+ let r = app
+ .call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&bela), None)
+ .await;
+ assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
+ }
+ let fourth = app.chart(&bela, "P3", false, "1983-01-01").await;
+ let uri = format!("/v1/charts/{}/analyses", fourth["id"].as_str().unwrap());
+ let r = app.call("POST", &uri, Some(&bela), None).await;
+ assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::TOO_MANY_REQUESTS, Some("fair_use_limit")));
+
+ // after it ends, units are needed again
+ sqlx::query("UPDATE entitlements SET expires_at = now() - interval '1 day'").execute(&pool).await.unwrap();
+ let r = app.call("POST", &uri, Some(&bela), None).await;
+ assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED);
+ assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null);
+}
diff --git a/services/frontend/README.md b/services/frontend/README.md
index 31c2444..c5c9a2d 100644
--- a/services/frontend/README.md
+++ b/services/frontend/README.md
@@ -11,10 +11,15 @@ Next.js (App Router, TypeScript) webes felület. A compose-ban a **3001-es** por
- **saját születési adatok**: dátum, idő (vagy „nem tudom”), ország és település helykeresővel. Mentéskor kiszámolja a képletet, és megmutatja a pozíciókat (bolygók, tengelyek, házcsúcsok).
- A javított adatokból új képlet lesz (a backend a születési adatot nem módosítja), és az lesz a saját képlet.
- Ha a megadott időpont az óraátállítás miatt kétszer is előfordult, a felület megkérdezi, melyikről van szó.
+- **Összevetések** (`/osszevetesek`, szinasztria): a saját és a felvett személyek képletei közül bármelyik kettő összevethető; a személykártyán és a személy képletoldalán „Összevetés velem” gomb is van. Az összevetés oldala (`/osszevetesek/{id}`):
+ - kettős kör: belül az első fél bolygói és házai, kívül a második fél bolygói, középen a köztük lévő főfényszögek;
+ - a fényszögek jelleg szerint (harmonikus, feszültebb, együttállás);
+ - fülek: fizetős kapcsolati elemzés (`synastry` egység), a két fél közti fényszögmátrix, házátfedések, kompozit, részletes lista.
- **Admin** (`/admin`, csak `admin` szerepkörrel; másnak 404):
- felhasználók keresése;
- szerepkörök be- és kikapcsolása (felhasználó, prémium, VIP, szerző, admin);
- - elemzések jóváírása típusonként (képlet, szinasztria).
+ - elemzések jóváírása típusonként (képlet, szinasztria);
+ - **Promptok** (`/admin/promptok`): a tömör összefoglaló, a részletes és a kapcsolati elemzés system promptja szerkeszthető, változatokkal; mentés előtt egy saját képleten vagy összevetésen kipróbálható.
- **Jogosultság:** a belépést nem igénylő oldalakon kívül minden oldal a szerveren ellenőrzi a munkamenetet; belépés nélkül a belépőoldalra irányít, majd vissza.
## Felépítés
diff --git a/services/frontend/src/app/admin/AdminUsers.tsx b/services/frontend/src/app/admin/AdminUsers.tsx
index c6955c6..3ad06f4 100644
--- a/services/frontend/src/app/admin/AdminUsers.tsx
+++ b/services/frontend/src/app/admin/AdminUsers.tsx
@@ -2,9 +2,10 @@
import { useCallback, useEffect, useState } from "react";
+import { huf, usePackages } from "@/components/PackageCards";
import { api, errorText } from "@/lib/api";
import { ROLE_LABELS, formatDate } from "@/lib/astro";
-import type { AdminUser, Role } from "@/lib/types";
+import type { AdminUser, Package, Role } from "@/lib/types";
const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"];
const UNITS: { value: "natal" | "synastry"; label: string }[] = [
@@ -16,6 +17,7 @@ export function AdminUsers({ selfId }: { selfId: string }) {
const [query, setQuery] = useState("");
const [users, setUsers] = useState(null);
const [error, setError] = useState(null);
+ const packages = usePackages() ?? [];
const load = useCallback(async (q: string) => {
try {
@@ -62,6 +64,7 @@ export function AdminUsers({ selfId }: { selfId: string }) {
Felhasználó
Szerepkörök
Részletes elemzések
+ Csomag
Képletek
Regisztrált
Utoljára belépett
@@ -73,6 +76,7 @@ export function AdminUsers({ selfId }: { selfId: string }) {
key={u.id}
user={u}
isSelf={u.id === selfId}
+ packages={packages}
onChange={(next) => setUsers((list) => list?.map((x) => (x.id === next.id ? next : x)) ?? null)}
/>
))}
@@ -84,7 +88,17 @@ export function AdminUsers({ selfId }: { selfId: string }) {
);
}
-function UserRow({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean; onChange: (u: AdminUser) => void }) {
+function UserRow({
+ user,
+ isSelf,
+ packages,
+ onChange,
+}: {
+ user: AdminUser;
+ isSelf: boolean;
+ packages: Package[];
+ onChange: (u: AdminUser) => void;
+}) {
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
const [delta, setDelta] = useState("");
@@ -200,9 +214,84 @@ function UserRow({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean;
)}
+
+
+
{user.charts}
{formatDate(user.created_at)}
{formatDate(user.last_login_at, true)}
);
}
+
+/** Gives the user a package from the catalog (a gift: nothing is paid). */
+function PackageGrant({
+ user,
+ packages,
+ onChange,
+}: {
+ user: AdminUser;
+ packages: Package[];
+ onChange: (u: AdminUser) => void;
+}) {
+ const [id, setId] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
+
+ async function give(e: React.FormEvent) {
+ e.preventDefault();
+ const pkg = packages.find((p) => p.id === id);
+ if (!pkg) return;
+ setBusy(true);
+ setStatus(null);
+ try {
+ const res = await api<{ analyses_left: AdminUser["analyses_left"]; unlimited_until: string | null }>(
+ `/admin/users/${user.id}/packages`,
+ { body: { package: pkg.id, note: "admin ajándék" } },
+ );
+ onChange({ ...user, analyses_left: res.analyses_left, unlimited_until: res.unlimited_until });
+ setStatus({ ok: true, text: `${pkg.name} kiosztva` });
+ setId("");
+ } catch (err) {
+ setStatus({ ok: false, text: errorText(err) });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+
+ );
+}
diff --git a/services/frontend/src/app/admin/page.tsx b/services/frontend/src/app/admin/page.tsx
index 9f65c2e..a8da261 100644
--- a/services/frontend/src/app/admin/page.tsx
+++ b/services/frontend/src/app/admin/page.tsx
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
+import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server";
import { AdminUsers } from "./AdminUsers";
@@ -13,9 +14,10 @@ export default async function AdminPage() {
if (!me.user.roles.includes("admin")) notFound();
return (
+
Felhasználók
-
Szerepkörök kezelése és részletes elemzések jóváírása (ajándék, reklamáció). A vásárlások is ide könyvelődnek majd.
+
Szerepkörök kezelése, csomagok kiosztása és elemzések jóváírása (ajándék, reklamáció).
diff --git a/services/frontend/src/app/admin/promptok/AdminPrompts.tsx b/services/frontend/src/app/admin/promptok/AdminPrompts.tsx
new file mode 100644
index 0000000..2ff9f8d
--- /dev/null
+++ b/services/frontend/src/app/admin/promptok/AdminPrompts.tsx
@@ -0,0 +1,283 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import { Tabs } from "@/components/Tabs";
+import { api, errorText } from "@/lib/api";
+import { formatDate } from "@/lib/astro";
+import type { AdminPrompt, ChartListItem, PromptKind } from "@/lib/types";
+
+import { PromptTrial } from "./PromptTrial";
+
+const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] = [
+ {
+ kind: "summary",
+ id: "osszefoglalo",
+ label: "Tömör összefoglaló",
+ about: "Ingyenes, a képlet oldalán a „Röviden” blokk: egy cím és 3–4 mondat. Minden új képlethez magától elkészül.",
+ },
+ {
+ kind: "natal",
+ id: "reszletes",
+ label: "Részletes elemzés",
+ about: "Fizetős, hat fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
+ },
+ {
+ kind: "synastry",
+ id: "kapcsolati",
+ label: "Kapcsolati elemzés",
+ about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
+ },
+];
+
+const LANGUAGES: Record = { hu: "Magyar", en: "Angol" };
+
+export function AdminPrompts() {
+ const [prompts, setPrompts] = useState(null);
+ const [charts, setCharts] = useState([]);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ api<{ prompts: AdminPrompt[] }>("/admin/prompts")
+ .then((d) => setPrompts(d.prompts))
+ .catch((e) => setError(errorText(e)));
+ api<{ charts: ChartListItem[] }>("/charts")
+ .then((d) => setCharts(d.charts))
+ .catch(() => setCharts([]));
+ }, []);
+
+ if (error) {
+ return (
+
+ {error}
+
+ );
+ }
+ if (!prompts) return Betöltés…
;
+
+ const replace = (next: AdminPrompt) =>
+ setPrompts((all) => all?.map((p) => (p.kind === next.kind && p.language === next.language ? next : p)) ?? null);
+
+ return (
+
+ ({
+ id: k.id,
+ label: k.label,
+ content: (
+ p.kind === k.kind)}
+ charts={charts}
+ onSaved={replace}
+ />
+ ),
+ }))}
+ />
+
+ );
+}
+
+function KindPrompts({
+ about,
+ prompts,
+ charts,
+ onSaved,
+}: {
+ about: string;
+ prompts: AdminPrompt[];
+ charts: ChartListItem[];
+ onSaved: (p: AdminPrompt) => void;
+}) {
+ const [language, setLanguage] = useState(prompts[0]?.language ?? "hu");
+ const prompt = prompts.find((p) => p.language === language) ?? prompts[0];
+ if (!prompt) return null;
+ return (
+
+
+
{about}
+ {prompts.length > 1 && (
+
+ Nyelv
+ setLanguage(e.target.value)}
+ >
+ {prompts.map((p) => (
+
+ {LANGUAGES[p.language] ?? p.language}
+ {p.custom ? " (szerkesztett)" : ""}
+
+ ))}
+
+
+ )}
+
+
+
+ );
+}
+
+function PromptEditor({
+ prompt,
+ charts,
+ onSaved,
+}: {
+ prompt: AdminPrompt;
+ charts: ChartListItem[];
+ onSaved: (p: AdminPrompt) => void;
+}) {
+ const [draft, setDraft] = useState(prompt.system);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const [saved, setSaved] = useState(false);
+ const dirty = draft.trim() !== prompt.system.trim();
+ const id = `prompt-${prompt.kind}-${prompt.language}`;
+
+ useEffect(() => {
+ if (!dirty) return;
+ const warn = (e: BeforeUnloadEvent) => e.preventDefault();
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [dirty]);
+
+ async function save(system: string | null) {
+ setBusy(true);
+ setError(null);
+ setSaved(false);
+ try {
+ const next = await api(`/admin/prompts/${prompt.kind}/${prompt.language}`, {
+ method: "PUT",
+ body: { system },
+ });
+ onSaved(next);
+ setDraft(next.system);
+ setSaved(true);
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+
+
+ {prompt.custom ? (
+ Szerkesztett
+ ) : (
+ Alapértelmezett
+ )}
+ {prompt.updated_at && (
+
+ Utoljára mentve: {formatDate(prompt.updated_at, true)}
+ {prompt.updated_by ? ` · ${prompt.updated_by}` : ""}
+
+ )}
+
+
+
+ Utasítások a modellnek (system prompt)
+
+
+ {error && (
+
+ {error}
+
+ )}
+ {saved && !dirty && (
+
+ Elmentve. Az ezután kért elemzések már ezzel készülnek.
+
+ )}
+
+
+ save(draft)} disabled={busy || !dirty}>
+ {busy ? "Mentés…" : "Mentés"}
+
+ setDraft(prompt.system)} disabled={busy || !dirty}>
+ Változások elvetése
+
+ {(prompt.custom || draft.trim() !== prompt.default.trim()) && (
+ setDraft(prompt.default)}
+ disabled={busy || draft.trim() === prompt.default.trim()}
+ >
+ Alapértelmezett szöveg betöltése
+
+ )}
+
+
+
{
+ setDraft(system);
+ setSaved(false);
+ }}
+ />
+
+
+ Amit a modell ezen felül kap
+
+
+ Ezt a kód állítja össze, nem szerkeszthető. A {"{chart data}"} helyére a képlet pozíciói kerülnek
+ (név, dátum és hely nélkül). A válasz formáját (mezők, fejezetek) egy rögzített JSON-séma írja elő.
+
+
{prompt.user_template}
+
+
+
+ {prompt.history.length > 0 && (
+
+ Korábbi változatok ({prompt.history.length})
+
+ {prompt.history.map((h, i) => (
+
+
+ {formatDate(h.created_at, true)}
+ {h.created_by ? ` · ${h.created_by}` : ""}
+
+
+ {i === 0 ? "érvényben · " : ""}
+ {h.custom ? `${(h.system ?? "").length.toLocaleString("hu-HU")} karakter` : "alapértelmezett"}
+
+ setDraft(h.system ?? prompt.default)}
+ disabled={busy}
+ >
+ Betöltés
+
+
+ ))}
+
+ A betöltött változat a szerkesztőbe kerül; a mentéssel lesz érvényes.
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/admin/promptok/PromptTrial.tsx b/services/frontend/src/app/admin/promptok/PromptTrial.tsx
new file mode 100644
index 0000000..cf817e9
--- /dev/null
+++ b/services/frontend/src/app/admin/promptok/PromptTrial.tsx
@@ -0,0 +1,240 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+
+import { AnalysisLoading } from "@/components/AnalysisLoading";
+import { AnalysisView } from "@/components/AnalysisView";
+import { api, errorText } from "@/lib/api";
+import { formatDate } from "@/lib/astro";
+import { listName } from "@/lib/synastry";
+import type { ChartListItem, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
+
+const POLL_MS = 4000;
+const MAX_POLLS = 150; // 10 minutes
+
+interface Trial {
+ preview: PromptPreview;
+ /** The draft it was written with, to load it back. */
+ system: string;
+}
+
+/**
+ * Writes an analysis with the draft in the editor (saved or not) on one of
+ * the admin's charts. Nothing is stored with the chart.
+ */
+export function PromptTrial({
+ kind,
+ language,
+ draft,
+ charts,
+ onLoad,
+}: {
+ kind: PromptKind;
+ language: string;
+ draft: string;
+ charts: ChartListItem[];
+ onLoad: (system: string) => void;
+}) {
+ const synastry = kind === "synastry";
+ const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
+ const [synastries, setSynastries] = useState([]);
+ const [synastryId, setSynastryId] = useState("");
+
+ useEffect(() => {
+ if (!synastry) return;
+ api<{ synastries: SynastryListItem[] }>("/synastries")
+ .then((d) => {
+ const own = d.synastries.filter((s) => s.owned);
+ setSynastries(own);
+ setSynastryId((current) => current || own[0]?.id || "");
+ })
+ .catch(() => setSynastries([]));
+ }, [synastry]);
+ const targetId = synastry ? synastryId : chartId;
+ const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
+ const [trials, setTrials] = useState([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const selectId = `trial-chart-${kind}-${language}`;
+
+ async function start() {
+ setBusy(true);
+ setError(null);
+ try {
+ const preview = await api(`/admin/prompts/${kind}/${language}/preview`, {
+ body: synastry ? { system: draft, synastry_id: synastryId } : { system: draft, chart_id: chartId },
+ });
+ setTrials((all) => [{ preview, system: draft }, ...all]);
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const update = useCallback(
+ (next: PromptPreview) =>
+ setTrials((all) => all.map((t) => (t.preview.id === next.id ? { ...t, preview: next } : t))),
+ [],
+ );
+
+ return (
+
+
+
Kipróbálás
+
+ A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
+ {synastry ? "összevetésedre" : "képletedre"}. Az eredmény nem kerül {synastry ? "az összevetéshez" : "a képlethez"},
+ csak itt látod. Valódi modellhívás, ezért költsége van.
+
+
+ {synastry && synastries.length === 0 ? (
+
+ Kipróbáláshoz előbb készíts egy összevetést az Összevetések oldalon.
+
+ ) : synastry ? (
+
+
+ Összevetés
+ setSynastryId(e.target.value)}>
+ {synastries.map((s) => (
+
+ {comparisonName(s)}
+
+ ))}
+
+
+
+ {busy ? "Indítás…" : "Kipróbálás"}
+
+
+ ) : charts.length === 0 ? (
+ Kipróbáláshoz előbb legyen legalább egy képleted.
+ ) : (
+
+
+ Képlet
+ setChartId(e.target.value)}>
+ {charts.map((c) => (
+
+ {c.is_primary ? `Én (${c.label})` : c.label}
+ {c.birth.time ? "" : " – idő nélkül"}
+
+ ))}
+
+
+
+ {busy ? "Indítás…" : "Kipróbálás"}
+
+
+ )}
+ {error && (
+
+ {error}
+
+ )}
+ {trials.map((t) => (
+ {
+ const s = synastries.find((x) => x.id === t.preview.synastry_id);
+ return s ? comparisonName(s) : "Összevetés";
+ })()
+ : (charts.find((c) => c.id === t.preview.chart_id)?.label ?? "Képlet")
+ }
+ changed={t.system.trim() !== draft.trim()}
+ onUpdate={update}
+ onLoad={() => onLoad(t.system)}
+ />
+ ))}
+
+ );
+}
+
+function TrialResult({
+ trial,
+ chartLabel,
+ changed,
+ onUpdate,
+ onLoad,
+}: {
+ trial: Trial;
+ chartLabel: string;
+ changed: boolean;
+ onUpdate: (p: PromptPreview) => void;
+ onLoad: () => void;
+}) {
+ const p = trial.preview;
+ const waiting = p.status === "pending" || p.status === "running";
+
+ useEffect(() => {
+ if (!waiting) return;
+ let polls = 0;
+ let stopped = false;
+ let timer: ReturnType | undefined;
+ const tick = async () => {
+ try {
+ const next = await api(`/admin/previews/${p.id}`);
+ if (stopped) return;
+ onUpdate(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, p.id, onUpdate]);
+
+ const meta = [
+ p.model_used ?? p.model,
+ p.seconds !== null ? `${p.seconds} mp` : null,
+ p.input_tokens !== null && p.output_tokens !== null
+ ? `${p.input_tokens.toLocaleString("hu-HU")} + ${p.output_tokens.toLocaleString("hu-HU")} token`
+ : null,
+ p.cost_usd !== null ? `$${p.cost_usd.toFixed(4)}` : null,
+ ].filter(Boolean);
+
+ return (
+
+
+ {waiting ? (
+
+ ) : p.status === "failed" ? (
+
+ Nem sikerült: {p.error ?? "ismeretlen hiba"}
+
+ ) : p.content ? (
+ p.kind === "summary" ? (
+
+
{p.content.title}
+
{p.content.summary}
+
+ ) : (
+
+ )
+ ) : null}
+ {meta.length > 0 && !waiting && {meta.join(" · ")}
}
+
+ );
+}
diff --git a/services/frontend/src/app/admin/promptok/page.tsx b/services/frontend/src/app/admin/promptok/page.tsx
new file mode 100644
index 0000000..3fc50c8
--- /dev/null
+++ b/services/frontend/src/app/admin/promptok/page.tsx
@@ -0,0 +1,27 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+
+import { AdminNav } from "@/components/AdminNav";
+import { requireMe } from "@/lib/server";
+
+import { AdminPrompts } from "./AdminPrompts";
+
+export const metadata: Metadata = { title: "Promptok" };
+
+export default async function AdminPromptsPage() {
+ const me = await requireMe("/admin/promptok");
+ if (!me.user.roles.includes("admin")) notFound();
+ return (
+
+
+
+
Promptok
+
+ Az elemzéseket író modell utasításai. A változás az ezután kért elemzésekre hat; a már elkészültek
+ változatlanok maradnak.
+
+
+
+
+ );
+}
diff --git a/services/frontend/src/app/csomagok/page.tsx b/services/frontend/src/app/csomagok/page.tsx
new file mode 100644
index 0000000..be17388
--- /dev/null
+++ b/services/frontend/src/app/csomagok/page.tsx
@@ -0,0 +1,97 @@
+import type { Metadata } from "next";
+
+import { PackageCards } from "@/components/PackageCards";
+import { formatDate } from "@/lib/astro";
+import { backendGet, requireMe } from "@/lib/server";
+import type { Package, PublicConfig } from "@/lib/types";
+
+export const metadata: Metadata = { title: "Csomagok" };
+
+const faq = (dailyLimit: number): [string, string][] => [
+ [
+ "Lejárnak a megvett elemzések?",
+ "Nem. A csomagokban kapott elemzések és személyhelyek addig megmaradnak, amíg fel nem használod őket. Csak a Korlátlan csomag szól egy évre.",
+ ],
+ [
+ "Mi a különbség a képletelemzés és a kapcsolati elemzés között?",
+ "A képletelemzés egy ember születési képletét írja le hat fejezetben. A kapcsolati elemzés két képletet vet össze: mi vonz, hol súrlódtok, és mit ad a kapcsolat.",
+ ],
+ [
+ "Mire kell a személyhely?",
+ "A saját képleted mellé felvett emberekhez (társ, gyerek, barát). Egy személy felvétele egy helyet használ; a képlete és a rövid összefoglalója ingyenes, a részletes elemzés külön jár.",
+ ],
+ [
+ "Van korlát a Korlátlan csomagban?",
+ `Méltányos használat: naponta legfeljebb ${dailyLimit} új részletes elemzés kérhető. Ha még tart, egy újabb Korlátlan csomag a lejárathoz ad hozzá egy évet.`,
+ ],
+];
+
+/** The packages: the main ladder, top-ups, and what the user has now. */
+export default async function PackagesPage() {
+ const me = await requireMe("/csomagok");
+ const [catalog, config] = await Promise.all([
+ backendGet<{ packages: Package[] }>("/v1/packages"),
+ backendGet("/v1/config"),
+ ]);
+ const packages = catalog?.packages ?? [];
+ const canPay = config?.mock_payments ?? false;
+ const left = me.analyses_left;
+ const slots = me.persons;
+
+ return (
+
+
+
Csomagok
+
+ Minél többen vagytok, annál kevesebbe kerül egy elemzés. A megvett elemzések nem járnak le.
+
+
+
+
+ Most
+ {me.unlimited_until ? (
+
+ Korlátlan csomag {formatDate(me.unlimited_until).replace(/\.$/, "")}-ig.
+
+ ) : (
+
+ {left.natal} képletelemzés · {left.synastry} kapcsolati elemzés ·{" "}
+ {slots.unlimited ? (
+ "korlátlan személy"
+ ) : (
+ <>
+ {slots.left} szabad személyhely
+ >
+ )}
+
+ )}
+
+
+
+
+
+ Kiegészítők
+ Ha már van csomagod, és csak egy kicsi kell még.
+ p.tier === "addon").map((p) => p.id)}
+ canPay={canPay}
+ compact
+ />
+
+
+
+ Gyakori kérdések
+
+ {faq(config?.unlimited_daily_limit ?? 5).map(([q, a]) => (
+
+
{q}
+ {a}
+
+ ))}
+
+ Az árak bruttó árak, az áfát tartalmazzák.
+
+
+ );
+}
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index 0dde22a..d75f0d4 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -16,6 +16,7 @@
--harmonic: #7fb0e0;
--tense: #e38b8b;
--square: #f0a35e;
+ --p2: #c3a6f0; /* the second person of a comparison */
--radius: 10px;
--font-display: var(--font-cormorant), "Cormorant Garamond", Georgia, serif;
--font-body: var(--font-inter), Inter, system-ui, sans-serif;
@@ -215,8 +216,8 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
@media (max-width: 640px) { .loading { flex-direction: column; text-align: center; } }
/* Payment step */
-.pay-box { display: flex; flex-direction: column; gap: 16px; padding: 20px; max-width: 520px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
-.pay-line { display: flex; justify-content: space-between; gap: 12px; }
+.pay-box { display: flex; flex-direction: column; gap: 16px; padding: 20px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
+.pay-lead { margin: 0; }
.chart-layout { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, 1fr); gap: 24px; align-items: stretch; }
.chart-side { gap: 16px; }
.chart-side .summary-card { flex: 1 1 auto; }
@@ -352,13 +353,6 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.person-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; padding: 0 12px 12px; border-top: 1px solid var(--line); padding-top: 8px; margin: 0 8px; }
.btn-danger { border-color: var(--danger); color: var(--danger); }
.btn-danger:hover { background: rgba(242, 160, 160, 0.08); color: var(--danger); border-color: var(--danger); }
-.packs { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; }
-.pack {
- display: flex; flex-direction: column; gap: 6px; align-items: flex-start; padding: 16px 18px;
- background: var(--panel-2); border: 1px solid var(--line-2); border-radius: var(--radius);
-}
-.pack strong { font-family: var(--font-display); font-size: 22px; font-weight: 600; }
-.pack .btn { margin-top: 8px; }
/* Chart switcher (the chart page title) */
.switcher { position: relative; align-self: flex-start; }
@@ -404,3 +398,154 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.legal a { color: var(--gold); }
.legal-table td { vertical-align: top; line-height: 1.5; }
.danger-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--danger); border-radius: var(--radius); }
+
+/* Admin */
+.admin-nav { display: flex; gap: 4px; border-bottom: 1px solid var(--line); margin-bottom: 4px; overflow-x: auto; }
+.admin-nav a {
+ padding: 10px 14px; min-height: 44px; display: inline-flex; align-items: center; color: var(--muted);
+ text-decoration: none; border-bottom: 2px solid transparent; margin-bottom: -1px; white-space: nowrap;
+}
+.admin-nav a:hover { color: var(--ink); }
+.admin-nav a[aria-current="page"] { color: var(--gold); border-bottom-color: var(--gold); }
+.prompt-kind { display: flex; flex-direction: column; gap: 20px; }
+.prompt-kind-head { display: flex; gap: 16px 24px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; }
+.prompt-kind-head > p { flex: 1 1 360px; margin: 0; }
+.prompt-lang { width: 200px; }
+.prompt-editor { display: flex; flex-direction: column; gap: 16px; }
+.prompt-status { display: flex; gap: 8px 12px; align-items: center; flex-wrap: wrap; }
+.prompt-text {
+ min-height: 420px; padding: 12px 14px; resize: vertical; line-height: 1.55;
+ font: 400 13.5px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+}
+.prompt-extra { display: flex; flex-direction: column; gap: 10px; }
+.prompt-pre {
+ margin: 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel-2);
+ white-space: pre-wrap; overflow-wrap: anywhere; font: 400 13px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ color: var(--ink-2);
+}
+.prompt-history { list-style: none; margin: 0 0 8px; padding: 0; display: flex; flex-direction: column; }
+.prompt-history li {
+ display: grid; grid-template-columns: 1fr auto auto; gap: 12px; align-items: center;
+ padding: 8px 0; border-bottom: 1px solid var(--line);
+}
+@media (max-width: 640px) {
+ .prompt-text { min-height: 320px; font-size: 13px; }
+ .prompt-lang { width: 100%; }
+ .prompt-history li { grid-template-columns: 1fr auto; }
+ .prompt-history li .hint { grid-column: 1; }
+ .prompt-history li .btn { grid-column: 2; grid-row: 1 / span 2; }
+}
+.prompt-trial {
+ display: flex; flex-direction: column; gap: 16px; padding: 20px; border: 1px solid var(--line);
+ border-radius: var(--radius); background: rgba(255, 255, 255, 0.015);
+}
+.prompt-trial-head { display: flex; flex-direction: column; gap: 6px; }
+.prompt-trial-head h2 { font-size: 18px; margin: 0; }
+.prompt-trial-head .hint { margin: 0; }
+.prompt-trial-form { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
+.prompt-trial-form .field { flex: 0 1 360px; }
+.trial { display: flex; flex-direction: column; gap: 14px; padding-top: 16px; border-top: 1px solid var(--line); }
+.trial-head { display: flex; gap: 8px 12px; align-items: center; justify-content: space-between; flex-wrap: wrap; }
+.trial-summary { display: flex; flex-direction: column; gap: 8px; }
+.trial-summary .summary-title, .trial-summary .summary-text { margin: 0; }
+@media (max-width: 640px) {
+ .prompt-trial { padding: 16px; }
+ .prompt-trial-form .field { flex-basis: 100%; }
+ .prompt-trial-form .btn { width: 100%; }
+}
+
+/* Comparisons (synastry) */
+.w-p2 .w-point-glyph { fill: var(--p2); }
+.w-p2 .w-point-tick { stroke: var(--p2); }
+.w-p2 .w-point:hover .w-point-glyph { fill: var(--gold); }
+.w-end-p2 { fill: var(--p2); }
+.w-p2-band { stroke-dasharray: 2 4; }
+.legend-dot, .pair-dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; flex: none; }
+.legend-p1 { background: var(--ink); }
+.legend-p2 { background: var(--p2); }
+.p2-text, .cross-grid th.p2-head { color: var(--p2); }
+.cross-grid td.cross-corner { position: relative; min-width: 76px; height: 44px; font: 500 11px var(--font-body); color: var(--muted); }
+.cross-col { position: absolute; top: 2px; right: 4px; color: var(--p2); white-space: nowrap; }
+.cross-row { position: absolute; bottom: 2px; left: 2px; white-space: nowrap; }
+
+.nature { display: flex; flex-direction: column; gap: 12px; }
+.nature-bar { display: flex; gap: 3px; height: 10px; border-radius: 999px; overflow: hidden; }
+.nature-bar-sm { height: 6px; margin-top: 4px; }
+.nature-seg { flex-basis: 0; min-width: 4px; }
+.nature-harmonious { background: var(--harmonic); }
+.nature-challenging { background: var(--tense); }
+.nature-neutral { background: var(--gold); }
+.nature-list { margin: 0; display: flex; flex-direction: column; gap: 8px; }
+.nature-list > div { display: grid; grid-template-columns: 128px 1fr; gap: 8px; align-items: baseline; }
+.nature-list dt { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); }
+.nature-list dd { margin: 0; }
+.nature-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
+
+.pair-card { gap: 4px; }
+.pair-row {
+ display: grid; grid-template-columns: auto 1fr auto; gap: 12px; align-items: center; padding: 10px 0;
+ color: inherit; text-decoration: none; border-bottom: 1px solid var(--line);
+}
+.pair-row:last-child { border-bottom: 0; padding-bottom: 0; }
+a.pair-row:hover strong { color: var(--gold); }
+.pair-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.pair-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
+
+.compare-new { gap: 16px; }
+.compare-form { display: grid; grid-template-columns: 1fr auto 1fr auto; gap: 12px; align-items: end; }
+.compare-swap { font-size: 20px; padding: 0 10px; }
+.compare-tile { gap: 6px; padding: 16px 20px; }
+.compare-tile strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
+.compare-tile .muted { font-size: 14px; }
+.compare-tile .form-actions { margin-top: 6px; }
+.back-link { font-size: 14px; text-decoration: none; align-self: flex-start; }
+@media (max-width: 640px) {
+ .compare-form { grid-template-columns: 1fr auto; }
+ .compare-form .field:first-child { grid-column: 1; }
+ .compare-swap { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
+ .compare-form .field:nth-child(3) { grid-column: 1; }
+ .compare-form > .btn-primary { grid-column: 1 / -1; width: 100%; }
+ .nature-list > div { grid-template-columns: 1fr; gap: 2px; }
+ .nav { overflow-x: auto; scrollbar-width: none; }
+ .nav a { white-space: nowrap; padding: 10px 9px; }
+ .cross-grid td.cross-corner { min-width: 56px; font-size: 9px; }
+}
+
+/* Packages */
+.pkg-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: stretch; }
+.pkg-grid-compact { grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; }
+.pkg {
+ position: relative; display: flex; flex-direction: column; gap: 10px; padding: 22px 20px 20px;
+ background: var(--panel); border: 1px solid var(--line-2); border-radius: var(--radius);
+}
+.pkg-grid-compact .pkg { padding: 18px 16px 16px; gap: 8px; background: var(--panel-2); }
+.pkg-featured { border-color: var(--gold); box-shadow: 0 0 0 1px var(--gold), 0 12px 32px rgba(217, 180, 106, 0.12); }
+.pkg-tags { display: flex; gap: 6px; min-height: 22px; flex-wrap: wrap; }
+.pkg-badge, .pkg-save {
+ display: inline-flex; align-items: center; min-height: 22px; padding: 0 9px; border-radius: 999px;
+ font-size: 12px; font-weight: 600; letter-spacing: 0.3px;
+}
+.pkg-badge { background: var(--gold); color: var(--gold-ink); }
+.pkg-save { border: 1px solid rgba(159, 216, 176, 0.5); color: var(--ok); }
+.pkg-name { font-size: 26px; }
+.pkg-grid-compact .pkg-name { font-size: 22px; }
+.pkg-tagline { margin: 0; font-size: 14px; min-height: 42px; }
+.pkg-price { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
+.pkg-price strong { font-family: var(--font-display); font-size: 32px; font-weight: 600; color: var(--ink); }
+.pkg-grid-compact .pkg-price strong { font-size: 26px; }
+.pkg-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; font-size: 14px; color: var(--ink-2); flex: 1; }
+.pkg-list li { padding-left: 22px; position: relative; }
+.pkg-list li::before { content: "✓"; position: absolute; left: 0; color: var(--gold); }
+.pkg-per { margin: 0; }
+.pkg-step { margin: 0; font-size: 13px; color: var(--gold); }
+.pkg .btn { margin-top: 4px; width: 100%; }
+.holdings { gap: 6px; padding: 16px 20px; }
+.holdings p { margin: 0; color: var(--ink-2); }
+.faq { margin: 0; display: flex; flex-direction: column; gap: 14px; }
+.faq dt { font-weight: 600; margin-bottom: 4px; }
+.faq dd { margin: 0; }
+@media (max-width: 1000px) { .pkg-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+@media (max-width: 640px) {
+ .pkg-grid, .pkg-grid-compact { grid-template-columns: 1fr; }
+ .pkg-tagline { min-height: 0; }
+}
diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx
index 9fe79ab..c794698 100644
--- a/services/frontend/src/app/kepletek/[id]/page.tsx
+++ b/services/frontend/src/app/kepletek/[id]/page.tsx
@@ -7,6 +7,7 @@ import { ChartSummary } from "@/components/ChartSummary";
import { ChartSwitcher } from "@/components/ChartSwitcher";
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
+import { CompareButton } from "@/components/CompareButton";
import { Tabs } from "@/components/Tabs";
import { ASPECTS, ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
import { backendGet, requireMe } from "@/lib/server";
@@ -31,6 +32,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
]);
const charts = chartList?.charts ?? [];
const persons = charts.filter((c) => c.kind === "person");
+ const own = charts.find((c) => c.is_primary) ?? null;
if (!chart) notFound();
const list = analyses?.analyses ?? [];
const summary = list.find((a) => a.kind === "summary" && a.status !== "failed") ?? null;
@@ -51,7 +53,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
c.is_primary) ?? null}
+ own={own}
persons={persons}
canAdd={me.persons.left !== 0}
/>
@@ -116,6 +118,16 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
)}
)}
+ {!chart.is_primary && own && (
+
+
Összevetés
+
Te és {chart.label}
+
Két képlet egy körön: mi vonz, hol súrlódtok, és mit ad a kapcsolat.
+
+
+
+
+ )}
{chart.is_primary && (
Személyek
@@ -144,10 +156,11 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
label: "Elemzés",
content: (
),
diff --git a/services/frontend/src/app/osszevetesek/ComparisonActions.tsx b/services/frontend/src/app/osszevetesek/ComparisonActions.tsx
new file mode 100644
index 0000000..4fce442
--- /dev/null
+++ b/services/frontend/src/app/osszevetesek/ComparisonActions.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+
+/** Deletes a comparison (and its analysis). */
+export function ComparisonActions({ id, name }: { id: string; name: string }) {
+ const router = useRouter();
+ const [confirm, setConfirm] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+
+ async function remove() {
+ setBusy(true);
+ setError(null);
+ try {
+ await api(`/synastries/${id}`, { method: "DELETE" });
+ router.refresh();
+ } catch (e) {
+ setError(errorText(e));
+ setBusy(false);
+ }
+ }
+
+ return (
+
+ {confirm ? (
+ <>
+
Törlöd a(z) {name} összevetést és az elemzését?
+
+ {busy ? "Törlés…" : "Igen, törlöm"}
+
+
setConfirm(false)} disabled={busy}>
+ Mégse
+
+ >
+ ) : (
+
setConfirm(true)}>
+ Törlés
+
+ )}
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/osszevetesek/NewComparison.tsx b/services/frontend/src/app/osszevetesek/NewComparison.tsx
new file mode 100644
index 0000000..1d9fe55
--- /dev/null
+++ b/services/frontend/src/app/osszevetesek/NewComparison.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import Link from "next/link";
+import { useState } from "react";
+
+import { CompareButton } from "@/components/CompareButton";
+import { sideName } from "@/lib/synastry";
+import type { ChartListItem } from "@/lib/types";
+
+/** Picks two of the user's charts to compare. */
+export function NewComparison({ charts }: { charts: ChartListItem[] }) {
+ const own = charts.find((c) => c.is_primary);
+ const [first, setFirst] = useState(own?.id ?? charts[0]?.id ?? "");
+ const [second, setSecond] = useState(charts.find((c) => c.id !== (own?.id ?? charts[0]?.id))?.id ?? "");
+
+ if (charts.length < 2) {
+ return (
+
+ Új összevetés
+
+ Összevetéshez legalább két képlet kell. Vedd fel társad, családtagod vagy barátod születési adatait, és nézd meg,
+ hogyan hatnak egymásra a képleteitek.
+
+
+
+ Új személy felvétele
+
+
+
+ );
+ }
+
+ const option = (c: ChartListItem) => (
+
+ {sideName(c)}
+ {c.birth.time ? "" : " (idő nélkül)"}
+
+ );
+ const swap = () => {
+ setFirst(second);
+ setSecond(first);
+ };
+
+ return (
+
+ Új összevetés
+
+
+ Első fél
+ setFirst(e.target.value)}>
+ {charts.map(option)}
+
+
+
+ ⇄
+
+
+ Második fél
+ setSecond(e.target.value)}>
+ {charts.map(option)}
+
+
+ {first && second && first !== second ? (
+
+ ) : (
+
+ Összevetés
+
+ )}
+
+
+ {first === second
+ ? "Két különböző képletet válassz."
+ : "A körön az első fél képlete és házai vannak belül, a második fél bolygói kívül."}
+
+
+ );
+}
diff --git a/services/frontend/src/app/osszevetesek/[id]/page.tsx b/services/frontend/src/app/osszevetesek/[id]/page.tsx
new file mode 100644
index 0000000..719c309
--- /dev/null
+++ b/services/frontend/src/app/osszevetesek/[id]/page.tsx
@@ -0,0 +1,167 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+import { notFound } from "next/navigation";
+
+import { SignTrio } from "@/components/ChartCard";
+import { DetailedAnalysis } from "@/components/DetailedAnalysis";
+import { CompositeTables, CrossGrid, HouseOverlays, InterAspectList, NatureBar } from "@/components/SynastryTables";
+import { SynastryLegend, SynastryWheel } from "@/components/SynastryWheel";
+import { Tabs } from "@/components/Tabs";
+import { ASPECTS, formatBirthDate } from "@/lib/astro";
+import { backendGet, requireMe } from "@/lib/server";
+import { sideName, sideTimeKnown } from "@/lib/synastry";
+import type { Analysis, ChartListItem, PublicConfig, Synastry, SynastrySide } from "@/lib/types";
+
+export const metadata: Metadata = { title: "Összevetés" };
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const GRID_LEGEND = ["conjunction", "sextile", "square", "trine", "opposition"];
+
+function Person({ side, which }: { side: SynastrySide; which: "p1" | "p2" }) {
+ const time = sideTimeKnown(side);
+ const birth = side.birth_data;
+ const name = sideName(side);
+ const body = (
+ <>
+
+
+ {name}
+ {birth && (
+
+ {formatBirthDate(birth.date)}
+ {time && birth.time ? `, ${birth.time.slice(0, 5)}` : ", ismeretlen időpont"}
+
+ )}
+
+ {side.highlights && (
+
+ )}
+ >
+ );
+ return side.owned ? (
+
+ {body}
+
+ ) : (
+ {body}
+ );
+}
+
+/** One comparison of two charts: the double wheel, the numbers, the analysis and the tables. */
+export default async function ComparisonPage({ params }: { params: Promise<{ id: string }> }) {
+ const { id } = await params;
+ const me = await requireMe(`/osszevetesek/${id}`);
+ if (!UUID.test(id)) notFound();
+ const [synastry, analyses, config] = await Promise.all([
+ backendGet(`/v1/synastries/${id}`),
+ backendGet<{ analyses: Analysis[] }>(`/v1/synastries/${id}/analyses`),
+ backendGet("/v1/config"),
+ ]);
+ if (!synastry) notFound();
+ const list = analyses?.analyses ?? [];
+ const detailed = list.find((a) => a.status !== "failed") ?? list[0] ?? null;
+
+ const { chart1, chart2 } = synastry;
+ const name1 = sideName(chart1);
+ const name2 = sideName(chart2);
+ const time1 = sideTimeKnown(chart1);
+ const time2 = sideTimeKnown(chart2);
+ const result = synastry.synastry;
+ const unknown = [!time1 && name1, !time2 && name2].filter(Boolean);
+
+ return (
+
+
+
+ ← Összevetések
+
+
+ {name1} és {name2}
+
+
Összevetés · két képlet egymásra vetítve
+
+
+
+
+
+
+
+
+
+
+
Számokban
+
{result.summary.aspect_count} fényszög köztetek
+
+ {unknown.length > 0 && (
+
+ {unknown.join(" és ")} születési ideje ismeretlen: az ő tengelyei és házai kimaradnak, a Hold helyzete
+ közelítő.
+
+ )}
+
+
+
+
+
+
+ ),
+ },
+ {
+ id: "fenyszogek",
+ label: "Fényszögek",
+ content: (
+
+
+
+ {GRID_LEGEND.map((k) => (
+
+
+ {ASPECTS[k]?.glyph}
+ {" "}
+ {ASPECTS[k]?.hu}
+
+ ))}
+
+
+ ),
+ },
+ { id: "hazak", label: "Házak", content: },
+ { id: "kompozit", label: "Kompozit", content: },
+ {
+ id: "reszletek",
+ label: "Részletek",
+ content: ,
+ },
+ ]}
+ />
+
+
+ );
+}
diff --git a/services/frontend/src/app/osszevetesek/page.tsx b/services/frontend/src/app/osszevetesek/page.tsx
new file mode 100644
index 0000000..fbbfee9
--- /dev/null
+++ b/services/frontend/src/app/osszevetesek/page.tsx
@@ -0,0 +1,71 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+
+import { formatDate } from "@/lib/astro";
+import { backendGet, requireMe } from "@/lib/server";
+import { listName } from "@/lib/synastry";
+import type { ChartListItem, SynastryListItem } from "@/lib/types";
+
+import { ComparisonActions } from "./ComparisonActions";
+import { NewComparison } from "./NewComparison";
+
+export const metadata: Metadata = { title: "Összevetések" };
+
+/** The user's comparisons, and a form for a new one. */
+export default async function ComparisonsPage() {
+ await requireMe("/osszevetesek");
+ const [chartList, synastryList] = await Promise.all([
+ backendGet<{ charts: ChartListItem[] }>("/v1/charts"),
+ backendGet<{ synastries: SynastryListItem[] }>("/v1/synastries"),
+ ]);
+ const charts = chartList?.charts ?? [];
+ const synastries = synastryList?.synastries ?? [];
+
+ return (
+
+
+
Összevetések
+
+ Két képlet egymásra vetítve: mi vonz, hol súrlódtok, és mit ad a kapcsolat. A saját és a felvett személyek
+ képletei közül bármelyik kettőt összevetheted.
+
+
+
+
+
+ {synastries.length > 0 && (
+
+ Korábbi összevetések
+
+ {synastries.map((s) => {
+ const name = `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
+ const n = s.summary?.by_nature;
+ const total = s.summary?.aspect_count || 1;
+ return (
+
+
+ {name}
+ {formatDate(s.created_at)}
+ {n && (
+ <>
+
+
+
+
+
+
+ {n.harmonious} harmonikus · {n.challenging} feszültebb · {n.neutral} együttállás
+
+ >
+ )}
+
+ {s.owned && }
+
+ );
+ })}
+
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/profil/page.tsx b/services/frontend/src/app/profil/page.tsx
index de40003..dbb4e31 100644
--- a/services/frontend/src/app/profil/page.tsx
+++ b/services/frontend/src/app/profil/page.tsx
@@ -46,7 +46,10 @@ export default async function ProfilePage() {
{me.providers.map((p) => PROVIDERS[p] ?? p).join(", ") || "–"}
Részletes elemzések
- {me.analyses_left.natal} képlet, {me.analyses_left.synastry} szinasztria
+ {me.unlimited_until
+ ? `Korlátlan, ${formatDate(me.unlimited_until).replace(/\.$/, "")}-ig`
+ : `${me.analyses_left.natal} képlet, ${me.analyses_left.synastry} kapcsolati`}{" "}
+ · Csomagok
Személyek
diff --git a/services/frontend/src/app/szemelyek/page.tsx b/services/frontend/src/app/szemelyek/page.tsx
index 88160b1..3cfb583 100644
--- a/services/frontend/src/app/szemelyek/page.tsx
+++ b/services/frontend/src/app/szemelyek/page.tsx
@@ -18,6 +18,7 @@ export default async function PersonsPage() {
]);
const charts = list?.charts ?? [];
const persons = charts.filter((c) => c.kind === "person");
+ const ownId = charts.find((c) => c.is_primary)?.id ?? null;
const isAdmin = me.user.roles.includes("admin");
const slots = me.persons;
const full = slots.left === 0;
@@ -28,8 +29,8 @@ export default async function PersonsPage() {
Személyek
- Társad, családtagjaid, barátaid képlete. Mindegyikhez kérhetsz részletes elemzést, és a képletoldal címére
- kattintva válthatsz köztük.
+ Társad, családtagjaid, barátaid képlete. Mindegyikhez kérhetsz részletes elemzést, összevetheted a sajátoddal,
+ és a képletoldal címére kattintva válthatsz köztük.
@@ -39,6 +40,7 @@ export default async function PersonsPage() {
now)}
/>
@@ -70,7 +72,7 @@ export default async function PersonsPage() {
? "Elfogytak a helyeid. Újabb személyhez válassz csomagot."
: "A felvett személyek képletét és elemzéseit itt éred el. Egy törölt személy helye nem szabadul fel."}
-
+
)}
diff --git a/services/frontend/src/app/szemelyek/uj/page.tsx b/services/frontend/src/app/szemelyek/uj/page.tsx
index ddfc7c1..6d4bb18 100644
--- a/services/frontend/src/app/szemelyek/uj/page.tsx
+++ b/services/frontend/src/app/szemelyek/uj/page.tsx
@@ -26,7 +26,7 @@ export default async function NewPersonPage() {
{slots.left === 0 ? (
<>
Elfogytak a helyeid. Újabb személyhez válassz csomagot.
-
+
>
) : (
<>
diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx
new file mode 100644
index 0000000..2462ac7
--- /dev/null
+++ b/services/frontend/src/components/AdminNav.tsx
@@ -0,0 +1,19 @@
+import Link from "next/link";
+
+const PAGES = [
+ { href: "/admin", label: "Felhasználók" },
+ { href: "/admin/promptok", label: "Promptok" },
+];
+
+/** Switches between the admin pages. */
+export function AdminNav({ current }: { current: string }) {
+ return (
+
+ {PAGES.map((p) => (
+
+ {p.label}
+
+ ))}
+
+ );
+}
diff --git a/services/frontend/src/components/ChartTables.tsx b/services/frontend/src/components/ChartTables.tsx
index ca378d6..fadd8eb 100644
--- a/services/frontend/src/components/ChartTables.tsx
+++ b/services/frontend/src/components/ChartTables.tsx
@@ -1,7 +1,7 @@
import { ANGLES, ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
import type { Aspect, Chart, Position } from "@/lib/types";
-function Pos({ p }: { p: Position }) {
+export function Pos({ p }: { p: Position }) {
return (
<>
{dms(p.degree_in_sign_dms)} {SIGNS[p.sign]?.glyph} {signName(p.sign)}
@@ -47,7 +47,7 @@ export function BigThree({ chart }: { chart: Chart }) {
}
// Rows and columns of the aspect grid: the points drawn on the wheel, then the angles.
-const GRID_POINTS = [
+export const GRID_POINTS = [
"sun",
"moon",
"mercury",
diff --git a/services/frontend/src/components/ChartWheel.tsx b/services/frontend/src/components/ChartWheel.tsx
index dcc87a2..5d64652 100644
--- a/services/frontend/src/components/ChartWheel.tsx
+++ b/services/frontend/src/components/ChartWheel.tsx
@@ -2,7 +2,7 @@ import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib
import type { ChartResult, Position } from "@/lib/types";
// Radii of the rings (viewBox is SIZE × SIZE, centre C).
-const SIZE = 680;
+export const SIZE = 680;
const C = SIZE / 2;
const R_LABEL = 322; // ASC / MC labels
const R_OUT = 300; // outer edge of the zodiac ring
@@ -13,7 +13,7 @@ const R_HOUSE = 172; // outer edge of the house-number ring
const R_INNER = 146; // aspect circle
// Points drawn on the wheel; the asteroids and the south node are only in the tables.
-const WHEEL_POINTS = [
+export const WHEEL_POINTS = [
"sun",
"moon",
"mercury",
@@ -30,10 +30,10 @@ const WHEEL_POINTS = [
];
// Aspects drawn on the wheel, between these points; the rest (minor aspects,
// nodes, Lilith, Chiron) are only in the aspect table.
-const WHEEL_ASPECTS = ["opposition", "square", "trine", "sextile"];
-const ASPECT_POINTS = ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
-const SIGN_ORDER = Object.keys(SIGNS);
-const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
+export const WHEEL_ASPECTS = ["opposition", "square", "trine", "sextile"];
+export const ASPECT_POINTS = ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
+export const SIGN_ORDER = Object.keys(SIGNS);
+export const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
const ANGLE_LABELS: [string, string][] = [
["ascendant", "ASC"],
["midheaven", "MC"],
@@ -42,15 +42,15 @@ const ANGLE_LABELS: [string, string][] = [
];
/** Screen point of an ecliptic longitude: the ascendant (or 0° Aries) is on the left. */
-function xy(lon: number, r: number, start: number): [number, number] {
+export function xy(lon: number, r: number, start: number): [number, number] {
const a = ((180 + lon - start) * Math.PI) / 180;
return [C + r * Math.cos(a), C - r * Math.sin(a)];
}
-const f = (n: number) => n.toFixed(2);
+export const f = (n: number) => n.toFixed(2);
/** Pushes glyphs apart so that neighbours are at least `min` degrees from each other. */
-function spread(lons: number[], min: number): number[] {
+export function spread(lons: number[], min: number): number[] {
const n = lons.length;
const order = lons.map((_, i) => i).sort((a, b) => lons[a] - lons[b]);
const pos = order.map((i) => lons[i]);
@@ -73,7 +73,7 @@ function spread(lons: number[], min: number): number[] {
return out;
}
-function arcPath(r1: number, r2: number, from: number, to: number, start: number): string {
+export function arcPath(r1: number, r2: number, from: number, to: number, start: number): string {
const [x1, y1] = xy(from, r2, start);
const [x2, y2] = xy(to, r2, start);
const [x3, y3] = xy(to, r1, start);
diff --git a/services/frontend/src/components/CompareButton.tsx b/services/frontend/src/components/CompareButton.tsx
new file mode 100644
index 0000000..54d0afa
--- /dev/null
+++ b/services/frontend/src/components/CompareButton.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+
+/** Compares two charts (or opens their existing comparison). */
+export function CompareButton({
+ chart1,
+ chart2,
+ label = "Összevetés velem",
+ className = "btn btn-sm btn-ghost",
+}: {
+ chart1: string;
+ chart2: string;
+ label?: string;
+ className?: string;
+}) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+
+ async function compare() {
+ setBusy(true);
+ setError(null);
+ try {
+ const s = await api<{ id: string }>("/synastries", { body: { chart1_id: chart1, chart2_id: chart2 } });
+ router.push(`/osszevetesek/${s.id}`);
+ } catch (e) {
+ setError(errorText(e));
+ setBusy(false);
+ }
+ }
+
+ return (
+ <>
+
+ {busy ? "Számolás…" : label}
+
+ {error && (
+
+ {error}
+
+ )}
+ >
+ );
+}
diff --git a/services/frontend/src/components/DetailedAnalysis.tsx b/services/frontend/src/components/DetailedAnalysis.tsx
index 86313f7..7224f19 100644
--- a/services/frontend/src/components/DetailedAnalysis.tsx
+++ b/services/frontend/src/components/DetailedAnalysis.tsx
@@ -7,6 +7,7 @@ import { api, errorText } from "@/lib/api";
import type { Analysis } from "@/lib/types";
import { AnalysisLoading } from "./AnalysisLoading";
+import { PackageChooser } from "./PackageCards";
import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000;
@@ -14,30 +15,70 @@ const MAX_POLLS = 120; // 10 minutes
type Step = "offer" | "confirm" | "pay";
+/** What is analysed: a natal chart, or a comparison of two charts. */
+export type AnalysisTarget = { kind: "natal"; chartId: string } | { kind: "synastry"; synastryId: string };
+
+const TEXTS = {
+ natal: {
+ eyebrow: "Részletes elemzés",
+ title: "Az egész képleted, fejezetekre bontva",
+ about:
+ "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.",
+ loadingTitle: "Készül az elemzésed",
+ loading:
+ "Most íródik a hat fejezet a képleted alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár.",
+ item: "Részletes képletelemzés",
+ unitName: "képletelemzés",
+ packages: ["single", "couple", "family"],
+ },
+ synastry: {
+ eyebrow: "Kapcsolati elemzés",
+ title: "Kettőtök képlete, fejezetekre bontva",
+ about:
+ "Kb. 1300 szó öt fejezetben: mi vonz egymáshoz, kommunikáció, érzelmi kötődés, súrlódások, hosszú távú lehetőségek " +
+ "(a kompozit képlettel). A végén erősségek, kihívások és útravaló. Csak a két képlet pozíciói alapján készül.",
+ loadingTitle: "Készül a kapcsolati elemzés",
+ loading:
+ "Most íródik az öt fejezet a két képlet alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár.",
+ item: "Részletes kapcsolati elemzés",
+ unitName: "kapcsolati elemzés",
+ packages: ["addon_synastry", "couple", "family"],
+ },
+};
+
/**
- * The detailed analysis of a chart. A saved one is shown at once; otherwise
+ * The detailed analysis of a chart or a comparison. A saved one is shown at once; otherwise
* the offer: admins start it free, users with units confirm, others pay
* (a stand-in payment for now). While the worker writes it, a loading wheel.
*/
export function DetailedAnalysis({
- chartId,
+ target,
initial,
left,
isAdmin,
+ unlimited = false,
canPay,
+ note,
}: {
- chartId: string;
+ target: AnalysisTarget;
initial: Analysis | null;
left: number;
isAdmin: boolean;
+ /** A running unlimited package: no unit is needed. */
+ unlimited?: boolean;
/** The stand-in payment is on (MOCK_PAYMENTS). */
canPay: boolean;
+ /** Shown above a finished analysis (e.g. who is the first and the second person). */
+ note?: string;
}) {
const [analysis, setAnalysis] = useState(initial);
const [step, setStep] = useState("offer");
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const waiting = analysis?.status === "pending" || analysis?.status === "running";
+ const t = TEXTS[target.kind];
+ const path = target.kind === "natal" ? `/charts/${target.chartId}` : `/synastries/${target.synastryId}`;
useEffect(() => {
if (!waiting || !analysis) return;
@@ -62,12 +103,11 @@ export function DetailedAnalysis({
};
}, [waiting, analysis]);
- async function start(pay: boolean) {
+ async function start() {
setBusy(true);
setError(null);
try {
- if (pay) await api("/payments/mock", { body: { unit: "natal" } });
- setAnalysis(await api(`/charts/${chartId}/analyses`, { method: "POST" }));
+ setAnalysis(await api(`${path}/analyses`, { method: "POST" }));
setStep("offer");
} catch (e) {
setError(errorText(e));
@@ -78,21 +118,19 @@ export function DetailedAnalysis({
if (analysis?.status === "done" && analysis.content) {
return (
-
- Részletes elemzés
-
+
+ {t.eyebrow}
+ {note && {note}
}
+
);
}
if (waiting) {
return (
-
- Részletes elemzés
-
+
);
}
@@ -100,13 +138,10 @@ export function DetailedAnalysis({
return (
- Részletes elemzés
-
Az egész képleted, fejezetekre bontva
+ {t.eyebrow}
+ {t.title}
-
- 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.
-
+ {t.about}
{analysis?.status === "failed" && (
Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
@@ -118,64 +153,68 @@ export function DetailedAnalysis({
)}
- {isAdmin ? (
+ {isAdmin || unlimited ? (
- start(false)} disabled={busy}>
- {busy ? "Indítás…" : "Részletes elemzés készítése"}
+
+ {busy ? "Indítás…" : `${t.item} készítése`}
- Adminként ingyenes.
+ {isAdmin ? "Adminként ingyenes." : "A korlátlan csomagod része."}
) : left > 0 ? (
step === "confirm" ? (
- start(false)} disabled={busy}>
+
{busy ? "Indítás…" : "Igen, kérem az elemzést"}
setStep("offer")} disabled={busy}>
Mégse
- Ez felhasznál 1-et a {left} képletelemzésedből.
+
+ Ez felhasznál 1-et a {left} {t.unitName}edből.
+
) : (
setStep("confirm")}>
Részletes elemzés kérése
- Még {left} képletelemzésed van.
+
+ Még {left} {t.unitName}ed van.
+
)
) : canPay ? (
step === "pay" ? (
-
- Részletes képletelemzés
- 1 db
-
+
+ Válassz csomagot. A vásárlás után az elemzés azonnal elindul, a maradék elemzések pedig nem járnak le.
+
+
- start(true)} disabled={busy}>
- {busy ? "Fizetés…" : "Fizetés"}
-
setStep("offer")} disabled={busy}>
Mégse
-
Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.
) : (
setStep("pay")}>
Részletes elemzés kérése
-
- Példa megtekintése
-
+ {target.kind === "natal" && (
+
+ Példa megtekintése
+
+ )}
)
) : (
-
- Példa megtekintése
-
+ {target.kind === "natal" && (
+
+ Példa megtekintése
+
+ )}
A részletes elemzés fizetős; a csomagok hamarosan elérhetők.
)}
diff --git a/services/frontend/src/components/PackageCards.tsx b/services/frontend/src/components/PackageCards.tsx
new file mode 100644
index 0000000..411de48
--- /dev/null
+++ b/services/frontend/src/components/PackageCards.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+import type { Package } from "@/lib/types";
+
+export const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
+
+/** What a package contains, as short lines. */
+export function contents(p: Package): string[] {
+ if (p.unlimited_months) {
+ return [
+ "Korlátlan képletelemzés",
+ "Korlátlan kapcsolati elemzés",
+ "Korlátlan számú személy",
+ `${p.unlimited_months} hónapig`,
+ ];
+ }
+ const lines: string[] = [];
+ if (p.natal) lines.push(`${p.natal} részletes képletelemzés`);
+ if (p.synastry) lines.push(`${p.synastry} kapcsolati elemzés`);
+ if (p.persons) lines.push(`${p.persons} személy felvétele`);
+ return lines;
+}
+
+/**
+ * Package cards with a buy button. Bigger packages show what they save and
+ * how little more they cost than the previous one. Until Stripe is connected
+ * the payment is a stand-in (MOCK_PAYMENTS) that grants the package at once.
+ */
+export function PackageCards({
+ packages,
+ ids,
+ canPay,
+ compact = false,
+ onBought,
+}: {
+ packages: Package[];
+ /** Which packages, in this order (default: the main ladder). */
+ ids?: string[];
+ canPay: boolean;
+ compact?: boolean;
+ /** After a purchase (default: reload the page data). */
+ onBought?: (p: Package) => Promise | void;
+}) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(null);
+ const [error, setError] = useState(null);
+ const [done, setDone] = useState(null);
+ const shown = ids
+ ? ids.map((id) => packages.find((p) => p.id === id)).filter((p): p is Package => p !== undefined)
+ : packages.filter((p) => p.tier === "main");
+
+ async function buy(p: Package) {
+ setBusy(p.id);
+ setError(null);
+ setDone(null);
+ try {
+ await api("/payments/mock", { body: { package: p.id } });
+ if (onBought) await onBought(p);
+ else {
+ setDone(p.name);
+ router.refresh();
+ }
+ } catch (e) {
+ setError(errorText(e));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ return (
+
+
+ {shown.map((p, i) => {
+ const prev = i > 0 ? shown[i - 1] : null;
+ const step = prev && p.tier === "main" && prev.tier === "main" ? p.price_huf - prev.price_huf : null;
+ return (
+
+
+ {p.badge && {p.badge} }
+ {p.savings_percent ? −{p.savings_percent}% : null}
+
+
+ {p.name}
+
+ {!compact && {p.tagline}
}
+
+ {huf(p.price_huf)}
+ {p.list_price_huf && p.list_price_huf > p.price_huf && (
+
+ {huf(p.list_price_huf)}
+
+ )}
+
+
+ {contents(p).map((line) => (
+ {line}
+ ))}
+
+
+ {p.unlimited_months
+ ? "Aki sokakat vesz fel: családot, barátokat."
+ : p.per_analysis_huf
+ ? `Elemzésenként ${huf(p.per_analysis_huf)}`
+ : " "}
+
+ {step !== null && step > 0 && prev && (
+
+ Csak +{huf(step)} a(z) {prev.name} csomaghoz képest
+
+ )}
+ {canPay ? (
+ buy(p)}
+ disabled={busy !== null}
+ >
+ {busy === p.id ? "Fizetés…" : "Megveszem"}
+
+ ) : (
+
+ Hamarosan
+
+ )}
+
+ );
+ })}
+
+ {error && (
+
+ {error}
+
+ )}
+ {done && (
+
+ A(z) {done} csomag jóváírva.
+
+ )}
+ {canPay &&
Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.
}
+
+ );
+}
+
+/** Loads the catalog in the browser (for choosers inside other components). */
+export function usePackages(): Package[] | null {
+ const [packages, setPackages] = useState(null);
+ useEffect(() => {
+ api<{ packages: Package[] }>("/packages")
+ .then((d) => setPackages(d.packages))
+ .catch(() => setPackages([]));
+ }, []);
+ return packages;
+}
+
+/** A few packages to choose from, loaded on demand, with a link to all of them. */
+export function PackageChooser({
+ ids,
+ canPay,
+ onBought,
+}: {
+ ids: string[];
+ canPay: boolean;
+ onBought?: (p: Package) => Promise | void;
+}) {
+ const packages = usePackages();
+ if (packages === null) return Csomagok betöltése…
;
+ return (
+
+
+
+ Összes csomag és a részletek →
+
+
+ );
+}
diff --git a/services/frontend/src/components/PersonActions.tsx b/services/frontend/src/components/PersonActions.tsx
index 2138c2f..3163515 100644
--- a/services/frontend/src/components/PersonActions.tsx
+++ b/services/frontend/src/components/PersonActions.tsx
@@ -6,8 +6,21 @@ import { useState } from "react";
import { api, errorText } from "@/lib/api";
-/** Correct (while allowed) or delete a person. */
-export function PersonActions({ id, name, editable }: { id: string; name: string; editable: boolean }) {
+import { CompareButton } from "./CompareButton";
+
+/** Compare with the own chart, correct (while allowed) or delete a person. */
+export function PersonActions({
+ id,
+ name,
+ editable,
+ ownId,
+}: {
+ id: string;
+ name: string;
+ editable: boolean;
+ /** The user's own chart, for "compare with me". */
+ ownId?: string | null;
+}) {
const router = useRouter();
const [confirm, setConfirm] = useState(false);
const [busy, setBusy] = useState(false);
@@ -39,6 +52,7 @@ export function PersonActions({ id, name, editable }: { id: string; name: string
>
) : (
<>
+ {ownId && }
{editable && (
Adatok javítása
diff --git a/services/frontend/src/components/PersonPacks.tsx b/services/frontend/src/components/PersonPacks.tsx
index fe5bfd4..ca959f5 100644
--- a/services/frontend/src/components/PersonPacks.tsx
+++ b/services/frontend/src/components/PersonPacks.tsx
@@ -1,64 +1,8 @@
"use client";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
+import { PackageChooser } from "./PackageCards";
-import { api, errorText } from "@/lib/api";
-
-/**
- * Person packages: a few more persons, or any number. Until Stripe is
- * connected the payment is a stand-in (MOCK_PAYMENTS) that grants it at once.
- */
-export function PersonPacks({ packSize, canPay }: { packSize: number; canPay: boolean }) {
- const router = useRouter();
- const [busy, setBusy] = useState(null);
- const [error, setError] = useState(null);
-
- async function buy(pkg: "persons" | "persons_unlimited") {
- setBusy(pkg);
- setError(null);
- try {
- await api("/payments/mock", { body: { package: pkg } });
- router.refresh();
- } catch (e) {
- setError(errorText(e));
- } finally {
- setBusy(null);
- }
- }
-
- if (!canPay) {
- return További személyekhez csomag kell; a csomagok hamarosan elérhetők.
;
- }
- return (
-
-
-
- +{packSize} személy
- Még {packSize} ember képlete és elemzése.
- buy("persons")} disabled={busy !== null}>
- {busy === "persons" ? "Fizetés…" : "Fizetés"}
-
-
-
- Korlátlan
- Bárkit felvehetsz, nincs felső határ.
- buy("persons_unlimited")}
- disabled={busy !== null}
- >
- {busy === "persons_unlimited" ? "Fizetés…" : "Fizetés"}
-
-
-
- {error && (
-
- {error}
-
- )}
-
Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.
-
- );
+/** Packages that give more persons: a few more, the family package, or unlimited. */
+export function PersonPacks({ canPay }: { canPay: boolean }) {
+ return ;
}
diff --git a/services/frontend/src/components/SiteHeader.tsx b/services/frontend/src/components/SiteHeader.tsx
index 1da2ab2..13d399f 100644
--- a/services/frontend/src/components/SiteHeader.tsx
+++ b/services/frontend/src/components/SiteHeader.tsx
@@ -17,6 +17,8 @@ export function SiteHeader({ me }: { me: Me }) {
const links = [
{ href: "/keplet", label: "Képletem" },
{ href: "/szemelyek", label: "Személyek" },
+ { href: "/osszevetesek", label: "Összevetések" },
+ { href: "/csomagok", label: "Csomagok" },
{ href: "/profil", label: "Profil" },
];
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
diff --git a/services/frontend/src/components/SynastryTables.tsx b/services/frontend/src/components/SynastryTables.tsx
new file mode 100644
index 0000000..a17f026
--- /dev/null
+++ b/services/frontend/src/components/SynastryTables.tsx
@@ -0,0 +1,314 @@
+import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
+import type { HouseOverlay, InterAspect, Synastry, SynastryResult } from "@/lib/types";
+
+import { GRID_POINTS, Pos } from "./ChartTables";
+
+const NATURES: { key: keyof SynastryResult["summary"]["by_nature"]; label: string; hint: string }[] = [
+ { key: "harmonious", label: "Harmonikus", hint: "trigon, szextil: ami könnyen megy köztetek" },
+ { key: "challenging", label: "Feszültebb", hint: "kvadrát, szembenállás: súrlódás, de mozgatóerő is" },
+ { key: "neutral", label: "Együttállás", hint: "összeolvadás: erős, a bolygóktól függő hatás" },
+];
+
+/** The inter-chart aspects by character, as a bar and counts. */
+export function NatureBar({ summary }: { summary: SynastryResult["summary"] }) {
+ const total = summary.aspect_count || 1;
+ return (
+
+
+ {NATURES.map((n) => (
+
+ ))}
+
+
+ {NATURES.map((n) => (
+
+
+ {n.label}
+
+
+ {summary.by_nature[n.key]} {n.hint}
+
+
+ ))}
+
+
+ );
+}
+
+const GRID_ANGLES: [string, string][] = [
+ ["ascendant", "AC"],
+ ["midheaven", "MC"],
+];
+
+function gridPoints(s: Synastry["chart1"]): [string, string][] {
+ const present = new Set(s.chart.points.map((p) => p.id));
+ const rows: [string, string][] = GRID_POINTS.filter((id) => present.has(id)).map((id) => [id, POINTS[id]?.glyph ?? id]);
+ if (s.highlights.time_known) {
+ for (const [key, label] of GRID_ANGLES) if (s.chart.angles?.[key]) rows.push([key, label]);
+ }
+ return rows;
+}
+
+/** The aspects between the two charts: the first person in the rows, the second in the columns. */
+export function CrossGrid({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
+ const rows = gridPoints(synastry.chart1);
+ const cols = gridPoints(synastry.chart2);
+ const byPair = new Map();
+ for (const a of synastry.synastry.aspects) byPair.set(`${a.person1}|${a.person2}`, a);
+ const label = ([id, text]: [string, string], who: string) => (
+ 2 ? "sym" : "grid-angle"} aria-label={`${who}: ${pointName(id)}`} role="img">
+ {text}
+
+ );
+
+ return (
+
+
+
+
+
+ {name2} →
+ ↓ {name1}
+
+ {cols.map((c) => (
+
+ {label(c, name2)}
+
+ ))}
+
+
+
+ {rows.map((row) => {
+ const [id] = row;
+ return (
+
+
+ {label(row, name1)}
+
+ {cols.map(([other]) => {
+ const a = byPair.get(`${id}|${other}`);
+ const info = a ? ASPECTS[a.aspect] : undefined;
+ const text = a
+ ? `${name1} ${pointName(id)} ${info?.hu ?? a.aspect} ${name2} ${pointName(other)}, orbis ${orbText(a.orb)}`
+ : undefined;
+ return (
+
+ {a && (
+
+ {info?.glyph ?? "?"}
+
+ )}
+
+ );
+ })}
+
+ );
+ })}
+
+
+
+ );
+}
+
+function OverlayTable({ title, overlays, missing }: { title: string; overlays: HouseOverlay[] | null; missing: string }) {
+ return (
+
+
{title}
+ {overlays ? (
+
+
+
+ Pont
+ Jegy
+ Ház
+
+
+
+ {overlays.map((o) => (
+
+
+
+ {POINTS[o.point]?.glyph}
+ {" "}
+ {pointName(o.point)}
+
+
+
+ {SIGNS[o.sign]?.glyph}
+ {" "}
+ {signName(o.sign)}
+
+ {o.house}.
+
+ ))}
+
+
+ ) : (
+
{missing}
+ )}
+
+ );
+}
+
+/** Each person's points in the other's houses (needs the other's birth time). */
+export function HouseOverlays({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
+ const o = synastry.synastry.house_overlays;
+ return (
+
+
+ Melyik életterületét érinti a másik: az egyik fél bolygói a másik házaiban. Ehhez a ház „gazdájának” pontos
+ születési ideje kell.
+
+
+
+
+
+
+ );
+}
+
+/** The composite chart (midpoints of the two charts). */
+export function CompositeTables({ synastry }: { synastry: Synastry }) {
+ const c = synastry.synastry.composite;
+ const hasHouses = Boolean(c.houses);
+ const angles = (
+ [
+ ["ascendant", "ASC"],
+ ["midheaven", "MC"],
+ ] as const
+ ).filter(([key]) => c.angles?.[key]);
+ const aspects = [...c.aspects].filter((a) => a.orb <= 3).sort((a, b) => a.orb - b.orb);
+ return (
+
+
+ A kompozit képlet a két képlet felezőpontjaiból áll: a kapcsolatot mint önálló harmadik „személyt” írja le.
+ {!c.angles && " Tengelyek és házak nélkül, mert legalább az egyik születési idő ismeretlen."}
+
+
+
+
Pontok
+
+
+
+ Pont
+ Pozíció
+ {hasHouses && Ház }
+
+
+
+ {c.points.map((p) => (
+
+
+
+ {POINTS[p.id]?.glyph}
+ {" "}
+ {pointName(p.id)}
+
+
+
+
+ {hasHouses && {p.house ? `${p.house}.` : "–"} }
+
+ ))}
+ {angles.map(([key, label]) => (
+
+ {label}
+
+ {dms(c.angles![key].degree_in_sign_dms)} {SIGNS[c.angles![key].sign]?.glyph} {" "}
+ {signName(c.angles![key].sign)}
+
+ {hasHouses && }
+
+ ))}
+
+
+
+
+
Szoros fényszögek
+ {aspects.length === 0 ? (
+
Nincs 3°-nál szorosabb fényszög.
+ ) : (
+
+
+ {aspects.map((a) => (
+
+
+ {pointName(a.point1)} {pointName(a.point2)}
+
+ {orbText(a.orb)}
+
+ ))}
+
+
+ )}
+
+
+
+ );
+}
+
+function AspectTag({ aspect }: { aspect: string }) {
+ const info = ASPECTS[aspect];
+ return (
+
+
+ {info?.glyph}
+ {" "}
+ {info?.hu ?? aspect}
+
+ );
+}
+
+/** Every aspect between the two charts, closest first. */
+export function InterAspectList({ synastry, name1, name2 }: { synastry: Synastry; name1: string; name2: string }) {
+ const aspects = [...synastry.synastry.aspects].sort((a, b) => a.orb - b.orb);
+ if (aspects.length === 0) return Nincs fényszög a két képlet között.
;
+ return (
+
+
+
+
+ {name1}
+ Fényszög
+ {name2}
+ Orbisz
+
+
+
+ {aspects.map((a) => (
+
+
+
+ {POINTS[a.person1]?.glyph}
+ {" "}
+ {pointName(a.person1)}
+
+
+
+
+
+
+ {POINTS[a.person2]?.glyph}
+ {" "}
+ {pointName(a.person2)}
+
+ {orbText(a.orb)}
+
+ ))}
+
+
+
+ );
+}
diff --git a/services/frontend/src/components/SynastryWheel.tsx b/services/frontend/src/components/SynastryWheel.tsx
new file mode 100644
index 0000000..bb481b0
--- /dev/null
+++ b/services/frontend/src/components/SynastryWheel.tsx
@@ -0,0 +1,308 @@
+import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
+import type { ChartPoint, ChartResult, InterAspect, Position } from "@/lib/types";
+
+import {
+ ASPECT_POINTS,
+ SIGN_ELEMENT,
+ SIGN_ORDER,
+ SIZE,
+ WHEEL_ASPECTS,
+ WHEEL_POINTS,
+ arcPath,
+ f,
+ spread,
+ xy,
+} from "./ChartWheel";
+
+const C = SIZE / 2;
+const R_LABEL = 322; // ASC / MC labels of the first person
+const R_OUT = 300; // outer edge of the zodiac ring
+const R_ZOD = 262; // inner edge of the zodiac ring
+const R2_GLYPH = 238; // second person: glyphs
+const R2_DEG = 214;
+const R_MID = 198; // border of the two rings
+const R1_GLYPH = 176; // first person: glyphs
+const R1_DEG = 154;
+const R_HOUSE = 138; // house-number ring of the first person
+const R_INNER = 114; // aspect circle
+
+const ANGLE_LABELS: [string, string][] = [
+ ["ascendant", "ASC"],
+ ["midheaven", "MC"],
+ ["descendant", "DSC"],
+ ["imum_coeli", "IC"],
+];
+
+function angleOf(chart: ChartResult, key: string): Position | null {
+ const a = chart.angles?.[key];
+ return typeof a === "object" && a !== null ? a : null;
+}
+
+/** One person's planets on a ring: tick on the outer edge, glyph, degree. */
+function Ring({
+ points,
+ placed,
+ edge,
+ glyphR,
+ degR,
+ start,
+ who,
+ timeKnown,
+ className,
+}: {
+ points: ChartPoint[];
+ placed: number[];
+ edge: number;
+ glyphR: number;
+ degR: number;
+ start: number;
+ who: string;
+ timeKnown: boolean;
+ className: string;
+}) {
+ return (
+
+ {points.map((p, i) => {
+ const [t1x, t1y] = xy(p.longitude, edge, start);
+ const [t2x, t2y] = xy(p.longitude, edge - 8, start);
+ const [lx, ly] = xy(placed[i], glyphR + 13, start);
+ const [gx, gy] = xy(placed[i], glyphR, start);
+ const [dx, dy] = xy(placed[i], degR, start);
+ const deg = Number.parseInt(p.degree_in_sign_dms, 10);
+ return (
+
+
+ {who}: {pointName(p.id)} {dms(p.degree_in_sign_dms)} {signName(p.sign)}
+ {p.retrograde ? ", retrográd" : ""}
+ {timeKnown && p.house ? `, ${p.house}. ház` : ""}
+
+
+
+
+ {POINTS[p.id]?.glyph ?? p.id}
+
+
+ {deg}°{p.retrograde ? "℞" : ""}
+
+
+ );
+ })}
+
+ );
+}
+
+/**
+ * Two charts on one wheel: the first person's planets and houses inside, the
+ * second person's planets in the outer ring, the aspects between them in the middle.
+ */
+export function SynastryWheel({
+ chart1,
+ chart2,
+ time1,
+ time2,
+ aspects,
+ name1,
+ name2,
+}: {
+ chart1: ChartResult;
+ chart2: ChartResult;
+ time1: boolean;
+ time2: boolean;
+ aspects: InterAspect[];
+ name1: string;
+ name2: string;
+}) {
+ const asc = time1 ? angleOf(chart1, "ascendant") : null;
+ const start = asc?.longitude ?? 0;
+ const cusps = time1 ? (chart1.houses?.cusps ?? []) : [];
+
+ const pick = (chart: ChartResult) =>
+ WHEEL_POINTS.map((id) => chart.points.find((p) => p.id === id)).filter((p) => p !== undefined);
+ const points1 = pick(chart1);
+ const points2 = pick(chart2);
+ // The inner ring is shorter, so its glyphs need a wider angle.
+ const placed1 = spread(
+ points1.map((p) => p.longitude),
+ 12,
+ );
+ const placed2 = spread(
+ points2.map((p) => p.longitude),
+ 8,
+ );
+
+ const endsOf = (points: ChartPoint[], placed: number[], chart: ChartResult, timeKnown: boolean) => {
+ const ends = new Map();
+ points.forEach((p, i) => {
+ if (ASPECT_POINTS.includes(p.id)) ends.set(p.id, placed[i]);
+ });
+ if (timeKnown) {
+ for (const key of ["ascendant", "midheaven"]) {
+ const a = angleOf(chart, key);
+ if (a) ends.set(key, a.longitude);
+ }
+ }
+ return ends;
+ };
+ const ends1 = endsOf(points1, placed1, chart1, time1);
+ const ends2 = endsOf(points2, placed2, chart2, time2);
+ const lines = aspects
+ .filter((a) => WHEEL_ASPECTS.includes(a.aspect) && ends1.has(a.person1) && ends2.has(a.person2))
+ .map((a) => ({ ...a, strength: a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5 }))
+ .sort((x, y) => x.strength - y.strength);
+
+ return (
+
+
+ {name1} és {name2} képlete egy körön
+
+
+ Belül {name1} bolygói{time1 ? " és házai" : ""}, kívül {name2} bolygói; középen a kettejük közti főfényszögek.
+
+
+ {/* Zodiac ring */}
+
+ {SIGN_ORDER.map((sign, i) => {
+ const [gx, gy] = xy(i * 30 + 15, (R_OUT + R_ZOD) / 2, start);
+ return (
+
+
+
+ {SIGNS[sign].hu}
+ {SIGNS[sign].glyph}
+
+
+ );
+ })}
+ {Array.from({ length: 72 }, (_, k) => {
+ const d = k * 5;
+ const [x1, y1] = xy(d, R_ZOD, start);
+ const [x2, y2] = xy(d, R_ZOD + (d % 10 === 0 ? 8 : 5), start);
+ return ;
+ })}
+
+
+
+ {/* The first person's houses */}
+ {cusps.length === 12 && (
+
+
+ {cusps.map((c, i) => {
+ const isAngle = i % 3 === 0;
+ const [x1, y1] = xy(c.longitude, R_INNER, start);
+ const [x2, y2] = xy(c.longitude, isAngle ? R_OUT : R_MID, start);
+ const next = cusps[(i + 1) % 12].longitude;
+ const mid = c.longitude + ((next - c.longitude + 360) % 360) / 2;
+ const [nx, ny] = xy(mid, (R_HOUSE + R_INNER) / 2, start);
+ return (
+
+
+
+ {c.house}
+
+
+ );
+ })}
+ {ANGLE_LABELS.map(([key, label]) => {
+ const a = angleOf(chart1, key);
+ if (!a) return null;
+ const [x, y] = xy(a.longitude, R_LABEL, start);
+ return (
+
+
+ {name1}: {pointName(key)} {dms(a.degree_in_sign_dms)} {signName(a.sign)}
+
+ {label}
+
+ );
+ })}
+
+ )}
+
+ {/* Aspects between the two */}
+
+ {lines.map((a) => {
+ const [x1, y1] = xy(ends1.get(a.person1)!, R_INNER, start);
+ const [x2, y2] = xy(ends2.get(a.person2)!, R_INNER, start);
+ const s = a.strength;
+ return (
+
+
+ {name1} {pointName(a.person1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {name2} {pointName(a.person2)} (orbis{" "}
+ {orbText(a.orb)})
+
+
+ );
+ })}
+ {[...ends1].map(([id, lon]) => {
+ const [x, y] = xy(lon, R_INNER, start);
+ return ;
+ })}
+ {[...ends2].map(([id, lon]) => {
+ const [x, y] = xy(lon, R_INNER, start);
+ return ;
+ })}
+
+
+
+
+ );
+}
+
+/** Key to the two rings and the aspect lines. */
+export function SynastryLegend({ name1, name2, time1 }: { name1: string; name2: string; time1: boolean }) {
+ return (
+
+
+
+ belül: {name1}
+ {time1 ? " (bolygók és házak)" : ""}
+
+
+ kívül: {name2}
+
+
+
+ {[
+ ["trine", "trigon"],
+ ["sextile", "szextil"],
+ ["square", "kvadrát"],
+ ["opposition", "szembenállás"],
+ ].map(([aspect, label]) => (
+
+ {label}
+
+ ))}
+
+
A vonalak a két fél bolygói közti főfényszögek; vastagabb vonal: szorosabb fényszög. Az összes a táblázatokban.
+
+ );
+}
diff --git a/services/frontend/src/lib/synastry.ts b/services/frontend/src/lib/synastry.ts
new file mode 100644
index 0000000..8826e53
--- /dev/null
+++ b/services/frontend/src/lib/synastry.ts
@@ -0,0 +1,20 @@
+import type { ChartListItem, Synastry, SynastrySide } from "./types";
+
+/** Short name of one side of a comparison: "Én" for the own chart. */
+export function sideName(side: { label: string; is_primary?: boolean }): string {
+ return side.is_primary ? "Én" : side.label;
+}
+
+/** Whether a side's birth time is known (another user's chart has fewer fields). */
+export function sideTimeKnown(side: SynastrySide): boolean {
+ const chart = side.chart as SynastrySide["chart"] & { time_known?: boolean };
+ return side.highlights?.time_known ?? chart.time?.time_known ?? chart.time_known ?? false;
+}
+
+/** Name of a chart in the comparison list, from the user's chart list. */
+export function listName(ref: { id: string; label: string }, charts: ChartListItem[]): string {
+ const chart = charts.find((c) => c.id === ref.id);
+ return chart ? sideName(chart) : ref.label;
+}
+
+export type { Synastry };
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 726c021..9efdd4f 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -19,6 +19,25 @@ export interface Me {
analyses_left: UnitBalance;
birth_change: BirthChange;
persons: PersonSlots;
+ /** The unlimited package runs until then (null: none). */
+ unlimited_until: string | null;
+}
+
+/** A package from the catalog (`GET /v1/packages`). */
+export interface Package {
+ id: string;
+ name: string;
+ tagline: string;
+ tier: "main" | "addon";
+ price_huf: number;
+ natal: number;
+ synastry: number;
+ persons: number;
+ unlimited_months: number | null;
+ badge: string | null;
+ list_price_huf: number | null;
+ savings_percent: number | null;
+ per_analysis_huf: number | null;
}
/** How many persons the user may still add (`left`/`limit` null: no limit). */
@@ -50,7 +69,8 @@ export interface PublicConfig {
password_login: boolean;
password_min_length: number;
mock_payments: boolean;
- person_pack_size: number;
+ /** New detailed analyses a day with the unlimited package. */
+ unlimited_daily_limit: number;
}
export interface Position {
@@ -124,6 +144,67 @@ export interface ChartListItem {
created_at: string;
}
+/** An aspect between a point of the first chart and one of the second. */
+export interface InterAspect {
+ person1: string;
+ person2: string;
+ aspect: string;
+ nature: "harmonious" | "challenging" | "neutral";
+ major: boolean;
+ orb: number;
+ max_orb: number;
+}
+
+export interface HouseOverlay {
+ point: string;
+ sign: string;
+ house: number;
+}
+
+export interface SynastryResult {
+ aspects: InterAspect[];
+ house_overlays: {
+ /** The first person's points in the second person's houses (null: second time unknown). */
+ person1_in_person2: HouseOverlay[] | null;
+ person2_in_person1: HouseOverlay[] | null;
+ };
+ summary: {
+ aspect_count: number;
+ by_nature: { harmonious: number; challenging: number; neutral: number };
+ by_aspect: Record;
+ };
+ composite: {
+ method: string;
+ points: ChartPoint[];
+ angles: Record | null;
+ houses: { cusps: (Position & { house: number })[] } | null;
+ aspects: Aspect[];
+ };
+ warnings: string[];
+}
+
+/** One side of a comparison: the full chart when it is the viewer's own. */
+export type SynastrySide = Chart & { owned: true };
+
+export interface Synastry {
+ id: string;
+ owned: boolean;
+ chart1: SynastrySide;
+ chart2: SynastrySide;
+ synastry: SynastryResult;
+ created_at: string;
+}
+
+/** A comparison in the list (`GET /v1/synastries`). */
+export interface SynastryListItem {
+ id: string;
+ owned: boolean;
+ chart1: { id: string; label: string; owned: boolean };
+ chart2: { id: string; label: string; owned: boolean };
+ summary: SynastryResult["summary"] | null;
+ created_at: string;
+}
+
export interface Analysis {
id: string;
kind: "natal" | "synastry" | "summary";
@@ -147,6 +228,53 @@ export interface AdminUser {
last_login_at: string | null;
charts: number;
analyses_left: UnitBalance;
+ unlimited_until: string | null;
+}
+
+export type PromptKind = "summary" | "natal" | "synastry";
+
+export interface PromptRevision {
+ id: number;
+ custom: boolean;
+ /** `null`: the built-in text was restored. */
+ system: string | null;
+ created_at: string;
+ created_by: string | null;
+}
+
+/** An editable analysis system prompt (admin). */
+export interface AdminPrompt {
+ kind: PromptKind;
+ language: string;
+ /** The text in force. */
+ system: string;
+ custom: boolean;
+ updated_at: string | null;
+ updated_by: string | null;
+ default: string;
+ /** The fixed user message; `{chart data}` stands for the chart. */
+ user_template: string;
+ history: PromptRevision[];
+}
+
+/** A test run of a draft prompt on one of the admin's charts. */
+export interface PromptPreview {
+ id: string;
+ kind: PromptKind;
+ chart_id: string | null;
+ synastry_id: string | null;
+ language: string;
+ model: string;
+ status: "pending" | "running" | "done" | "failed";
+ content: AnalysisContent | null;
+ error: string | null;
+ model_used: string | null;
+ input_tokens: number | null;
+ output_tokens: number | null;
+ cost_usd: number | null;
+ created_at: string;
+ completed_at: string | null;
+ seconds: number | null;
}
export interface AnalysisContent {
diff --git a/services/worker/Cargo.toml b/services/worker/Cargo.toml
index a434915..454fcc6 100644
--- a/services/worker/Cargo.toml
+++ b/services/worker/Cargo.toml
@@ -8,6 +8,7 @@ publish.workspace = true
[dependencies]
db.workspace = true
+analysis-prompt.workspace = true
service-kit.workspace = true
anyhow.workspace = true
axum.workspace = true
diff --git a/services/worker/README.md b/services/worker/README.md
index 51ff64a..b9f0dd6 100644
--- a/services/worker/README.md
+++ b/services/worker/README.md
@@ -20,13 +20,14 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
-- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`src/analysis/prompt.rs`, `PROMPT_VERSION = v2`):
+- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v2`; ha a sor `prompt_version`-je `v2-r`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
- `title`, `summary`;
- `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`;
- `strengths`, `challenges`, `advice`;
- a rövid összefoglalónál (`summary`) csak `title` és egy 3–4 mondatos `summary`.
A worker a választ maga is ellenőrzi a sémán. Magyar szövegben az egyenes idézőjelpárokat („…”) alakra cseréli.
+- Ha nincs esedékes elemzés, a worker az admin próbafuttatásait írja (`prompt_previews`): a mentetlen system prompttal, egyetlen próbálkozással, egység nélkül. 30 nap után a takarítás törli őket.
- Eltárolja a ténylegesen válaszoló modellt (`model_used`; az `openrouter/auto` mögött ez más lehet), a tokenszámot és a költséget (`cost_usd`).
- **Átmeneti hiba** (hálózat, 429, 5xx, elfogyott OpenRouter-egyenleg, hibás vagy csonka válasz): újrapróbálja 30 mp, 2 perc, majd 8 perc múlva.
- **Végleges hiba** (például ismeretlen modell), vagy ha elfogyott a `MAX_ANALYSIS_ATTEMPTS` próbálkozás: az elemzés `failed` lesz, és az egység visszajár (`refund`, elemzésenként legfeljebb egyszer).
diff --git a/services/worker/src/analysis/mod.rs b/services/worker/src/analysis/mod.rs
index 8671425..300d558 100644
--- a/services/worker/src/analysis/mod.rs
+++ b/services/worker/src/analysis/mod.rs
@@ -5,6 +5,9 @@
//! through OpenRouter and stores the structured answer (`done`). Temporary
//! failures are retried with backoff; after the last attempt, or on a
//! permanent error, the analysis is `failed` and the unit is refunded.
+//!
+//! Admin test runs of an edited prompt (`prompt_previews`) go through the
+//! same loop when no analysis is due: one attempt, no credits, no retries.
pub mod compact;
pub mod openrouter;
@@ -37,12 +40,24 @@ pub struct Job {
pub attempts: i32,
}
+/// A test run of an edited system prompt on a chart.
+#[derive(Debug, sqlx::FromRow)]
+pub struct PreviewJob {
+ pub id: Uuid,
+ pub kind: String,
+ pub chart_id: Option,
+ pub synastry_id: Option,
+ pub language: String,
+ pub model: String,
+ pub system: String,
+}
+
pub struct Analyzer {
pub db: PgPool,
pub llm: OpenRouter,
pub max_attempts: i32,
pub concurrency: usize,
- /// Analyses being written right now (put back to `pending` on shutdown).
+ /// Analyses and previews being written right now (released on shutdown).
running: Mutex>,
}
@@ -77,34 +92,118 @@ impl Analyzer {
pub async fn prompt_for(&self, job: &Job) -> Result {
let kind = Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}"));
- let gone = || LlmError::Permanent("the chart was deleted".into());
let text = match kind {
- Kind::Natal | Kind::Summary => {
- let (chart,): (Value,) = sqlx::query_as("SELECT result FROM charts WHERE id = $1")
- .bind(job.chart_id)
- .fetch_optional(&self.db)
- .await
- .map_err(db_err)?
- .ok_or_else(gone)?;
- compact::natal(&chart)
- }
- Kind::Synastry => {
- let (result, chart1, chart2): (Value, Value, Value) = sqlx::query_as(
- "SELECT s.result, c1.result, c2.result FROM synastries s \
- JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.id = $1",
- )
- .bind(job.synastry_id)
+ Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
+ Kind::Synastry => self.synastry_text(job.synastry_id).await?,
+ };
+ let (base, revision) = prompt::split_version(&job.prompt_version);
+ if base != PROMPT_VERSION {
+ tracing::warn!(id = %job.id, requested = %job.prompt_version, current = PROMPT_VERSION, "prompt version differs");
+ }
+ // An admin-edited system prompt; NULL (or a missing row) means the built-in one.
+ let system: Option = match revision {
+ Some(id) => sqlx::query_scalar("SELECT system FROM prompt_revisions WHERE id = $1")
+ .bind(id)
.fetch_optional(&self.db)
.await
.map_err(db_err)?
- .ok_or_else(gone)?;
- compact::synastry(&chart1, &chart2, &result)
+ .flatten(),
+ None => None,
+ };
+ Ok(prompt::build(kind, &job.language, &text, system.as_deref()))
+ }
+
+ /// The compact text of a stored natal chart.
+ async fn natal_text(&self, chart_id: Option) -> Result {
+ let (chart,): (Value,) = sqlx::query_as("SELECT result FROM charts WHERE id = $1")
+ .bind(chart_id)
+ .fetch_optional(&self.db)
+ .await
+ .map_err(|e| LlmError::Transient(format!("database: {e}")))?
+ .ok_or_else(|| LlmError::Permanent("the chart was deleted".into()))?;
+ Ok(compact::natal(&chart))
+ }
+
+ /// The compact text of a stored synastry with its two charts.
+ async fn synastry_text(&self, synastry_id: Option) -> Result {
+ let (result, chart1, chart2): (Value, Value, Value) = sqlx::query_as(
+ "SELECT s.result, c1.result, c2.result FROM synastries s \
+ JOIN charts c1 ON c1.id = s.chart1_id JOIN charts c2 ON c2.id = s.chart2_id WHERE s.id = $1",
+ )
+ .bind(synastry_id)
+ .fetch_optional(&self.db)
+ .await
+ .map_err(|e| LlmError::Transient(format!("database: {e}")))?
+ .ok_or_else(|| LlmError::Permanent("the synastry was deleted".into()))?;
+ Ok(compact::synastry(&chart1, &chart2, &result))
+ }
+
+ /// Takes the oldest waiting prompt test run, if any.
+ pub async fn claim_preview(&self) -> Result, sqlx::Error> {
+ let job: Option = sqlx::query_as(
+ "UPDATE prompt_previews SET status = 'running', started_at = now() \
+ WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
+ ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
+ RETURNING id, kind, chart_id, synastry_id, language, model, system",
+ )
+ .fetch_optional(&self.db)
+ .await?;
+ if let Some(job) = &job {
+ self.running.lock().unwrap().insert(job.id);
+ }
+ Ok(job)
+ }
+
+ /// Writes one test run with the edited system prompt (a single attempt).
+ pub async fn handle_preview(&self, job: PreviewJob) {
+ let started = Instant::now();
+ let result = async {
+ let kind =
+ Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
+ let text = match kind {
+ Kind::Synastry => self.synastry_text(job.synastry_id).await?,
+ _ => self.natal_text(job.chart_id).await?,
+ };
+ let built = prompt::build(kind, &job.language, &text, Some(&job.system));
+ let mut c = self.llm.complete(&job.model, &built).await?;
+ prompt::polish(&job.language, &mut c.content);
+ Ok::<_, LlmError>(c)
+ }
+ .await;
+ let saved = match &result {
+ Ok(c) => {
+ sqlx::query(
+ "UPDATE prompt_previews SET status = 'done', content = $2, model_used = $3, input_tokens = $4, \
+ output_tokens = $5, cost_usd = $6, completed_at = now() WHERE id = $1 AND status = 'running'",
+ )
+ .bind(job.id)
+ .bind(&c.content)
+ .bind(&c.model)
+ .bind(c.input_tokens)
+ .bind(c.output_tokens)
+ .bind(c.cost_usd)
+ .execute(&self.db)
+ .await
+ }
+ Err(e) => {
+ sqlx::query(
+ "UPDATE prompt_previews SET status = 'failed', error = $2, completed_at = now() \
+ WHERE id = $1 AND status = 'running'",
+ )
+ .bind(job.id)
+ .bind(e.message())
+ .execute(&self.db)
+ .await
}
};
- if job.prompt_version != PROMPT_VERSION {
- tracing::warn!(id = %job.id, requested = %job.prompt_version, current = PROMPT_VERSION, "prompt version differs");
+ match (&result, saved) {
+ (_, Err(e)) => tracing::error!(id = %job.id, error = %e, "saving the prompt preview failed"),
+ (Ok(c), Ok(_)) => tracing::info!(
+ id = %job.id, model = %c.model, cost_usd = c.cost_usd, secs = started.elapsed().as_secs(), "prompt preview done"
+ ),
+ (Err(e), Ok(_)) => tracing::warn!(id = %job.id, error = %e.message(), "prompt preview failed"),
}
- Ok(prompt::build(kind, &job.language, &text))
+ self.running.lock().unwrap().remove(&job.id);
}
/// Writes one claimed analysis and records the outcome.
@@ -204,6 +303,14 @@ impl Analyzer {
.bind(STUCK_AFTER_MINUTES)
.execute(&self.db)
.await?;
+ // A test run is not retried: the admin can start it again.
+ sqlx::query(
+ "UPDATE prompt_previews SET status = 'failed', error = 'interrupted', completed_at = now() \
+ WHERE status = 'running' AND started_at < now() - make_interval(mins => $1)",
+ )
+ .bind(STUCK_AFTER_MINUTES)
+ .execute(&self.db)
+ .await?;
Ok(result.rows_affected())
}
@@ -224,6 +331,16 @@ impl Analyzer {
Ok(r) => tracing::info!(released = r.rows_affected(), "unfinished analyses put back in the queue"),
Err(e) => tracing::error!(error = %e, "releasing unfinished analyses"),
}
+ let result = sqlx::query(
+ "UPDATE prompt_previews SET status = 'failed', error = 'interrupted', completed_at = now() \
+ WHERE id = ANY($1) AND status = 'running'",
+ )
+ .bind(&ids)
+ .execute(&self.db)
+ .await;
+ if let Err(e) = result {
+ tracing::error!(error = %e, "releasing unfinished prompt previews");
+ }
}
}
@@ -254,7 +371,21 @@ pub async fn run(analyzer: Arc, poll: Duration, stop: watch::Receiver<
drop(permit);
});
}
- Ok(None) => break,
+ // No analysis is due: a prompt test run, if one waits.
+ Ok(None) => match analyzer.claim_preview().await {
+ Ok(Some(job)) => {
+ let analyzer = analyzer.clone();
+ tasks.spawn(async move {
+ analyzer.handle_preview(job).await;
+ drop(permit);
+ });
+ }
+ Ok(None) => break,
+ Err(e) => {
+ tracing::error!(error = %e, "claiming a prompt preview");
+ break;
+ }
+ },
Err(e) => {
tracing::error!(error = %e, "claiming an analysis");
break;
diff --git a/services/worker/src/analysis/openrouter.rs b/services/worker/src/analysis/openrouter.rs
index d06885c..7232971 100644
--- a/services/worker/src/analysis/openrouter.rs
+++ b/services/worker/src/analysis/openrouter.rs
@@ -55,8 +55,13 @@ impl Serialize for Ordered<'_> {
fn serialize(&self, serializer: S) -> Result {
match self.0 {
Value::Object(map) => {
- let order: Vec<&str> =
- map.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
+ let order: Vec<&str> = map
+ .get("required")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ .collect();
let mut out = serializer.serialize_map(Some(map.len()))?;
for (key, value) in map {
match (key.as_str(), value) {
diff --git a/services/worker/src/analysis/prompt.rs b/services/worker/src/analysis/prompt.rs
index 238d4fc..36ae1c0 100644
--- a/services/worker/src/analysis/prompt.rs
+++ b/services/worker/src/analysis/prompt.rs
@@ -1,338 +1,3 @@
-//! Prompts and output schemas of the analyses (prompt version [`PROMPT_VERSION`]).
-//!
-//! The model answers with one JSON object (OpenRouter structured output);
-//! [`validate`] checks it against the same schema before it is stored.
+//! Prompts and answer schemas live in the shared `analysis-prompt` crate.
-use serde_json::{Value, json};
-
-/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
-pub const PROMPT_VERSION: &str = "v2";
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Kind {
- Natal,
- Synastry,
- /// A free teaser of a natal chart: a title and a few sentences.
- Summary,
-}
-
-impl Kind {
- pub fn parse(s: &str) -> Option {
- match s {
- "natal" => Some(Kind::Natal),
- "synastry" => Some(Kind::Synastry),
- "summary" => Some(Kind::Summary),
- _ => None,
- }
- }
-}
-
-pub struct Prompt {
- pub system: String,
- pub user: String,
- pub schema_name: &'static str,
- pub schema: Value,
-}
-
-/// (key, what the section covers) in reading order.
-const NATAL_SECTIONS: [(&str, &str); 6] = [
- ("personality", "Core identity: the Sun, Moon, Ascendant and chart ruler read together"),
- ("emotions", "Emotional needs, security and inner life (Moon, 4th house, water emphasis)"),
- ("mind", "Thinking, communication and learning (Mercury, 3rd and 9th houses)"),
- ("love", "Love, attraction and relationships (Venus, Mars, 5th and 7th houses, Descendant)"),
- ("work", "Calling, career, money and daily work (MC, 10th, 2nd and 6th houses, Saturn, Jupiter)"),
- (
- "growth",
- "Main inner tensions, life lessons and the path of growth (tight squares and oppositions, Saturn, Chiron, Nodes)",
- ),
-];
-
-const SYNASTRY_SECTIONS: [(&str, &str); 5] = [
- ("attraction", "What draws them together: Sun, Moon, Venus, Mars and Ascendant contacts"),
- ("communication", "How they think and talk together (Mercury contacts, air emphasis, 3rd house overlays)"),
- ("emotional_bond", "Emotional closeness, safety and care (Moon contacts, 4th and 8th house overlays)"),
- ("friction", "Where they rub against each other and how to handle it (challenging aspects, Saturn, Pluto, Mars)"),
- ("long_term", "Long-term potential and shared purpose, including the composite chart"),
-];
-
-fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
- match kind {
- Kind::Natal => &NATAL_SECTIONS,
- Kind::Synastry => &SYNASTRY_SECTIONS,
- Kind::Summary => &[],
- }
-}
-
-/// The JSON schema of the answer (strict mode: every property required).
-pub fn schema(kind: Kind) -> Value {
- if kind == Kind::Summary {
- return json!({
- "type": "object",
- "additionalProperties": false,
- "required": ["title", "summary"],
- "properties": {
- "title": {"type": "string", "description": "Short, evocative title for this chart (at most 6 words)"},
- "summary": {"type": "string", "description": "3-4 sentences, 60-100 words, one paragraph"}
- }
- });
- }
- let mut props = serde_json::Map::new();
- for (key, about) in sections(kind) {
- props.insert(
- (*key).into(),
- json!({
- "type": "object",
- "description": about,
- "additionalProperties": false,
- "required": ["title", "body"],
- "properties": {
- "title": {"type": "string", "description": "Short, specific section title (not just the topic name)"},
- "body": {"type": "string", "description": "2-4 paragraphs separated by a blank line"}
- }
- }),
- );
- }
- let keys: Vec<&str> = sections(kind).iter().map(|(k, _)| *k).collect();
- json!({
- "type": "object",
- "additionalProperties": false,
- "required": ["title", "summary", "sections", "strengths", "challenges", "advice"],
- "properties": {
- "title": {"type": "string", "description": "Short, evocative title for this analysis (at most 8 words)"},
- "summary": {"type": "string", "description": "3-4 sentence overview"},
- "sections": {"type": "object", "additionalProperties": false, "required": keys, "properties": props},
- "strengths": {"type": "array", "items": {"type": "string"}, "description": "3-5 key strengths, one sentence each"},
- "challenges": {"type": "array", "items": {"type": "string"}, "description": "3-5 key challenges, one sentence each"},
- "advice": {"type": "string", "description": "A closing, encouraging paragraph with concrete guidance"}
- }
- })
-}
-
-const HUNGARIAN_STYLE: &str = "\
-Write natural, idiomatic Hungarian, as a native Hungarian author would; it must not read like a translation from English. \
-Use correct Hungarian suffixes and vowel harmony, Hungarian quotation marks („…”) and the en dash (–). \
-Use the usual Hungarian astrological terms:
-- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
-- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
-Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
-- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció);
-- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
-Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
-- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
-
-fn language_name(language: &str) -> &'static str {
- match language {
- "hu" => "Hungarian",
- _ => "English",
- }
-}
-
-fn rules(kind: Kind, language: &str) -> String {
- let (role, reader) = match kind {
- Kind::Natal => (
- "a personal natal chart interpretation",
- "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
- ),
- Kind::Summary => (
- "a short free summary of a natal chart (a teaser shown before the detailed, paid analysis)",
- "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
- ),
- Kind::Synastry => (
- "a relationship (synastry) interpretation for two people",
- "Write for both people at once, in the informal second person plural (in Hungarian: \"ti\", \"kettőtök\"). \
- When you must tell them apart, call them Person 1 and Person 2 (in Hungarian: \"az első fél\" and \"a második fél\"). \
- Do not assume their genders or the type of relationship.",
- ),
- };
- let mut text = format!(
- "You are an experienced, warm and psychologically minded astrologer. You write {role} for the Sorsfonalak app.
-
-Write in {lang}.
-
-Rules:
-- Base every statement on the chart data given. Never invent positions, aspects or houses that are not listed.
-- When you interpret a placement, name its astrological basis in a short clause, but keep the focus on the person, not on jargon.
-- Synthesize: weave signs, houses, aspects and rulers into one coherent portrait; show how tensions can be integrated. \
-Give the most weight to the Sun, Moon, Ascendant, chart ruler, tight aspects (orb under 3°) and strong emphases or gaps in elements and modalities.
-- If a birth time is unknown, do not mention houses, the Ascendant or the Midheaven for that chart, and be careful with the Moon's sign.
-- {reader}
-- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \
-and no medical, legal or financial advice.
-- Avoid generic horoscope clichés and filler: every paragraph must say something specific to this chart.
-- Texts are plain paragraphs separated by a blank line, without headings or lists inside; **bold** may be used sparingly.
-- {length}
-- Answer with a single JSON object that matches the given schema, and nothing else.",
- lang = language_name(language),
- length = match kind {
- Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
- (if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
- a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
- no sales talk, and do not mention a longer analysis.",
- _ => "Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.",
- },
- );
- if language == "hu" {
- text.push_str("\n\n");
- text.push_str(HUNGARIAN_STYLE);
- }
- text
-}
-
-pub fn build(kind: Kind, language: &str, chart_text: &str) -> Prompt {
- let mut user = String::from("Chart data:\n\n");
- user.push_str(chart_text);
- if kind == Kind::Summary {
- user.push_str("\nWrite the short summary now.");
- } else {
- user.push_str("\nSections to write, in this order:\n");
- for (key, about) in sections(kind) {
- user.push_str(&format!("- {key}: {about}\n"));
- }
- user.push_str("\nWrite the analysis now.");
- }
- Prompt {
- system: rules(kind, language),
- user,
- schema_name: match kind {
- Kind::Natal => "natal_analysis",
- Kind::Synastry => "synastry_analysis",
- Kind::Summary => "chart_summary",
- },
- schema: schema(kind),
- }
-}
-
-/// Checks an answer against our schema subset (objects with required
-/// properties, strings with at least three letters, string arrays with at
-/// least two items). A placeholder such as "x" counts as missing.
-pub fn validate(schema: &Value, value: &Value) -> Result<(), String> {
- fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> {
- match schema["type"].as_str() {
- Some("object") => {
- let obj = value.as_object().ok_or_else(|| format!("{path}: expected an object"))?;
- for key in schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str) {
- let child = obj.get(key).ok_or_else(|| format!("{path}.{key}: missing"))?;
- walk(&schema["properties"][key], child, &format!("{path}.{key}"))?;
- }
- Ok(())
- }
- Some("array") => {
- let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?;
- if items.len() < 2 {
- return Err(format!("{path}: too few items"));
- }
- items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]")))
- }
- Some("string") => match value.as_str() {
- Some(s) if s.chars().filter(|c| c.is_alphabetic()).nth(2).is_some() => Ok(()),
- _ => Err(format!("{path}: expected a non-empty string")),
- },
- _ => Ok(()),
- }
- }
- walk(schema, value, "$")
-}
-
-/// Fixes typography the models often get wrong. In Hungarian, pairs of
-/// straight double quotes become „…” (only when they pair up evenly).
-pub fn polish(language: &str, content: &mut Value) {
- fn hungarian_quotes(text: &str) -> Option {
- if !text.contains('"') || !text.matches('"').count().is_multiple_of(2) {
- return None;
- }
- let mut open = true;
- Some(
- text.chars()
- .map(|c| match c {
- '"' => {
- let q = if open { '„' } else { '”' };
- open = !open;
- q
- }
- c => c,
- })
- .collect(),
- )
- }
- match content {
- Value::String(s) if language == "hu" => {
- if let Some(fixed) = hungarian_quotes(s) {
- *s = fixed;
- }
- }
- Value::Array(items) => items.iter_mut().for_each(|v| polish(language, v)),
- Value::Object(map) => map.values_mut().for_each(|v| polish(language, v)),
- _ => {}
- }
-}
-
-/// The analysis as Markdown (for reading and comparing outputs).
-pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String {
- let (strengths, challenges, advice) = if language == "hu" {
- ("Erősségek", "Kihívások", "Útravaló")
- } else {
- ("Strengths", "Challenges", "Advice")
- };
- let mut md =
- format!("# {}\n\n_{}_\n\n", content["title"].as_str().unwrap_or(""), content["summary"].as_str().unwrap_or(""));
- if kind == Kind::Summary {
- return md;
- }
- for (key, _) in sections(kind) {
- let s = &content["sections"][*key];
- md.push_str(&format!("## {}\n\n{}\n\n", s["title"].as_str().unwrap_or(key), s["body"].as_str().unwrap_or("")));
- }
- for (title, key) in [(strengths, "strengths"), (challenges, "challenges")] {
- md.push_str(&format!("## {title}\n\n"));
- for item in content[key].as_array().into_iter().flatten().filter_map(Value::as_str) {
- md.push_str(&format!("- {item}\n"));
- }
- md.push('\n');
- }
- md.push_str(&format!("## {advice}\n\n{}\n", content["advice"].as_str().unwrap_or("")));
- md
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn summary_prompt_is_short() {
- let p = build(Kind::Summary, "hu", "SUN: Cancer");
- assert_eq!(p.schema_name, "chart_summary");
- assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező"));
- assert!(!p.user.contains("Sections to write"));
- assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(()));
- assert!(validate(&p.schema, &json!({"title": "Érzékeny mag"})).is_err());
- let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."}));
- assert_eq!(md, "# Cím\n\n_Szöveg._\n\n");
- }
-
- #[test]
- fn validate_rejects_placeholder_titles() {
- let schema = schema(Kind::Synastry);
- let section = json!({"title": "Rák-szívek", "body": "Két bekezdés szöveg."});
- let mut answer = json!({
- "title": "Két Rák-szív", "summary": "Összefoglaló.", "advice": "Útravaló.",
- "strengths": ["Egyik erősség.", "Másik erősség."], "challenges": ["Egy kihívás.", "Még egy."],
- "sections": {"attraction": section, "communication": section, "emotional_bond": section,
- "friction": section, "long_term": section},
- });
- assert_eq!(validate(&schema, &answer), Ok(()));
- answer["sections"]["attraction"]["title"] = json!("x");
- assert_eq!(validate(&schema, &answer), Err("$.sections.attraction.title: expected a non-empty string".into()));
- }
-
- #[test]
- fn polish_turns_straight_quotes_hungarian() {
- let mut v = json!({"a": "a \"hazai pálya\" és a \"sorok\"", "b": ["egy \" pár nélkül"], "c": {"d": "nincs"}});
- polish("hu", &mut v);
- assert_eq!(v["a"], "a „hazai pálya” és a „sorok”");
- assert_eq!(v["b"][0], "egy \" pár nélkül");
- assert_eq!(v["c"]["d"], "nincs");
- let mut en = json!({"a": "the \"home\" ground"});
- polish("en", &mut en);
- assert_eq!(en["a"], "the \"home\" ground");
- }
-}
+pub use analysis_prompt::*;
diff --git a/services/worker/src/cleanup.rs b/services/worker/src/cleanup.rs
index f5d0da2..3a29a2f 100644
--- a/services/worker/src/cleanup.rs
+++ b/services/worker/src/cleanup.rs
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
-const STATEMENTS: [(&str, &str); 4] = [
+const STATEMENTS: [(&str, &str); 5] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -18,6 +18,7 @@ const STATEMENTS: [(&str, &str); 4] = [
OR failed_at < now() - interval '30 days'",
),
("invites", "DELETE FROM synastry_invites WHERE accepted_at IS NULL AND expires_at < now() - interval '30 days'"),
+ ("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
];
pub async fn run_once(db: &PgPool) -> Result, sqlx::Error> {
diff --git a/services/worker/src/compare.rs b/services/worker/src/compare.rs
index 93c5b27..30082f8 100644
--- a/services/worker/src/compare.rs
+++ b/services/worker/src/compare.rs
@@ -83,7 +83,7 @@ pub async fn main(args: Vec) -> anyhow::Result<()> {
prompt::Kind::Synastry => compact::synastry(&input["person1"], &input["person2"], &input),
_ => compact::natal(&input),
};
- let built = prompt::build(args.kind, &args.language, &data);
+ let built = prompt::build(args.kind, &args.language, &data, None);
std::fs::create_dir_all(&args.out)?;
std::fs::write(
diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs
index 954a6a7..5d3526c 100644
--- a/services/worker/src/tests.rs
+++ b/services/worker/src/tests.rs
@@ -175,7 +175,10 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
sqlx::query("UPDATE email_outbox SET sent_at = now() WHERE id = $1").bind(recent).execute(&db).await.unwrap();
let deleted = crate::cleanup::run_once(&db).await.unwrap();
- assert_eq!(deleted, vec![("sessions", 1), ("auth_tokens", 0), ("emails", 1), ("invites", 0)]);
+ assert_eq!(
+ deleted,
+ vec![("sessions", 1), ("auth_tokens", 0), ("emails", 1), ("invites", 0), ("prompt_previews", 0)]
+ );
let (left,): (Vec,) =
sqlx::query_as("SELECT array_agg(id ORDER BY id) FROM email_outbox").fetch_one(&db).await.unwrap();
assert_eq!(left, vec![recent, unsent]);
@@ -369,6 +372,107 @@ mod analyses {
}
}
+ #[sqlx::test(migrator = "db::MIGRATOR")]
+ async fn uses_the_admin_edited_system_prompt(db: PgPool) {
+ let s = setup(&db).await;
+ let (revision,): (i64,) = sqlx::query_as(
+ "INSERT INTO prompt_revisions (kind, language, system) VALUES ('natal', 'hu', 'Saját szabályok.') RETURNING id",
+ )
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ // a newer revision is not used: the analysis records the one it was requested with
+ sqlx::query("INSERT INTO prompt_revisions (kind, language, system) VALUES ('natal', 'hu', 'Újabb.')")
+ .execute(&db)
+ .await
+ .unwrap();
+ let id = request_analysis(&db, &s).await;
+ sqlx::query("UPDATE analyses SET prompt_version = $1 WHERE id = $2")
+ .bind(format!("v1-r{revision}"))
+ .bind(id)
+ .execute(&db)
+ .await
+ .unwrap();
+ let (fake, url) = fake_openrouter(vec![reply(&content(Kind::Natal))]).await;
+ assert!(run_once(&analyzer(&db, &url)).await);
+ assert_eq!(row(&db, id).await.0, "done");
+ let requests = fake.requests.lock().unwrap();
+ assert_eq!(requests[0]["messages"][0]["content"], "Saját szabályok.");
+ assert!(requests[0]["messages"][1]["content"].as_str().unwrap().contains("- personality: "));
+ }
+
+ #[sqlx::test(migrator = "db::MIGRATOR")]
+ async fn prompt_previews_run_after_analyses(db: PgPool) {
+ let s = setup(&db).await;
+ let preview = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO prompt_previews (id, kind, chart_id, language, model, system, created_by) \
+ VALUES ($1, 'summary', $2, 'hu', 'test/summary', 'Próba szabályok.', $3)",
+ )
+ .bind(preview)
+ .bind(s.chart)
+ .bind(s.user)
+ .execute(&db)
+ .await
+ .unwrap();
+ let analysis = request_analysis(&db, &s).await;
+ let (fake, url) = fake_openrouter(vec![
+ reply(&content(Kind::Natal)),
+ reply(&json!({"title": "Érzékeny mag", "summary": "Rövid összefoglaló szöveg."})),
+ (500, json!({})),
+ ])
+ .await;
+ let a = analyzer(&db, &url);
+
+ // the analysis goes first; the preview only when nothing else is due
+ let job = a.claim().await.unwrap().expect("the analysis");
+ assert_eq!(job.id, analysis);
+ a.handle(job).await;
+ assert!(a.claim().await.unwrap().is_none());
+ let job = a.claim_preview().await.unwrap().expect("the preview");
+ a.handle_preview(job).await;
+ let (status, title, model, credits): (String, Option, Option, i64) = sqlx::query_as(
+ "SELECT status, content->>'title', model_used, \
+ (SELECT count(*) FROM credit_ledger WHERE user_id = p.created_by) \
+ FROM prompt_previews p WHERE id = $1",
+ )
+ .bind(preview)
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!((status.as_str(), title.is_some(), model.as_deref()), ("done", true, Some("test/model-2026")));
+ let before = credits;
+ {
+ let requests = fake.requests.lock().unwrap();
+ assert_eq!(requests[1]["model"], "test/summary");
+ assert_eq!(requests[1]["messages"][0]["content"], "Próba szabályok.");
+ }
+
+ // one attempt only: an error fails the preview at once, without refunds
+ let second = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO prompt_previews (id, kind, chart_id, language, model, system, created_by) \
+ VALUES ($1, 'natal', $2, 'hu', 'test/model', 'Másik.', $3)",
+ )
+ .bind(second)
+ .bind(s.chart)
+ .bind(s.user)
+ .execute(&db)
+ .await
+ .unwrap();
+ a.handle_preview(a.claim_preview().await.unwrap().unwrap()).await;
+ let (status, error, credits): (String, Option, i64) = sqlx::query_as(
+ "SELECT status, error, (SELECT count(*) FROM credit_ledger WHERE user_id = p.created_by) \
+ FROM prompt_previews p WHERE id = $1",
+ )
+ .bind(second)
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!((status.as_str(), error.is_some(), credits), ("failed", true, before));
+ assert!(a.claim_preview().await.unwrap().is_none());
+ }
+
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn retries_bad_answers_then_fails_and_refunds(db: PgPool) {
let s = setup(&db).await;
@@ -463,11 +567,31 @@ mod analyses {
assert!(run_once(&a).await);
assert_eq!(row(&db, id).await.0, "done");
+ {
+ let requests = fake.requests.lock().unwrap();
+ let user = requests[0]["messages"][1]["content"].as_str().unwrap();
+ assert!(user.starts_with("Chart data:\n\nSYNASTRY") && user.contains("- attraction: "));
+ assert!(requests[0]["messages"][0]["content"].as_str().unwrap().contains("Write in English."));
+ assert!(!user.contains("Szeged") && !user.contains("Pécs"));
+ }
+
+ // a prompt test run on the comparison
+ sqlx::query(
+ "INSERT INTO prompt_previews (id, kind, synastry_id, language, model, system, created_by) \
+ VALUES ($1, 'synastry', $2, 'hu', 'test/model', 'Kapcsolati próba.', $3)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(synastry)
+ .bind(s.user)
+ .execute(&db)
+ .await
+ .unwrap();
+ a.handle_preview(a.claim_preview().await.unwrap().expect("the preview")).await;
+ let (status,): (String,) = sqlx::query_as("SELECT status FROM prompt_previews").fetch_one(&db).await.unwrap();
+ assert_eq!(status, "done");
let requests = fake.requests.lock().unwrap();
- let user = requests[0]["messages"][1]["content"].as_str().unwrap();
- assert!(user.starts_with("Chart data:\n\nSYNASTRY") && user.contains("- attraction: "));
- assert!(requests[0]["messages"][0]["content"].as_str().unwrap().contains("Write in English."));
- assert!(!user.contains("Szeged") && !user.contains("Pécs"));
+ assert_eq!(requests[1]["messages"][0]["content"], "Kapcsolati próba.");
+ assert!(requests[1]["messages"][1]["content"].as_str().unwrap().contains("SYNASTRY"));
}
#[test]