+
+ Ajándék csomag
+ setPkg(e.target.value)}>
+ nincs
+ {(packages ?? []).map((p) => (
+
+ {p.name}
+
+ ))}
+
+
A levél nyelve
setLocale(e.target.value)}>
@@ -175,6 +189,12 @@ function InviteForm({ onSent }: { onSent: () => Promise }) {
+ {pkg && (
+
+ Minden meghívott kap egy promókódot erre a csomagra. A levélben benne lesz, és a regisztrációkor magától
+ beváltódik. A meghívó visszavonása a kódot is visszavonja.
+
+ )}
{error && (
{error}
@@ -187,18 +207,19 @@ function InviteForm({ onSent }: { onSent: () => Promise }) {
{r.email}: {RESULT[r.status]}
+ {r.promo_code && {r.promo_code}}
{r.url && }
))}
)}
-
+
);
}
/** The invitation e-mail as the recipient sees it, and a test copy to the admin. */
-function MailPreview({ message, locale }: { message: string; locale: string }) {
+function MailPreview({ message, locale, pkg }: { message: string; locale: string; pkg: string }) {
const [mail, setMail] = useState<{ subject: string; html: string; text: string } | null>(null);
const [view, setView] = useState<"html" | "text">("html");
const [busy, setBusy] = useState(false);
@@ -210,7 +231,7 @@ function MailPreview({ message, locale }: { message: string; locale: string }) {
try {
const res = await api<{ subject: string; html: string; text: string; sent_to: string | null }>(
"/admin/invitations/preview",
- { body: { message: message.trim() || null, locale, send_to_me: sendToMe } },
+ { body: { message: message.trim() || null, locale, send_to_me: sendToMe, package: pkg || null } },
);
setMail(res);
if (res.sent_to) setNote({ ok: true, text: `Tesztlevél a sorban: ${res.sent_to}. A linkjei nem működnek.` });
@@ -337,6 +358,12 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
{STATUS[i.status]}
{i.accepted_by && {i.accepted_by}
}
+ {i.package && (
+
+ Ajándék: {i.package.name ?? i.package.id}
+ {i.package.redeemed_at ? " (beváltva)" : ""}
+
+ )}
diff --git a/services/frontend/src/app/bevaltas/page.tsx b/services/frontend/src/app/bevaltas/page.tsx
index 3e6ab0e..78590c2 100644
--- a/services/frontend/src/app/bevaltas/page.tsx
+++ b/services/frontend/src/app/bevaltas/page.tsx
@@ -17,8 +17,8 @@ export default async function RedeemPage({ searchParams }: Props) {
Promókód
Promókód beváltása
- Írd be a kapott kódot. A hozzá tartozó csomag azonnal a tiéd, az elemzései nem járnak le. Egy kód egyszer
- váltható be.
+ Írd be a kapott kódot. Az egyenlegedet azonnal feltöltjük a csomag szintjéig: amit már elhasználtál belőle,
+ visszakapod, ami ennél több van, megmarad. Egy kód egyszer váltható be.
diff --git a/services/frontend/src/components/RedeemCode.tsx b/services/frontend/src/components/RedeemCode.tsx
index cc89021..8225aae 100644
--- a/services/frontend/src/components/RedeemCode.tsx
+++ b/services/frontend/src/components/RedeemCode.tsx
@@ -12,22 +12,42 @@ function format(input: string): string {
return clean.match(/.{1,4}/g)?.join("-") ?? "";
}
-/** Redeeming a promo code: the package arrives at once. */
+const UNITS: Record = {
+ natal: "képletelemzés",
+ synastry: "kapcsolati elemzés",
+ forecast: "éves előrejelzés",
+ person: "személyhely",
+ question: "kérdés",
+};
+
+/** "+2 képletelemzés, +3 kérdés" */
+function addedText(added: Record): string {
+ return Object.entries(added)
+ .map(([unit, n]) => `+${n} ${UNITS[unit] ?? unit}`)
+ .join(", ");
+}
+
+/**
+ * Redeeming a promo code. It fills the units up to the package's amounts
+ * (used ones come back, more than that stays).
+ */
export function RedeemCode({ initial = "", compact = false }: { initial?: string; compact?: boolean }) {
const router = useRouter();
const id = useId();
const [code, setCode] = useState(format(initial));
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
- const [got, setGot] = useState(null);
+ const [got, setGot] = useState<{ name: string; added: string } | null>(null);
async function redeem(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
- const r = await api<{ package: { name: string } }>("/promo-codes/redeem", { body: { code } });
- setGot(r.package.name);
+ const r = await api<{ package: { name: string }; added: Record }>("/promo-codes/redeem", {
+ body: { code },
+ });
+ setGot({ name: r.package.name, added: addedText(r.added ?? {}) });
setCode("");
router.refresh();
} catch (err) {
@@ -67,8 +87,8 @@ export function RedeemCode({ initial = "", compact = false }: { initial?: string
{error && {error}
}
{got && (
- Megkaptad: {got} . Az elemzéseid már felhasználhatók,{" "}
- indulhat a képleted.
+ Beváltva: {got.name} . Feltöltöttük az egyenlegedet: {got.added}.{" "}
+ Tovább a képletedhez
)}
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index b0aa94b..3d36aa8 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -413,6 +413,8 @@ export interface AdminInvitation {
mail: "sent" | "queued" | "failed" | "archived";
mail_error: string | null;
can_resend: boolean;
+ /** The package it comes with (a promo code, redeemed at sign-up). */
+ package: { id: string; name: string | null; code: string | null; redeemed_at: string | null } | null;
}
export interface WaitlistEntry {
@@ -428,6 +430,8 @@ export interface InvitationResult {
status: "invited" | "invalid" | "already_user" | "already_invited" | "opted_out";
id?: string;
url?: string;
+ /** The promo code of the package sent with it. */
+ promo_code?: string | null;
}
/** A calculated year in a list (`GET /v1/charts/{id}/forecasts`). */
From 4f09aac3f5748f5d6d4ec7b9dcd8b00b9c84ed83 Mon Sep 17 00:00:00 2001
From: feco
Date: Thu, 19 Nov 2026 10:12:51 +0000
Subject: [PATCH 3/6] Inviting a person to compare charts
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The new person page offers 'Adatok megadása' (typed-in data, uses a slot)
or 'Meghívom': a 'how compatible are we?' link with an optional name,
e-mail and message (no links, 300 chars), shareable by copy, the phone's
share menu, WhatsApp or Facebook. With an address we e-mail it too (at most
10 a day per user, opted-out addresses skipped, unsubscribe link included).
The invitee lands on /meghivas/, signs in, gives their own birth data
if needed and gets the comparison; the inviter is told and lists pending
invitations (revocable) on the persons page. No person slot is used.
Also: the accepted e-mail links to /osszevetesek/, and the cross grid no
longer breaks on another user's chart (no highlights there).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
---
crates/db/migrations/0024_person_invites.sql | 7 +
crates/email-templates/src/lib.rs | 87 +++++++++
docs/szemely-meghivas.md | 30 ++++
services/backend/src/routes/invitations.rs | 11 +-
services/backend/src/routes/synastries.rs | 76 +++++++-
services/backend/src/tests.rs | 61 +++++++
services/frontend/src/app/globals.css | 16 ++
.../src/app/meghivas/[token]/AcceptInvite.tsx | 63 +++++++
.../src/app/meghivas/[token]/page.tsx | 95 ++++++++++
services/frontend/src/app/szemelyek/page.tsx | 27 +--
.../src/app/szemelyek/uj/NewPersonChooser.tsx | 77 ++++++++
.../frontend/src/app/szemelyek/uj/page.tsx | 28 +--
.../frontend/src/components/InvitePerson.tsx | 170 ++++++++++++++++++
.../src/components/PendingInvites.tsx | 85 +++++++++
.../src/components/SynastryTables.tsx | 3 +-
services/frontend/src/lib/types.ts | 23 +++
16 files changed, 820 insertions(+), 39 deletions(-)
create mode 100644 crates/db/migrations/0024_person_invites.sql
create mode 100644 docs/szemely-meghivas.md
create mode 100644 services/frontend/src/app/meghivas/[token]/AcceptInvite.tsx
create mode 100644 services/frontend/src/app/meghivas/[token]/page.tsx
create mode 100644 services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
create mode 100644 services/frontend/src/components/InvitePerson.tsx
create mode 100644 services/frontend/src/components/PendingInvites.tsx
diff --git a/crates/db/migrations/0024_person_invites.sql b/crates/db/migrations/0024_person_invites.sql
new file mode 100644
index 0000000..d94f839
--- /dev/null
+++ b/crates/db/migrations/0024_person_invites.sql
@@ -0,0 +1,7 @@
+-- "How compatible are we?" invitations from the new person page: who it is
+-- for (the inviter's own name for them) and, if the inviter asked us to
+-- e-mail it, the address.
+ALTER TABLE synastry_invites
+ ADD COLUMN label text CHECK (char_length(label) <= 80),
+ ADD COLUMN invitee_email text;
+CREATE INDEX synastry_invites_emailed_idx ON synastry_invites (inviter_id, created_at) WHERE invitee_email IS NOT NULL;
diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs
index 320fbf6..2f54b89 100644
--- a/crates/email-templates/src/lib.rs
+++ b/crates/email-templates/src/lib.rs
@@ -158,6 +158,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result invitation(lang, payload, url)?,
+ ("synastry_invite", _) => synastry_invite(lang, payload, url)?,
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
Ok(content.render(lang))
@@ -282,6 +283,79 @@ fn name(payload: &Value, field: &str) -> Option {
(!name.is_empty()).then(|| name.to_owned())
}
+/// A user invites someone to compare their charts ("how compatible are we?").
+fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result {
+ let inviter = name(payload, "inviter_name");
+ let message = message(payload);
+ let until =
+ payload["expires_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("expires_on"))?;
+ let until_hu = until.trim_end_matches('.');
+ let unsubscribe_url = field(payload, "unsubscribe_url")?;
+ let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
+ Ok(match lang {
+ Lang::Hu => {
+ let who = inviter.clone().unwrap_or_else(|| "Valaki".into());
+ Content {
+ subject: format!("{who} kíváncsi, mennyire illetek össze"),
+ preheader: Some(format!(
+ "Születési képletek összevetése a Sorsfonalakon. A meghívó {until_hu}-ig érvényes."
+ )),
+ greeting: "Szia!".into(),
+ intro: format!(
+ "{who} szeretné összevetni a születési képleteteket a Sorsfonalakon, és megnézni, mennyire illetek össze."
+ ),
+ quote: message,
+ points: Some((
+ "Mit kapsz?",
+ vec![
+ "a saját születési képleted kiszámolva és megrajzolva, egy rövid elemzéssel, ingyen,",
+ "a kettőtök összevetését: hol erős és hol kényes a kapcsolatotok.",
+ ],
+ )),
+ button: "Megnézem",
+ url,
+ note: format!(
+ "A meghívó {until_hu}-ig érvényes. Google-fiókkal lépsz be. A születési adataidat {who} nem látja, csak az összevetést."
+ ),
+ reason: Some(format!(
+ "Ezt a levelet azért kaptad, mert {who} megadta az e-mail-címed a Sorsfonalakon."
+ )),
+ unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)),
+ unsubscribe_post_url: Some(unsubscribe_post_url),
+ }
+ }
+ Lang::En => {
+ let who = inviter.clone().unwrap_or_else(|| "Someone".into());
+ Content {
+ subject: format!("{who} wonders how well you match"),
+ preheader: Some(format!(
+ "Comparing birth charts on Sorsfonalak. The invitation is valid until {until}."
+ )),
+ greeting: "Hi,".into(),
+ intro: format!(
+ "{who} would like to compare your birth charts on Sorsfonalak and see how well you match."
+ ),
+ quote: message,
+ points: Some((
+ "What you get:",
+ vec![
+ "your own birth chart, calculated and drawn, with a short reading, for free,",
+ "the comparison of the two of you: where your relationship is strong and where it is delicate.",
+ ],
+ )),
+ button: "Take a look",
+ url,
+ note: format!(
+ "The invitation is valid until {until}. You sign in with Google. {who} does not see your birth data, only the comparison."
+ ),
+ reason: Some(format!("You got this e-mail because {who} entered your address on Sorsfonalak.")),
+ unsubscribe: Some(("No more invitations, please", unsubscribe_url)),
+ unsubscribe_post_url: Some(unsubscribe_post_url),
+ }
+ }
+ })
+}
+
/// The personal message of an invitation: line breaks kept, other control characters dropped.
fn message(payload: &Value) -> Option {
let text: String =
@@ -465,6 +539,19 @@ mod tests {
})
}
+ #[test]
+ fn synastry_invite_names_the_inviter() {
+ let hu = render("synastry_invite", "hu", &invitation_payload()).unwrap();
+ assert_eq!(hu.subject, "Kata kíváncsi, mennyire illetek össze");
+ assert!(hu.text.contains("> Gyere, nézd meg!"));
+ assert!(hu.text.contains("A meghívó 2026. december 17-ig érvényes."));
+ assert!(hu.html.contains(r#"href="https://sorsfonalak.test/meghivo/abc""#));
+ assert!(hu.text.contains("Nem kérek több meghívót"));
+ let mut anonymous = invitation_payload();
+ anonymous["inviter_name"] = Value::Null;
+ assert_eq!(render("synastry_invite", "en", &anonymous).unwrap().subject, "Someone wonders how well you match");
+ }
+
#[test]
fn invitation_has_both_parts() {
let hu = render("invitation", "hu", &invitation_payload()).unwrap();
diff --git a/docs/szemely-meghivas.md b/docs/szemely-meghivas.md
new file mode 100644
index 0000000..0328493
--- /dev/null
+++ b/docs/szemely-meghivas.md
@@ -0,0 +1,30 @@
+# Személy meghívása
+
+Az „Új személy” oldalon két lehetőség van:
+
+- **Adatok megadása:** a felhasználó maga írja be a születési adatokat. Ez egy személyhelyet használ, ahogy eddig.
+- **Meghívom:** egy „Mennyire illünk össze?” meghívó (`synastry_invites`). A meghívott a saját adatait adja meg. Személyhely nem kell hozzá, és akkor is működik, ha a helyek elfogytak.
+
+## Menete
+
+1. **A meghívó elkészül.** A meghívó megadhatja, kinek szól (ezt csak ő látja), a meghívott e-mail-címét (nem kötelező) és egy üzenetet (legfeljebb 300 karakter, link nélkül). A link `/meghivas/`, 14 napig érvényes. Megosztható másolással, a telefon megosztás menüjével, WhatsAppon vagy Facebookon.
+2. **Levél** (`synastry_invite` sablon), ha e-mail-cím is van:
+ - naponta legfeljebb 10 levél felhasználónként, a többi meghívó csak linkkel megy;
+ - aki leiratkozott a meghívókról, nem kap levelet (a link ilyenkor is működik);
+ - a levél alján leiratkozó link van, ugyanaz a végpont, mint az oldalmeghívóknál.
+3. **A meghívott a linkről érkezik.**
+ - Belép Google-lal. Meghívásos regisztrációnál a link kódja engedi be.
+ - Ha még nincs képlete, megadja a születési adatait, és rögtön elkészül az összevetés (`POST /v1/invites/accept`).
+ - Az összevetés oldalára jut.
+4. **A meghívó értesítést kap** (`invite_accepted`, a link az `/osszevetesek/` oldalra visz). A Személyek oldalon a „Meghívóid” listában látszanak a függő meghívók (visszavonhatók) és az elmúlt 30 nap elfogadott meghívói.
+
+## Ki mit fizet
+
+| Mi | Ár |
+|---|---|
+| A meghívott képlete és rövid összefoglalója | ingyen, mint mindenkinek |
+| Az összevetés rajza és táblázatai | ingyen |
+| Kapcsolati elemzés | 1 kapcsolati egység, annak, aki elindítja; mindketten látják, és mindketten kérdezhetnek róla |
+| A meghívott részletes képletelemzése | csak ha ő kéri, a saját egységéből |
+
+A meghívó a meghívott születési adatait nem látja, csak a bolygóállásokat és az összevetést.
diff --git a/services/backend/src/routes/invitations.rs b/services/backend/src/routes/invitations.rs
index e62b731..fda232e 100644
--- a/services/backend/src/routes/invitations.rs
+++ b/services/backend/src/routes/invitations.rs
@@ -127,7 +127,7 @@ async fn gift_of(conn: &mut PgConnection, invitation_id: Uuid) -> Result) -> Result , ApiError> {
+pub(super) fn clean_message(message: Option) -> Result, ApiError> {
let Some(message) = message.map(|m| m.replace("\r\n", "\n").trim().to_owned()).filter(|m| !m.is_empty()) else {
return Ok(None);
};
@@ -142,7 +142,7 @@ fn clean_message(message: Option) -> Result, ApiError> {
Ok(Some(message))
}
-fn links(state: &AppState, token: &str) -> (String, String, String) {
+pub(super) fn links(state: &AppState, token: &str) -> (String, String, String) {
let base = &state.config.public_base_url;
(
format!("{base}/meghivo/{token}"),
@@ -199,7 +199,7 @@ async fn send(
Ok(url)
}
-async fn opted_out(conn: &mut PgConnection, email: &str) -> Result {
+pub(super) async fn opted_out(conn: &mut PgConnection, email: &str) -> Result {
Ok(sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM email_optouts WHERE email_hash = $1)")
.bind(db::token_hash(email))
.fetch_one(conn)
@@ -587,8 +587,11 @@ pub async fn unsubscribe(
WithRejection(Query(q), _): WithRejection, ApiError>,
) -> ApiResult> {
let mut tx = state.db.begin().await?;
+ // The link of a site invitation, or of a "how compatible are we?" one a user had us e-mail.
let email: Option = sqlx::query_scalar(
- "SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1",
+ "SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1 \
+ UNION ALL SELECT invitee_email FROM synastry_invites WHERE token_hash = $1 AND invitee_email IS NOT NULL \
+ LIMIT 1",
)
.bind(db::token_hash(q.token.trim()))
.fetch_optional(&mut *tx)
diff --git a/services/backend/src/routes/synastries.rs b/services/backend/src/routes/synastries.rs
index f488e4b..151ad5e 100644
--- a/services/backend/src/routes/synastries.rs
+++ b/services/backend/src/routes/synastries.rs
@@ -24,6 +24,8 @@ use crate::error::{ApiError, ApiResult};
use crate::views::{public_chart, rfc3339, rfc3339_opt, synastry_hash};
const INVITE_TTL: time::Duration = time::Duration::days(14);
+/// Invitations a user may have us e-mail in a day (the rest go by link).
+const EMAILED_PER_DAY: i64 = 10;
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct SynastryRow {
@@ -238,6 +240,10 @@ pub struct CreateInvite {
/// Defaults to the user's primary chart.
chart_id: Option,
message: Option,
+ /// Who it is for, as the inviter calls them (only the inviter sees it).
+ label: Option,
+ /// Have us e-mail the invitation to this address.
+ email: Option,
}
async fn chart_or_primary(db: &PgPool, chart_id: Option, user: Uuid) -> Result {
@@ -255,13 +261,57 @@ pub async fn create_invite(
WithRejection(Json(req), _): Body,
) -> ApiResult<(StatusCode, Json)> {
let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
- let message = req.message.map(|m| m.trim().chars().take(500).collect::()).filter(|m| !m.is_empty());
+ // No links: the message may go out in an e-mail from our domain.
+ let message = super::invitations::clean_message(req.message)?;
+ let label = req.label.map(|l| l.trim().chars().take(80).collect::()).filter(|l| !l.is_empty());
+ let email = match req.email.as_deref().map(str::trim).filter(|e| !e.is_empty()) {
+ Some(raw) => Some(super::auth::normalize_email(raw)?),
+ None => None,
+ };
let token = db::new_token();
let id = Uuid::now_v7();
let expires_at = OffsetDateTime::now_utc() + INVITE_TTL;
+ let url = format!("{}/meghivas/{token}", state.config.public_base_url);
+ let mut tx = state.db.begin().await?;
+ let mut emailed = false;
+ if let Some(to) = &email {
+ if *to == auth.user.email {
+ return Err(ApiError::BadRequest("Saját magadat nem hívhatod meg.".into()));
+ }
+ let today: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM synastry_invites WHERE inviter_id = $1 AND invitee_email IS NOT NULL \
+ AND created_at > now() - interval '1 day'",
+ )
+ .bind(auth.id())
+ .fetch_one(&mut *tx)
+ .await?;
+ if today >= EMAILED_PER_DAY {
+ return Err(ApiError::conflict(
+ "invite_mail_limit",
+ format!(
+ "Naponta legfeljebb {EMAILED_PER_DAY} meghívót küldünk ki levélben. A linket továbbra is elküldheted."
+ ),
+ ));
+ }
+ // Someone who asked for no more invitations gets none; the link still works.
+ if !super::invitations::opted_out(&mut tx, to).await? {
+ let (_, unsubscribe_url, unsubscribe_post_url) = super::invitations::links(&state, &token);
+ let payload = json!({
+ "url": url,
+ "inviter_name": auth.user.display_name,
+ "message": message,
+ "expires_on": expires_at.date().to_string(),
+ "unsubscribe_url": unsubscribe_url,
+ "unsubscribe_post_url": unsubscribe_post_url,
+ });
+ super::auth::queue_email_to(&mut tx, None, to, "synastry_invite", &auth.user.locale, payload).await?;
+ emailed = true;
+ }
+ }
sqlx::query(
- "INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at) \
- VALUES ($1, $2, $3, $4, $5, $6)",
+ "INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at, label, \
+ invitee_email) \
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(id)
.bind(auth.id())
@@ -269,16 +319,22 @@ pub async fn create_invite(
.bind(db::token_hash(&token))
.bind(&message)
.bind(expires_at)
- .execute(&state.db)
+ .bind(&label)
+ .bind(&email)
+ .execute(&mut *tx)
.await?;
+ tx.commit().await?;
Ok((
StatusCode::CREATED,
Json(json!({
"id": id,
"token": token,
- "url": format!("{}/invite/{token}", state.config.public_base_url),
+ "url": url,
"chart_id": chart.id,
"message": message,
+ "label": label,
+ "email": email,
+ "emailed": emailed,
"expires_at": rfc3339(expires_at),
})),
))
@@ -304,10 +360,12 @@ pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult,
Option,
Option,
+ Option,
+ Option,
);
let rows: Vec = sqlx::query_as(
"SELECT i.id, i.inviter_chart_id, i.message, i.created_at, i.expires_at, i.accepted_at, i.synastry_id, \
- u.display_name \
+ u.display_name, i.label, i.invitee_email \
FROM synastry_invites i LEFT JOIN users u ON u.id = i.accepted_by \
WHERE i.inviter_id = $1 ORDER BY i.created_at DESC",
)
@@ -316,9 +374,9 @@ pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult = rows
.into_iter()
- .map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by)| {
+ .map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by, label, email)| {
json!({
- "id": id, "chart_id": chart_id, "message": message,
+ "id": id, "chart_id": chart_id, "message": message, "label": label, "email": email,
"status": invite_status(accepted, expires),
"created_at": rfc3339(created), "expires_at": rfc3339(expires),
"accepted_at": rfc3339_opt(accepted), "accepted_by": accepted_by, "synastry_id": synastry_id,
@@ -425,7 +483,7 @@ pub async fn accept_invite(
.fetch_optional(&mut *tx)
.await?;
if let Some(inviter) = inviter {
- let url = format!("{}/synastry/{}", state.config.public_base_url, row.id);
+ let url = format!("{}/osszevetesek/{}", state.config.public_base_url, row.id);
super::auth::queue_email(
&mut tx,
&inviter,
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index 0a63774..5738de3 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -517,6 +517,67 @@ async fn invitation_links_two_users(pool: PgPool) {
assert!(app.outbox_url("anna@example.com", "invite_accepted").await.ends_with(&synastry_id));
}
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn a_person_can_be_invited_by_mail(pool: PgPool) {
+ let app = TestApp::new(pool.clone()).await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ app.chart(&anna, "Saját", true, "1990-03-15").await;
+
+ // links are not allowed in the message (it may go out in our e-mail)
+ let r =
+ app.post("/v1/invites", Some(&anna), json!({"message": "nézd: www.x.hu", "email": "bela@example.com"})).await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST);
+ let r = app.post("/v1/invites", Some(&anna), json!({"email": "anna@example.com"})).await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST, "not herself");
+
+ let r = app
+ .post(
+ "/v1/invites",
+ Some(&anna),
+ json!({"label": "Béla", "email": " Bela@Example.com ", "message": "Nézzük meg, mennyire illünk!"}),
+ )
+ .await;
+ assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
+ let token = r.body["token"].as_str().unwrap().to_string();
+ assert!(r.body["url"].as_str().unwrap().ends_with(&format!("/meghivas/{token}")));
+ assert_eq!((r.body["emailed"].as_bool(), r.body["email"].as_str()), (Some(true), Some("bela@example.com")));
+ let (template, payload): (String, Value) =
+ sqlx::query_as("SELECT template, payload FROM email_outbox WHERE to_email = 'bela@example.com'")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!((template.as_str(), &payload["inviter_name"]), ("synastry_invite", &json!("Anna")));
+ let invites = app.get("/v1/invites", Some(&anna)).await.body;
+ assert_eq!(
+ (&invites["invites"][0]["label"], &invites["invites"][0]["status"]),
+ (&json!("Béla"), &json!("pending"))
+ );
+
+ // the address can opt out; the next invitation goes by link only
+ let r = app.post(&format!("/v1/public/invitations/unsubscribe?token={token}"), None, json!({})).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ let r = app.post("/v1/invites", Some(&anna), json!({"email": "bela@example.com"})).await;
+ assert_eq!((r.status, r.body["emailed"].as_bool()), (StatusCode::CREATED, Some(false)));
+
+ // at most ten e-mailed a day
+ for i in 2..10 {
+ let r = app.post("/v1/invites", Some(&anna), json!({"email": format!("p{i}@example.com")})).await;
+ assert_eq!(r.status, StatusCode::CREATED);
+ }
+ let r = app.post("/v1/invites", Some(&anna), json!({"email": "p10@example.com"})).await;
+ assert_eq!(r.body["error"]["code"], "invite_mail_limit");
+ let r = app.post("/v1/invites", Some(&anna), json!({"label": "link only"})).await;
+ assert_eq!(r.status, StatusCode::CREATED, "a link is still fine");
+
+ // accepted: the inviter's mail leads to the comparison page
+ let bela = app.register("bela@example.com", "Béla").await;
+ app.chart(&bela, "Saját", true, "1976-09-03").await;
+ let r = app.post("/v1/invites/accept", Some(&bela), json!({"token": token})).await;
+ assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
+ let url = app.outbox_url("anna@example.com", "invite_accepted").await;
+ assert!(url.ends_with(&format!("/osszevetesek/{}", r.body["id"].as_str().unwrap())), "{url}");
+}
+
/// Gives `token`'s user analysis units (the admin endpoint is tested in `roles_and_admin_guard`).
async fn grant_units(app: &TestApp, token: &str, unit: &str, delta: i32) {
let id = app.get("/v1/me", Some(token)).await.body["user"]["id"].as_str().unwrap().to_string();
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index b8edad2..f6214a1 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -743,3 +743,19 @@ a.pair-row:hover strong { color: var(--gold); }
.promo-form .promo-note, .promo-form .btn { grid-column: 1 / -1; }
}
@media (max-width: 640px) { .who { flex-wrap: wrap; gap: 8px 12px; } }
+
+/* New person: typed-in data or an invitation */
+.mode-switch { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr)); gap: 10px; }
+.mode-option {
+ display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; text-align: left; cursor: pointer; font: inherit;
+ color: var(--ink); background: var(--panel-2); border: 1px solid var(--line-2); border-radius: 12px;
+}
+.mode-option strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; }
+.mode-option span { font-size: 13.5px; color: var(--muted); line-height: 1.45; }
+.mode-option:hover { border-color: #5a6790; }
+.mode-option[aria-selected="true"] { border-color: var(--gold); background: rgba(217, 180, 106, 0.08); }
+.mode-option[aria-selected="true"] strong { color: var(--gold); }
+.invite-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.invite-list li { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; padding: 10px 0; border-bottom: 1px solid var(--line); }
+.invite-list li:last-child { border-bottom: 0; }
+.invite-who { display: flex; flex-direction: column; min-width: 0; flex: 1 1 180px; }
diff --git a/services/frontend/src/app/meghivas/[token]/AcceptInvite.tsx b/services/frontend/src/app/meghivas/[token]/AcceptInvite.tsx
new file mode 100644
index 0000000..bf5b5b5
--- /dev/null
+++ b/services/frontend/src/app/meghivas/[token]/AcceptInvite.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+
+import { BirthForm } from "@/app/profil/BirthForm";
+import { api, errorText } from "@/lib/api";
+
+/** The logged-in invitee: gives their own birth data if needed, then the comparison is made. */
+export function AcceptInvite({ token, hasOwnChart }: { token: string; hasOwnChart: boolean }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const [needsChart, setNeedsChart] = useState(!hasOwnChart);
+
+ async function accept() {
+ setBusy(true);
+ setError(null);
+ try {
+ const s = await api<{ id: string }>("/invites/accept", { body: { token } });
+ router.push(`/osszevetesek/${s.id}`);
+ router.refresh();
+ } catch (e) {
+ setError(errorText(e));
+ setBusy(false);
+ }
+ }
+
+ if (needsChart) {
+ return (
+
+
Add meg a születési adataidat: ebből készül a képleted, és ezt vetjük össze.
+
{
+ setNeedsChart(false);
+ accept();
+ }}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+ }
+ return (
+
+
A saját képleteddel vetjük össze.
+
+
+ {busy ? "Készül az összevetés…" : "Összevetés elkészítése"}
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/meghivas/[token]/page.tsx b/services/frontend/src/app/meghivas/[token]/page.tsx
new file mode 100644
index 0000000..432e284
--- /dev/null
+++ b/services/frontend/src/app/meghivas/[token]/page.tsx
@@ -0,0 +1,95 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+
+import { GoogleLogin } from "@/app/belepes/GoogleLogin";
+import { Logo } from "@/components/SiteHeader";
+import { formatDate } from "@/lib/astro";
+import { BACKEND_URL, getMe } from "@/lib/server";
+import type { PersonInviteLanding, PublicConfig } from "@/lib/types";
+
+import { AcceptInvite } from "./AcceptInvite";
+
+export const metadata: Metadata = {
+ title: "Mennyire illünk össze?",
+ description: "Meghívó a születési képletek összevetésére a Sorsfonalakon.",
+ robots: { index: false },
+};
+
+const TOKEN = /^[A-Za-z0-9_-]{8,200}$/;
+
+async function load(path: string): Promise {
+ try {
+ const res = await fetch(`${BACKEND_URL}${path}`, { cache: "no-store" });
+ return res.ok ? ((await res.json()) as T) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A "how compatible are we?" link: who invites, login, own birth data, then the comparison. */
+export default async function PersonInvitePage({ params }: { params: Promise<{ token: string }> }) {
+ const { token } = await params;
+ const valid = TOKEN.test(token);
+ const [invite, config, me] = await Promise.all([
+ valid ? load(`/v1/public/invites/${token}`) : Promise.resolve(null),
+ load("/v1/config"),
+ getMe(),
+ ]);
+ const who = invite?.inviter_name ?? "Valaki";
+ const clientId = config?.google_login.enabled ? config.google_login.client_id : null;
+
+ let body: React.ReactNode;
+ if (!invite) {
+ body = Ez a meghívólink érvénytelen. Ellenőrizd, hogy a teljes linket nyitottad-e meg.
;
+ } else if (invite.status === "accepted") {
+ body = (
+
+ Ezt a meghívót már elfogadták. {me ? Az összevetéseid itt vannak. : null}
+
+ );
+ } else if (invite.status === "expired") {
+ body = Ez a meghívó lejárt vagy visszavonták. Kérj újat attól, aki küldte.
;
+ } else if (!me) {
+ body = clientId ? (
+ <>
+
+ A fiókod az első belépéskor jön létre, bármelyik Google-fiókoddal.
+ >
+ ) : (
+ A belépés most nem érhető el. Próbáld újra később.
+ );
+ } else {
+ body = ;
+ }
+
+ return (
+ <>
+ {!me && (
+
+ )}
+
+
+
Meghívó
+
Mennyire illetek össze?
+ {invite && (
+
+ {who} szeretné összevetni a születési képleteteket.
+
+ )}
+
+ {invite?.message && {invite.message} }
+
+ {body}
+ {invite?.status === "pending" && (
+
+ A saját képletedet és egy rövid elemzést ingyen kapsz. {who} az összevetést látja, a születési adataidat nem.
+ A meghívó {formatDate(invite.expires_at).replace(/\.$/, "")}-ig érvényes.
+
+ )}
+
+
+ >
+ );
+}
diff --git a/services/frontend/src/app/szemelyek/page.tsx b/services/frontend/src/app/szemelyek/page.tsx
index 3cfb583..28a7ba3 100644
--- a/services/frontend/src/app/szemelyek/page.tsx
+++ b/services/frontend/src/app/szemelyek/page.tsx
@@ -3,6 +3,7 @@ import Link from "next/link";
import { ChartCard } from "@/components/ChartCard";
import { PersonActions } from "@/components/PersonActions";
+import { PendingInvites } from "@/components/PendingInvites";
import { PersonPacks } from "@/components/PersonPacks";
import { backendGet, requireMe } from "@/lib/server";
import type { ChartListItem, PublicConfig } from "@/lib/types";
@@ -46,19 +47,23 @@ export default async function PersonsPage() {
))}
- {!full && (
-
-
- +
-
- Új személy
-
- {slots.unlimited ? "Korlátlan számú személy" : `Még ${slots.left} személyt vehetsz fel`}
-
-
- )}
+
+
+ +
+
+ Új személy
+
+ {full
+ ? "Meghívással bármikor"
+ : slots.unlimited
+ ? "Adatokkal vagy meghívással"
+ : `Még ${slots.left} személyt vehetsz fel, vagy hívd meg`}
+
+
+
+
{!slots.unlimited && (
diff --git a/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx b/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
new file mode 100644
index 0000000..495745e
--- /dev/null
+++ b/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import Link from "next/link";
+import { useState } from "react";
+
+import { InvitePerson } from "@/components/InvitePerson";
+
+import { NewPerson } from "./NewPerson";
+
+/**
+ * Adding a person: typing in their birth data (uses a slot), or inviting
+ * them to compare charts (they give their own data; no slot used).
+ */
+export function NewPersonChooser({
+ canAdd,
+ hasOwnChart,
+ full,
+}: {
+ /** A slot is free for typed-in data. */
+ canAdd: boolean;
+ /** Inviting compares with the user's own chart. */
+ hasOwnChart: boolean;
+ /** Shown instead of the form when no slot is left. */
+ full: React.ReactNode;
+}) {
+ const [mode, setMode] = useState<"data" | "invite">(canAdd ? "data" : "invite");
+ return (
+
+
+ setMode("data")}
+ >
+ Adatok megadása
+ Te írod be a születési adatait. Egy személyhelyet használ.
+
+ setMode("invite")}
+ >
+ Meghívom
+ Ő adja meg a saját adatait, és megnézitek, mennyire illetek össze. Ingyenes, nem kell hozzá hely.
+
+
+ {mode === "data" ? (
+ canAdd ? (
+ <>
+
+
Az adatokat a felvételt követő egy órán belül még javíthatod, utána nem módosíthatók.
+ >
+ ) : (
+ full
+ )
+ ) : hasOwnChart ? (
+ <>
+
+
+ A meghívott a saját képletét és rövid összefoglalóját ingyen kapja. Ti ketten az összevetést látjátok, egymás
+ születési adatait nem. A részletes kapcsolati elemzést bármelyikőtök kérheti egy kapcsolati elemzéssel, és
+ mindketten látjátok.
+
+ >
+ ) : (
+
+ A meghívó a saját képleteddel veti össze az övét, ezért előbb add meg a saját
+ születési adataidat.
+
+ )}
+
+ );
+}
diff --git a/services/frontend/src/app/szemelyek/uj/page.tsx b/services/frontend/src/app/szemelyek/uj/page.tsx
index 6d4bb18..d3de651 100644
--- a/services/frontend/src/app/szemelyek/uj/page.tsx
+++ b/services/frontend/src/app/szemelyek/uj/page.tsx
@@ -4,7 +4,7 @@ import { PersonPacks } from "@/components/PersonPacks";
import { backendGet, requireMe } from "@/lib/server";
import type { PublicConfig } from "@/lib/types";
-import { NewPerson } from "./NewPerson";
+import { NewPersonChooser } from "./NewPersonChooser";
export const metadata: Metadata = { title: "Új személy" };
@@ -18,22 +18,22 @@ export default async function NewPersonPage() {
Új személy
- Társad, családtagod, barátod: a születési adataiból elkészül a képlete és egy rövid összefoglaló.
+ Társad, családtagod, barátod: megadhatod a születési adatait, vagy meghívhatod, hogy ő adja meg, és megnézzétek,
+ mennyire illetek össze.
{!slots.unlimited && slots.left !== null && slots.left > 0 && ` Még ${slots.left} személyt vehetsz fel.`}
-
- {slots.left === 0 ? (
- <>
- Elfogytak a helyeid. Újabb személyhez válassz csomagot.
-
- >
- ) : (
- <>
-
- Az adatokat a felvételt követő egy órán belül még javíthatod, utána nem módosíthatók.
- >
- )}
+
+
+ Elfogytak a helyeid. Újabb személyhez válassz csomagot, vagy hívd meg.
+
+ >
+ }
+ />
);
diff --git a/services/frontend/src/components/InvitePerson.tsx b/services/frontend/src/components/InvitePerson.tsx
new file mode 100644
index 0000000..2410eb6
--- /dev/null
+++ b/services/frontend/src/components/InvitePerson.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+
+const MAX_MESSAGE = 300;
+
+interface Created {
+ url: string;
+ emailed: boolean;
+ email: string | null;
+ label: string | null;
+}
+
+/**
+ * Invites someone to compare charts instead of typing in their birth data:
+ * they enter their own data, and both see the comparison (not each other's
+ * birth data). No person slot is used.
+ */
+export function InvitePerson() {
+ const [label, setLabel] = useState("");
+ const [email, setEmail] = useState("");
+ const [message, setMessage] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const [created, setCreated] = useState(null);
+ const [copied, setCopied] = useState(false);
+
+ async function submit(e: React.FormEvent) {
+ e.preventDefault();
+ setBusy(true);
+ setError(null);
+ try {
+ setCreated(
+ await api("/invites", {
+ body: { label: label.trim() || null, email: email.trim() || null, message: message.trim() || null },
+ }),
+ );
+ } catch (err) {
+ setError(errorText(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function copy() {
+ if (!created) return;
+ try {
+ await navigator.clipboard.writeText(created.url);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch {
+ setError("Nem sikerült másolni; jelöld ki a linket, és másold kézzel.");
+ }
+ }
+
+ if (created) {
+ const text = `Nézzük meg, mennyire illünk össze! ${created.url}`;
+ return (
+
+
+ {created.emailed
+ ? `Elküldtük a meghívót ide: ${created.email}. A linket te is továbbküldheted.`
+ : created.email
+ ? `Ez a cím nem kér levelet tőlünk, ezért nem írtunk neki. Küldd el neki te a linket.`
+ : "Kész a meghívó. Küldd el a linket annak, akit meghívsz."}
+
+
+ e.currentTarget.select()}
+ />
+
+ {copied ? "Kimásolva" : "Másolás"}
+
+
+
+ {typeof navigator !== "undefined" && "share" in navigator && (
+
navigator.share({ text: "Nézzük meg, mennyire illünk össze!", url: created.url }).catch(() => {})}
+ >
+ Küldés…
+
+ )}
+
+ WhatsApp
+
+
+ Facebook
+
+
setCreated(null)}>
+ Újabb meghívó
+
+
+
+ A meghívó 14 napig érvényes. Amikor elfogadja, levelet kapsz, és az összevetés megjelenik az Összevetéseid
+ között.
+
+
+ );
+ }
+
+ return (
+
+ );
+}
diff --git a/services/frontend/src/components/PendingInvites.tsx b/services/frontend/src/components/PendingInvites.tsx
new file mode 100644
index 0000000..22058c8
--- /dev/null
+++ b/services/frontend/src/components/PendingInvites.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useState } from "react";
+
+import { api, errorText } from "@/lib/api";
+import { formatDate } from "@/lib/astro";
+import type { PersonInvite } from "@/lib/types";
+
+/** The user's "how compatible are we?" invitations: waiting ones (revocable) and accepted ones. */
+export function PendingInvites() {
+ const [invites, setInvites] = useState(null);
+ const [error, setError] = useState(null);
+
+ const load = useCallback(async () => {
+ try {
+ setInvites((await api<{ invites: PersonInvite[] }>("/invites")).invites);
+ } catch (e) {
+ setError(errorText(e));
+ }
+ }, []);
+
+ useEffect(() => {
+ load();
+ }, [load]);
+
+ async function revoke(i: PersonInvite) {
+ if (!window.confirm(`Visszavonod a meghívót${i.label ? ` (${i.label})` : ""}? A link nem fog működni.`)) return;
+ try {
+ await api(`/invites/${i.id}`, { method: "DELETE" });
+ await load();
+ } catch (e) {
+ setError(errorText(e));
+ }
+ }
+
+ // Waiting ones, and the accepted ones of the last 30 days.
+ const recent = Date.now() - 30 * 86_400_000;
+ const shown = (invites ?? []).filter(
+ (i) => i.status === "pending" || (i.status === "accepted" && i.accepted_at && Date.parse(i.accepted_at) > recent),
+ );
+ if (!error && shown.length === 0) return null;
+
+ return (
+
+ Meghívóid
+ {error && (
+
+ {error}
+
+ )}
+
+ {shown.map((i) => (
+
+
+ {i.label ?? i.email ?? "Meghívó"}
+ {i.label && i.email && {i.email} }
+
+ {i.status === "pending" ? (
+ <>
+
+ Elküldve {formatDate(i.created_at)}, érvényes {formatDate(i.expires_at).replace(/\.$/, "")}-ig
+
+ revoke(i)}>
+ Visszavonás
+
+ >
+ ) : (
+ <>
+
+ Elfogadta{i.accepted_by ? `: ${i.accepted_by}` : ""} · {formatDate(i.accepted_at)}
+
+ {i.synastry_id && (
+
+ Összevetés
+
+ )}
+ >
+ )}
+
+ ))}
+
+
+ );
+}
diff --git a/services/frontend/src/components/SynastryTables.tsx b/services/frontend/src/components/SynastryTables.tsx
index a17f026..17cac93 100644
--- a/services/frontend/src/components/SynastryTables.tsx
+++ b/services/frontend/src/components/SynastryTables.tsx
@@ -1,4 +1,5 @@
import { ASPECTS, POINTS, SIGNS, dms, orbText, pointName, signName } from "@/lib/astro";
+import { sideTimeKnown } from "@/lib/synastry";
import type { HouseOverlay, InterAspect, Synastry, SynastryResult } from "@/lib/types";
import { GRID_POINTS, Pos } from "./ChartTables";
@@ -47,7 +48,7 @@ const GRID_ANGLES: [string, string][] = [
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) {
+ if (sideTimeKnown(s)) {
for (const [key, label] of GRID_ANGLES) if (s.chart.angles?.[key]) rows.push([key, label]);
}
return rows;
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 3d36aa8..26bbd3f 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -544,3 +544,26 @@ export interface PromoCode {
revoked_at: string | null;
redeemed_by: { email: string; name: string | null } | null;
}
+
+/** A "how compatible are we?" invitation of the user (`GET /v1/invites`). */
+export interface PersonInvite {
+ id: string;
+ chart_id: string;
+ label: string | null;
+ email: string | null;
+ message: string | null;
+ status: "pending" | "accepted" | "expired";
+ created_at: string;
+ expires_at: string;
+ accepted_at: string | null;
+ accepted_by: string | null;
+ synastry_id: string | null;
+}
+
+/** Landing data of a "how compatible are we?" link (`GET /v1/public/invites/{token}`). */
+export interface PersonInviteLanding {
+ inviter_name: string | null;
+ message: string | null;
+ status: "pending" | "accepted" | "expired";
+ expires_at: string;
+}
From dad16fe46316a0418b009f90a91a1fd8068d514f Mon Sep 17 00:00:00 2001
From: feco
Date: Thu, 19 Nov 2026 10:36:18 +0000
Subject: [PATCH 4/6] Home page for visitors
Visitors now get a home page instead of the login: the example chart's
wheel coming alive (planets one by one, aspect lines drawn, a slow orbit,
a quiet starfield), the free short summary, excerpts of the detailed
analysis, the yearly forecast and the relationship comparison, how it works
and a closing call. While sign-up is by invitation it says so: the buttons
lead to the Google login with an invitation, and others can join the
waitlist. Motion is off for reduced-motion users. Logged-in users still go
to their chart.
Also: the wheel tooltips (planets, aspects, angles) were empty, since React
19 wants plain text inside ; they are template strings now.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
---
services/frontend/src/app/Landing.tsx | 417 ++++++++++++++++++
services/frontend/src/app/globals.css | 150 +++++++
services/frontend/src/app/page.tsx | 34 +-
.../frontend/src/components/ChartWheel.tsx | 13 +-
.../frontend/src/components/SynastryWheel.tsx | 13 +-
5 files changed, 607 insertions(+), 20 deletions(-)
create mode 100644 services/frontend/src/app/Landing.tsx
diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx
new file mode 100644
index 0000000..ad994a6
--- /dev/null
+++ b/services/frontend/src/app/Landing.tsx
@@ -0,0 +1,417 @@
+import Link from "next/link";
+
+import { ChartWheel } from "@/components/ChartWheel";
+import { Rich } from "@/components/Rich";
+import { Logo } from "@/components/SiteHeader";
+import { Waitlist } from "@/components/Waitlist";
+import example from "@/content/pelda.json";
+import type { AnalysisContent, ChartResult } from "@/lib/types";
+
+// A quiet starfield, the same on every render.
+const STARS = (() => {
+ let seed = 7;
+ const rnd = () => {
+ seed = (seed * 9301 + 49297) % 233280;
+ return seed / 233280;
+ };
+ return Array.from({ length: 70 }, (_, i) => ({
+ x: (rnd() * 1000).toFixed(1),
+ y: (rnd() * 600).toFixed(1),
+ r: (0.6 + rnd() * 1.4).toFixed(1),
+ t: i % 5,
+ }));
+})();
+
+const MONTHS = ["márc", "ápr", "máj", "jún", "júl", "aug", "szept", "okt", "nov", "dec", "jan", "febr"];
+
+/** Points of a ring of the comparison picture. */
+function ring(r: number, degrees: number[]) {
+ return degrees.map((d) => {
+ const a = (d * Math.PI) / 180;
+ return { x: 110 + r * Math.cos(a), y: 110 - r * Math.sin(a) };
+ });
+}
+const YOU = ring(72, [15, 70, 128, 190, 236, 300, 338]);
+const THEM = ring(100, [40, 95, 150, 205, 262, 318, 355]);
+const LINKS: [number, number, string][] = [
+ [0, 0, "var(--harmonic)"],
+ [2, 4, "var(--tense)"],
+ [4, 5, "var(--harmonic)"],
+ [5, 2, "var(--gold)"],
+];
+
+// Sample lines of a forecast timeline (illustration, marked as such).
+const EVENTS = [
+ { date: "ápr. 9.", glyph: "♃\uFE0E", tone: "harmonic", text: "Jupiter trigon Nap: kinyíló lehetőségek" },
+ { date: "júl. 22.", glyph: "♄\uFE0E", tone: "tense", text: "Szaturnusz kvadrát Hold: érzelmi számvetés" },
+ { date: "okt. 14.", glyph: "☉\uFE0E", tone: "neutral", text: "Napfogyatkozás a 10. házban: hivatás" },
+];
+
+const CHAPTERS = ["Személyiség", "Érzelmek", "Gondolkodás", "Szerelem", "Hivatás", "Fejlődés"];
+const SYNASTRY_TOPICS = ["Vonzás", "Kommunikáció", "Érzelmi kötődés", "Súrlódások", "Hosszú táv"];
+
+/** The home page for visitors: what the site does, shown on the example chart. */
+export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
+ const chart = example.chart as unknown as ChartResult;
+ const analysis = example.analysis as AnalysisContent;
+ const sections = ["emotions", "love"].map((k) => analysis.sections?.[k]).filter((s) => s !== undefined);
+ const lead = (analysis.summary ?? "").split(/(?<=\.)\s/)[0];
+ const signIn = inviteOnly ? "Belépés meghívóval" : "Elkészítem a képletem";
+
+ return (
+
+
+
+
+
+ {STARS.map((s, i) => (
+
+ ))}
+
+
+
+
Születési képlet · Éves előrejelzés · Kapcsolat
+
+ Ahol a csillagok
+
+ összekötnek.
+
+
+ Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
+ belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
+
+
+
+ {signIn}
+
+
+ Példaelemzés
+
+
+
+ {inviteOnly ? (
+ <>
+ Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be. Ha még nincs meghívód,{" "}
+ iratkozz fel a várólistára .
+ >
+ ) : (
+ "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ☉︎ Nap Halak
+
+
+ ☽︎ Hold Skorpió
+
+
+ ASC Oroszlán
+
+
+ Példa: egy kitalált képlet · {example.birth}
+
+
+
+
+
+
+
+
+
Első lépés
+
Pár mondat, ami rólad szól
+
+ A képleted mellé rögtön kapsz egy rövid összefoglalót: mi adja a képleted gerincét, hol feszül, és miben vagy
+ igazán erős. Ingyen, a belépés után azonnal.
+
+
+
+ Röviden · ingyenes
+ {example.summary.title}
+
+
+
+
+
+
+
+
+
+
+
Részletes elemzés
+
Ha mélyebbre mennél
+
+ Hat fejezet a személyiségedről, az érzelmeidről, a gondolkodásodról, a szerelemről, a hivatásodról és a
+ fejlődésed irányáról. A végén erősségek, kihívások és útravaló, és ha kérdésed van, rá is kérdezhetsz.
+
+
+
+
+
+ {analysis.title}
+ {lead}
+
+
+ {sections.map((s) => (
+
+ ))}
+
+
+ Részlet egy kitalált képlet teljes elemzéséből
+ Elolvasom a teljes példaelemzést →
+
+
+
+
+
Erősségek
+
+ {(analysis.strengths ?? []).slice(0, 2).map((t) => (
+
+
+
+ ))}
+
+
+
+
Kérdezz rá
+
+ Ami nem világos, vagy amire kíváncsi vagy, megkérdezheted: a válasz a képletedből és az elemzésedből
+ születik.
+
+
„Mit jelent nekem a Hold–Vénusz kvadrát a párkapcsolatban?”
+
+
+
+
+ {CHAPTERS.map((c) => (
+
+ {c}
+
+ ))}
+ Útravaló
+
+
+
+
+
+
+
+ Nemcsak a képleted
+
Mit hoz az éved, és kivel illetek össze?
+
+
+
+
+
Éves előrejelzés
+
Egy év, hónapról hónapra
+
+ Szolár képlet, tranzitok pontos dátumokkal és progresszió: születésnaptól születésnapig, hogy tudd, mikor
+ mire érdemes figyelni.
+
+
+
+
+
+
+ {MONTHS.map((m, i) => {
+ const x = 10 + (i * 420) / 11;
+ return (
+
+
+
+ {m}
+
+
+ );
+ })}
+
+
+
+
+
+
+ most
+
+
+
+ {EVENTS.map((e) => (
+
+ {e.date}
+
+ {e.glyph}
+
+ {e.text}
+
+ ))}
+
+
Minta az idővonalból
+
+
+
+
+
+
Kapcsolati összevetés
+
Mennyire illetek össze?
+
+ Két képlet egymásra vetítve. Hívd meg, akit szeretsz: ő megadja a saját adatait, és együtt nézitek meg,
+ hol erős és hol kényes a kapcsolatotok.
+
+
+
+
+
+
+
+
+ {THEM.map((p, i) => (
+
+ ))}
+
+
+ {YOU.map((p, i) => (
+
+ ))}
+
+ {LINKS.map(([a, b, color]) => (
+
+ ))}
+
+
+
+ Te
+
+
+ Ő
+
+
+
+
+
+
+ harmonikus · feszült · semleges fényszögek
+
+
+
+ {SYNASTRY_TOPICS.map((c) => (
+
+ {c}
+
+ ))}
+
+
+
+
+
+
+
+
+
Így működik
+
+
+ 1
+ Belépsz, és megadod az adataidat
+
+ {inviteOnly ? "Meghívóval, Google-fiókkal lépsz be" : "Google-fiókkal lépsz be"}, aztán megadod a születésed
+ dátumát, idejét és helyét. Ha az időpontot nem tudod, akkor is kiszámoljuk, ami kiszámolható.
+
+
+
+ 2
+ Kész a képleted, ingyen
+
+ Megrajzolt radix, bolygóállások, házak, fényszögek és egy rövid, személyre szóló összefoglaló.
+
+
+
+ 3
+ Ha többet szeretnél
+
+ Részletes elemzés, éves előrejelzés, kapcsolati összevetés, és kérdések, amikre a saját képleted felel.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Kíváncsi vagy, mit mutat a te képleted?
+
+ {inviteOnly
+ ? "Egyelőre meghívással lehet csatlakozni. Ha kaptál meghívót, lépj be a Google-fiókoddal. Ha még nem, írd fel magad, és szólunk."
+ : "Két perc, és ott a képleted a rövid összefoglalóval együtt."}
+
+
+ {signIn}
+
+ {inviteOnly && (
+
+
+
+ )}
+
+ Az elemzéseket mesterséges intelligencia írja a pontosan kiszámolt képlet alapján. Tájékoztató jellegűek, nem
+ helyettesítenek szakmai tanácsot.
+
+
+
+
+
+
+ );
+}
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index f6214a1..812d425 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -759,3 +759,153 @@ a.pair-row:hover strong { color: var(--gold); }
.invite-list li { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; padding: 10px 0; border-bottom: 1px solid var(--line); }
.invite-list li:last-child { border-bottom: 0; }
.invite-who { display: flex; flex-direction: column; min-width: 0; flex: 1 1 180px; }
+
+/* Home page for visitors (src/app/Landing.tsx) */
+.lp { overflow-x: clip; }
+.lp-wrap { max-width: 1180px; margin: 0 auto; padding: 0 24px; }
+.lp-header { gap: 16px; }
+.lp-nav { flex: 1; }
+.lp-hero { position: relative; overflow: hidden; }
+.lp-stars { position: absolute; inset: 0; width: 100%; height: 100%; }
+.lp-star { fill: var(--ink); opacity: 0.25; animation: lp-twinkle 6s ease-in-out infinite; }
+.lp-t1 { animation-delay: 1s; animation-duration: 7s; }
+.lp-t2 { animation-delay: 2.4s; animation-duration: 5s; }
+.lp-t3 { animation-delay: 3.1s; animation-duration: 8s; }
+.lp-t4 { animation-delay: 0.6s; animation-duration: 9s; }
+.lp-hero-grid {
+ position: relative; padding-top: 72px; padding-bottom: 88px;
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(min(440px, 100%), 1fr)); gap: 48px; align-items: center;
+}
+.lp-hero-text { display: flex; flex-direction: column; gap: 24px; min-width: 0; }
+.lp-hero-text .eyebrow { font-size: 13px; letter-spacing: 2px; }
+.lp-title { font-size: clamp(44px, 6vw, 76px); line-height: 1.02; letter-spacing: -0.5px; }
+.lp-lead { font-size: 19px; line-height: 1.65; color: var(--ink-2); max-width: 540px; }
+.lp-actions { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
+.lp-btn { min-height: 48px; padding: 0 22px; transition: transform 0.2s, background 0.2s, border-color 0.2s; }
+.lp-btn:hover { transform: translateY(-1px); }
+.lp-btn-big { min-height: 52px; padding: 0 28px; font-size: 16px; }
+.lp-figure { margin: 0; display: flex; flex-direction: column; align-items: center; gap: 14px; min-width: 0; }
+.lp-wheel {
+ position: relative; width: 100%; max-width: 560px; border-radius: 50%;
+ background: radial-gradient(closest-side, rgba(217, 180, 106, 0.07), transparent 72%);
+}
+.lp-wheel .chart-wheel { position: relative; }
+.lp-orbit { position: absolute; inset: 0; width: 100%; height: 100%; animation: lp-spin 240s linear infinite; }
+.lp-orbit circle { fill: none; stroke: var(--gold); stroke-opacity: 0.18; stroke-width: 1; stroke-dasharray: 2 10; }
+.lp-orbit .lp-orbit-dot { fill: var(--gold); stroke: none; opacity: 0.55; }
+/* the wheel comes alive: planets one by one, then the aspect lines */
+.lp-wheel .w-point { opacity: 0; animation: lp-fade 0.9s ease-out forwards; }
+.lp-wheel .w-point:nth-last-of-type(13) { animation-delay: 0.3s; }
+.lp-wheel .w-point:nth-last-of-type(12) { animation-delay: 0.42s; }
+.lp-wheel .w-point:nth-last-of-type(11) { animation-delay: 0.54s; }
+.lp-wheel .w-point:nth-last-of-type(10) { animation-delay: 0.66s; }
+.lp-wheel .w-point:nth-last-of-type(9) { animation-delay: 0.78s; }
+.lp-wheel .w-point:nth-last-of-type(8) { animation-delay: 0.9s; }
+.lp-wheel .w-point:nth-last-of-type(7) { animation-delay: 1.02s; }
+.lp-wheel .w-point:nth-last-of-type(6) { animation-delay: 1.14s; }
+.lp-wheel .w-point:nth-last-of-type(5) { animation-delay: 1.26s; }
+.lp-wheel .w-point:nth-last-of-type(4) { animation-delay: 1.38s; }
+.lp-wheel .w-point:nth-last-of-type(3) { animation-delay: 1.5s; }
+.lp-wheel .w-point:nth-last-of-type(2) { animation-delay: 1.62s; }
+.lp-wheel .w-point:nth-last-of-type(1) { animation-delay: 1.74s; }
+.lp-wheel .w-aspect { stroke-dasharray: 300; stroke-dashoffset: 300; animation: lp-draw 1.8s cubic-bezier(0.4, 0, 0.2, 1) 1.6s forwards; }
+.lp-wheel .w-aspect.w-asp-sextile { stroke-dasharray: 5 4; stroke-dashoffset: 0; opacity: 0; animation: lp-fade 1.2s ease-out 2.2s forwards; }
+.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
+.lp-caption .share-trio { justify-content: center; font-size: 15px; }
+.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
+.lp-rise { opacity: 0; transform: translateY(14px); animation: lp-rise 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) forwards; }
+.lp-r1 { animation-delay: 0.1s; } .lp-r2 { animation-delay: 0.25s; } .lp-r3 { animation-delay: 0.4s; } .lp-r4 { animation-delay: 0.55s; }
+
+.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
+.lp-alt { background: var(--panel-2); }
+.lp-two { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(380px, 100%), 1fr)); gap: 48px; align-items: center; }
+.lp-stack { display: flex; flex-direction: column; gap: 40px; }
+.lp-intro { display: flex; flex-direction: column; gap: 14px; max-width: 720px; }
+.lp-intro .eyebrow { font-size: 13px; letter-spacing: 2px; }
+.lp-h2 { font-size: clamp(34px, 4vw, 52px); line-height: 1.06; }
+.lp-h3 { font-size: 24px; }
+.lp-center { text-align: center; }
+.lp-text { font-size: 17px; color: var(--ink-2); line-height: 1.65; }
+.lp-small { font-size: 15px; color: var(--ink-2); line-height: 1.6; }
+.lp-float { padding: 32px; box-shadow: 0 30px 80px rgba(0, 0, 0, 0.35); animation: lp-float 9s ease-in-out infinite; }
+.lp-float .summary-title { font-size: 32px; }
+
+.lp-analysis-grid { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 24px; align-items: start; }
+.lp-paper { padding: 36px; gap: 22px; }
+.lp-paper-title { font-size: 36px; line-height: 1.08; }
+.lp-excerpts { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr)); gap: 28px; }
+.lp-fade { max-height: 270px; overflow: hidden; -webkit-mask-image: linear-gradient(#000 55%, transparent); mask-image: linear-gradient(#000 55%, transparent); }
+.lp-excerpt-title { font-family: var(--font-display); font-size: 24px; font-weight: 600; color: var(--gold); line-height: 1.15; margin: 0; }
+.lp-paper-foot { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; justify-content: space-between; border-top: 1px solid var(--line); padding-top: 20px; }
+.lp-paper-foot a { font-weight: 600; text-decoration: none; }
+.lp-aside { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
+.lp-side-card { gap: 12px; }
+.lp-list { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 10px; font-size: 15px; line-height: 1.6; color: var(--ink-2); }
+.lp-question { margin: 0; padding: 12px 14px; border-radius: var(--radius); background: var(--panel-2); border: 1px solid var(--line-2); font-size: 14px; }
+.lp-chips { display: flex; gap: 8px; flex-wrap: wrap; }
+.lp-chip { padding: 6px 14px; border-radius: 999px; border: 1px solid var(--line-2); font-size: 14px; color: var(--ink-2); }
+.lp-chip-gold { border-color: rgba(217, 180, 106, 0.5); color: var(--gold); }
+
+.lp-features { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); gap: 24px; }
+.lp-feature { padding: 32px; gap: 20px; }
+.lp-feature-head { display: flex; flex-direction: column; gap: 10px; }
+.lp-feature-title { font-size: 32px; line-height: 1.1; }
+.lp-panel { background: var(--panel-2); border: 1px solid var(--line); border-radius: 12px; padding: 20px; display: flex; flex-direction: column; gap: 14px; }
+.lp-timeline { width: 100%; height: auto; display: block; }
+.lp-tl-track { stroke: var(--line-2); stroke-width: 2; }
+.lp-tl-done { stroke: var(--gold); stroke-width: 2; }
+.lp-tl-month { fill: var(--muted); font: 400 10px var(--font-body); text-anchor: middle; }
+.lp-tl-now { fill: var(--ink); font: 600 11px var(--font-body); text-anchor: middle; }
+.lp-pulse { transform-box: fill-box; transform-origin: center; animation: lp-pulse 2.6s ease-in-out infinite; }
+.lp-events { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; font-size: 14.5px; }
+.lp-pair { display: grid; grid-template-columns: minmax(0, 200px) minmax(0, 1fr); gap: 20px; align-items: center; }
+.lp-rings { width: 100%; height: auto; display: block; }
+.lp-ring { fill: none; stroke: var(--line-2); stroke-width: 1; }
+.lp-ring-core { fill: var(--panel); stroke: var(--line); }
+.lp-spin { transform-box: fill-box; transform-origin: center; animation: lp-spin 120s linear infinite; }
+.lp-spin-back { transform-box: fill-box; transform-origin: center; animation: lp-spin 160s linear infinite reverse; }
+.lp-pair-legend { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
+.pair-text-row { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-2); }
+.pair-text-row.p2-text { color: var(--p2); }
+.lp-pair .nature-bar { margin-top: 6px; height: 8px; }
+
+.lp-steps { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr)); gap: 24px; }
+.lp-steps .card { gap: 12px; padding: 28px; }
+.lp-step-n { font-family: var(--font-display); font-size: 44px; font-weight: 600; line-height: 1; color: var(--gold); }
+.lp-step-title { font-family: var(--font-body); font-size: 18px; font-weight: 600; line-height: 1.3; }
+
+.lp-final { background: radial-gradient(ellipse at 50% 0%, rgba(217, 180, 106, 0.12), transparent 60%), var(--bg); padding: 104px 0; }
+.lp-final-inner { max-width: 820px; display: flex; flex-direction: column; align-items: center; gap: 22px; text-align: center; }
+.lp-emblem { width: 88px; height: 88px; }
+.lp-emblem-outer { fill: none; stroke: var(--gold); stroke-opacity: 0.5; stroke-width: 1; }
+.lp-waitlist { width: 100%; max-width: 520px; text-align: left; }
+.lp-disclaimer { max-width: 560px; }
+.lp-footer { border-top: 1px solid var(--line); padding: 28px 0; }
+.lp-footer-inner { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; justify-content: space-between; }
+.lp-footer-nav { display: flex; gap: 18px; flex-wrap: wrap; font-size: 14px; }
+.lp-footer-nav a { color: var(--muted); text-decoration: none; }
+.lp-footer-nav a:hover { color: var(--gold); }
+
+@keyframes lp-twinkle { 0%, 100% { opacity: 0.15; } 50% { opacity: 0.7; } }
+@keyframes lp-fade { to { opacity: 1; } }
+@keyframes lp-draw { to { stroke-dashoffset: 0; } }
+@keyframes lp-spin { to { transform: rotate(360deg); } }
+@keyframes lp-rise { to { opacity: 1; transform: none; } }
+@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
+@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
+@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
+@media (max-width: 640px) {
+ .lp-band { padding: 64px 0; }
+ .lp-hero-grid { padding-top: 40px; padding-bottom: 56px; gap: 32px; }
+ .lp-wrap { padding: 0 16px; }
+ .lp-paper, .lp-feature { padding: 22px; }
+ .lp-pair { grid-template-columns: minmax(0, 1fr); justify-items: center; }
+ .lp-rings { max-width: 200px; }
+ .lp-nav { display: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .lp *, .lp-orbit { animation: none !important; }
+ .lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; }
+ .lp-wheel .w-aspect { stroke-dashoffset: 0; }
+ .lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
+}
diff --git a/services/frontend/src/app/page.tsx b/services/frontend/src/app/page.tsx
index 6ef2e29..52d7823 100644
--- a/services/frontend/src/app/page.tsx
+++ b/services/frontend/src/app/page.tsx
@@ -1,10 +1,36 @@
+import type { Metadata } from "next";
import { redirect } from "next/navigation";
-import { getMe } from "@/lib/server";
+import { BACKEND_URL, getMe } from "@/lib/server";
+import type { PublicConfig } from "@/lib/types";
-// No home page yet: logged-in users go to their chart (or to the profile to enter
-// their birth data), others to login.
+import { Landing } from "./Landing";
+
+export const metadata: Metadata = {
+ title: { absolute: "Sorsfonalak – születési képlet, éves előrejelzés, kapcsolati összevetés" },
+ description:
+ "Percre pontos születési képlet és személyre szóló elemzés, éves előrejelzés és kapcsolati összevetés: mennyire illetek össze?",
+ openGraph: {
+ type: "website",
+ siteName: "Sorsfonalak",
+ locale: "hu_HU",
+ title: "Sorsfonalak – ahol a csillagok összekötnek",
+ description: "Születési képlet, részletes elemzés, éves előrejelzés és kapcsolati összevetés.",
+ },
+};
+
+async function signupMode(): Promise {
+ try {
+ const res = await fetch(`${BACKEND_URL}/v1/config`, { next: { revalidate: 300 } });
+ return res.ok ? ((await res.json()) as PublicConfig).signup_mode : "invite";
+ } catch {
+ return "invite";
+ }
+}
+
+/** Visitors get the home page; logged-in users go to their chart (or to the profile for their birth data). */
export default async function Home() {
const me = await getMe();
- redirect(!me ? "/belepes" : me.primary_chart_id ? "/keplet" : "/profil");
+ if (me) redirect(me.primary_chart_id ? "/keplet" : "/profil");
+ return ;
}
diff --git a/services/frontend/src/components/ChartWheel.tsx b/services/frontend/src/components/ChartWheel.tsx
index 6c52e7d..024bfae 100644
--- a/services/frontend/src/components/ChartWheel.tsx
+++ b/services/frontend/src/components/ChartWheel.tsx
@@ -197,9 +197,7 @@ export function ChartWheel({
dominantBaseline="central"
textAnchor="middle"
>
-
- {pointName(key)}: {dms(a.degree_in_sign_dms)} {signName(a.sign)}
-
+ {`${pointName(key)}: ${dms(a.degree_in_sign_dms)} ${signName(a.sign)}`}
{label}
);
@@ -225,8 +223,7 @@ export function ChartWheel({
strokeWidth={(0.6 + 1.9 * s).toFixed(2)}
>
- {pointName(a.point1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {pointName(a.point2)} (orbis{" "}
- {orbText(a.orb)})
+ {`${pointName(a.point1)} ${ASPECTS[a.aspect]?.hu ?? a.aspect} ${pointName(a.point2)} (orbis ${orbText(a.orb)})`}
);
@@ -244,9 +241,9 @@ export function ChartWheel({
return (
- {pointName(p.id)}: {dms(p.degree_in_sign_dms)} {signName(p.sign)}
- {p.retrograde ? ", retrográd" : ""}
- {timeKnown && p.house ? `, ${p.house}. ház` : ""}
+ {`${pointName(p.id)}: ${dms(p.degree_in_sign_dms)} ${signName(p.sign)}${p.retrograde ? ", retrográd" : ""}${
+ timeKnown && p.house ? `, ${p.house}. ház` : ""
+ }`}
diff --git a/services/frontend/src/components/SynastryWheel.tsx b/services/frontend/src/components/SynastryWheel.tsx
index bb481b0..f61d6e5 100644
--- a/services/frontend/src/components/SynastryWheel.tsx
+++ b/services/frontend/src/components/SynastryWheel.tsx
@@ -72,9 +72,9 @@ function Ring({
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` : ""}
+ {`${who}: ${pointName(p.id)} ${dms(p.degree_in_sign_dms)} ${signName(p.sign)}${p.retrograde ? ", retrográd" : ""}${
+ timeKnown && p.house ? `, ${p.house}. ház` : ""
+ }`}
@@ -208,9 +208,7 @@ export function SynastryWheel({
const [x, y] = xy(a.longitude, R_LABEL, start);
return (
-
- {name1}: {pointName(key)} {dms(a.degree_in_sign_dms)} {signName(a.sign)}
-
+ {`${name1}: ${pointName(key)} ${dms(a.degree_in_sign_dms)} ${signName(a.sign)}`}
{label}
);
@@ -236,8 +234,7 @@ export function SynastryWheel({
strokeWidth={(0.6 + 1.9 * s).toFixed(2)}
>
- {name1} {pointName(a.person1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {name2} {pointName(a.person2)} (orbis{" "}
- {orbText(a.orb)})
+ {`${name1} ${pointName(a.person1)} ${ASPECTS[a.aspect]?.hu ?? a.aspect} ${name2} ${pointName(a.person2)} (orbis ${orbText(a.orb)})`}
);
From 8e1205359dd5c12e454ebee17ac66ea5faec4fa7 Mon Sep 17 00:00:00 2001
From: feco
Date: Thu, 19 Nov 2026 11:07:13 +0000
Subject: [PATCH 5/6] Inviting shown but off until launch; waitlist
confirmation; waitlist invites with a package
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
USER_INVITES (default false) keeps users from inviting others until the
launch: the 'Meghívom' option and a 'Hívd meg, akit szeretsz' card on the
persons page are shown, disabled, with 'Hamarosan'; the backend refuses
with invites_disabled (admins may always).
Joining the waitlist sends one confirmation e-mail (waitlist_joined) with a
link that takes the address off the list and opts it out; at most 10 per
address in 15 minutes. Admins can pick a package for waitlist invitations,
like on the invitation form.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
---
crates/db/migrations/0025_waitlist_token.sql | 3 +
crates/email-templates/src/lib.rs | 63 +++++++++++++++
deploy/docker-compose.yml | 2 +
docs/promokodok.md | 7 ++
docs/szemely-meghivas.md | 2 +
services/backend/src/config.rs | 6 ++
services/backend/src/routes/invitations.rs | 40 +++++++--
services/backend/src/routes/mod.rs | 1 +
services/backend/src/routes/synastries.rs | 3 +
services/backend/src/tests.rs | 81 +++++++++++++++++++
.../app/admin/meghivok/AdminInvitations.tsx | 18 ++++-
services/frontend/src/app/globals.css | 5 ++
.../src/app/leiratkozas/Unsubscribe.tsx | 5 +-
.../frontend/src/app/leiratkozas/page.tsx | 2 +-
services/frontend/src/app/szemelyek/page.tsx | 53 ++++++++----
.../src/app/szemelyek/uj/NewPersonChooser.tsx | 17 +++-
.../frontend/src/app/szemelyek/uj/page.tsx | 1 +
services/frontend/src/lib/types.ts | 2 +
18 files changed, 285 insertions(+), 26 deletions(-)
create mode 100644 crates/db/migrations/0025_waitlist_token.sql
diff --git a/crates/db/migrations/0025_waitlist_token.sql b/crates/db/migrations/0025_waitlist_token.sql
new file mode 100644
index 0000000..d491b3b
--- /dev/null
+++ b/crates/db/migrations/0025_waitlist_token.sql
@@ -0,0 +1,3 @@
+-- The link in the waitlist confirmation e-mail that takes the address off
+-- the list (only its hash is kept).
+ALTER TABLE waitlist ADD COLUMN token_hash bytea UNIQUE;
diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs
index 2f54b89..73b97b8 100644
--- a/crates/email-templates/src/lib.rs
+++ b/crates/email-templates/src/lib.rs
@@ -159,6 +159,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result invitation(lang, payload, url)?,
("synastry_invite", _) => synastry_invite(lang, payload, url)?,
+ ("waitlist_joined", _) => waitlist_joined(lang, payload, url)?,
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
Ok(content.render(lang))
@@ -283,6 +284,56 @@ fn name(payload: &Value, field: &str) -> Option {
(!name.is_empty()).then(|| name.to_owned())
}
+/// The confirmation of a waitlist sign-up, with the link that takes the address off the list.
+fn waitlist_joined(lang: Lang, payload: &Value, url: String) -> Result {
+ let unsubscribe_url = field(payload, "unsubscribe_url")?;
+ let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
+ Ok(match lang {
+ Lang::Hu => Content {
+ subject: "Felírtunk a Sorsfonalak várólistájára".into(),
+ preheader: Some("Amint bejuthatsz, ide írunk.".into()),
+ greeting: "Szia!".into(),
+ intro: "Köszönjük, hogy kíváncsi vagy a Sorsfonalakra! Az oldal egyelőre zártkörű, de felírtunk a várólistára: amint bejuthatsz, erre a címre írunk."
+ .into(),
+ quote: None,
+ points: Some((
+ "Mi vár rád?",
+ vec![
+ "a születési képleted percre pontosan kiszámolva és megrajzolva, egy rövid elemzéssel,",
+ "részletes elemzés, éves előrejelzés és kapcsolati összevetés azokkal, akiket szeretsz.",
+ ],
+ )),
+ button: "Körülnézek",
+ url,
+ note: "Ha nem te iratkoztál fel, vagy meggondoltad magad, a lenti linkkel törölheted a címed a listáról.".into(),
+ reason: Some("Ezt a levelet azért kaptad, mert ezt a címet megadták a Sorsfonalak várólistáján.".into()),
+ unsubscribe: Some(("Leiratkozás a várólistáról", unsubscribe_url)),
+ unsubscribe_post_url: Some(unsubscribe_post_url),
+ },
+ Lang::En => Content {
+ subject: "You are on the Sorsfonalak waitlist".into(),
+ preheader: Some("We will write as soon as you can get in.".into()),
+ greeting: "Hi,".into(),
+ intro: "Thanks for your interest in Sorsfonalak! The site is invitation-only for now, but you are on the waitlist: we will write to this address as soon as you can get in."
+ .into(),
+ quote: None,
+ points: Some((
+ "What awaits you:",
+ vec![
+ "your birth chart, calculated to the minute and drawn, with a short reading,",
+ "detailed readings, a yearly forecast and comparisons with the people you love.",
+ ],
+ )),
+ button: "Take a look",
+ url,
+ note: "If it was not you, or you changed your mind, the link below takes your address off the list.".into(),
+ reason: Some("You got this e-mail because this address was entered on the Sorsfonalak waitlist.".into()),
+ unsubscribe: Some(("Leave the waitlist", unsubscribe_url)),
+ unsubscribe_post_url: Some(unsubscribe_post_url),
+ },
+ })
+}
+
/// A user invites someone to compare their charts ("how compatible are we?").
fn synastry_invite(lang: Lang, payload: &Value, url: String) -> Result {
let inviter = name(payload, "inviter_name");
@@ -539,6 +590,18 @@ mod tests {
})
}
+ #[test]
+ fn waitlist_confirmation_has_the_leave_link() {
+ let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
+ assert_eq!(hu.subject, "Felírtunk a Sorsfonalak várólistájára");
+ assert!(
+ hu.text.contains("Leiratkozás a várólistáról: https://sorsfonalak.test/leiratkozas?token=abc"),
+ "{}",
+ hu.text
+ );
+ assert!(hu.unsubscribe_post_url.is_some());
+ }
+
#[test]
fn synastry_invite_names_the_inviter() {
let hu = render("synastry_invite", "hu", &invitation_payload()).unwrap();
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 265e99c..e5af6d7 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -88,6 +88,8 @@ services:
# Purchases are off until real payments are connected; packages come
# from promo codes and admins (MOCK_PAYMENTS=true: pretend purchases).
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-false}
+ # Users inviting others ("Meghívom"): shown but off until the launch.
+ USER_INVITES: ${USER_INVITES:-false}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
diff --git a/docs/promokodok.md b/docs/promokodok.md
index 4a9b4d4..de80cc5 100644
--- a/docs/promokodok.md
+++ b/docs/promokodok.md
@@ -39,6 +39,13 @@ Az Admin → Meghívók oldalon az „Ajándék csomag” választóval minden m
- **Újraküldéskor** a levélben ugyanaz a kód marad.
- **Visszavonás:** a meghívó visszavonása a még fel nem használt kódot is visszavonja.
- **A meghívók listájában** látszik a csomag, és hogy beváltották-e.
+- **A várólistán lévőket** is csomaggal lehet meghívni: a „Várólista” táblázat fölötti választóval a „Meghívás” gomb azzal a csomaggal küldi a meghívót.
+
+## Várólista
+
+- **Visszaigazolás:** aki feliratkozik, egyszer kap egy visszaigazoló levelet (`waitlist_joined`), benne leiratkozó linkkel.
+- **Leiratkozás:** a link leveszi a címet a listáról, és felveszi a „nem kér levelet” listára, így meghívót sem küldünk oda többet.
+- **Korlát:** IP-címenként 15 percen belül legfeljebb 10 levél megy ki, hogy az űrlappal ne lehessen mások postafiókját elárasztani. A lista legfeljebb 10 000 cím.
## API
diff --git a/docs/szemely-meghivas.md b/docs/szemely-meghivas.md
index 0328493..e114392 100644
--- a/docs/szemely-meghivas.md
+++ b/docs/szemely-meghivas.md
@@ -5,6 +5,8 @@ Az „Új személy” oldalon két lehetőség van:
- **Adatok megadása:** a felhasználó maga írja be a születési adatokat. Ez egy személyhelyet használ, ahogy eddig.
- **Meghívom:** egy „Mennyire illünk össze?” meghívó (`synastry_invites`). A meghívott a saját adatait adja meg. Személyhely nem kell hozzá, és akkor is működik, ha a helyek elfogytak.
+**Az élesítésig ki van kapcsolva:** a „Meghívom” lehetőség és a Személyek oldal „Hívd meg, akit szeretsz” kártyája látszik, de „Hamarosan” felirattal le van tiltva. A backend `invites_disabled` hibával utasítja el. Bekapcsolás: `USER_INVITES=true` a szerver `.env` fájljában. Az adminok a kapcsolótól függetlenül meghívhatnak, hogy ki tudják próbálni.
+
## Menete
1. **A meghívó elkészül.** A meghívó megadhatja, kinek szól (ezt csak ő látja), a meghívott e-mail-címét (nem kötelező) és egy üzenetet (legfeljebb 300 karakter, link nélkül). A link `/meghivas/`, 14 napig érvényes. Megosztható másolással, a telefon megosztás menüjével, WhatsAppon vagy Facebookon.
diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs
index 308e89b..499e2d4 100644
--- a/services/backend/src/config.rs
+++ b/services/backend/src/config.rs
@@ -45,6 +45,10 @@ pub struct Config {
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
/// analysis unit at once, until Stripe is connected.
pub mock_payments: bool,
+ /// `USER_INVITES` (default `false`): users may invite others ("how
+ /// compatible are we?" links, which also let the invitee sign up). Off
+ /// until the launch; admins may always.
+ pub user_invites: bool,
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
/// ID token audience; empty disables Google login.
pub google_client_ids: Vec,
@@ -119,6 +123,7 @@ impl Config {
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
password_login: parsed("PASSWORD_LOGIN", false)?,
mock_payments: parsed("MOCK_PAYMENTS", false)?,
+ user_invites: parsed("USER_INVITES", false)?,
google_client_ids: list("GOOGLE_CLIENT_IDS"),
google_jwks_url: var("GOOGLE_JWKS_URL")
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
@@ -156,6 +161,7 @@ impl Config {
session_ttl_days: 30,
password_login: true,
mock_payments: true,
+ user_invites: true,
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
google_jwks_url,
bootstrap_admin_emails: vec!["admin@example.com".into()],
diff --git a/services/backend/src/routes/invitations.rs b/services/backend/src/routes/invitations.rs
index fda232e..c36b859 100644
--- a/services/backend/src/routes/invitations.rs
+++ b/services/backend/src/routes/invitations.rs
@@ -587,10 +587,12 @@ pub async fn unsubscribe(
WithRejection(Query(q), _): WithRejection, ApiError>,
) -> ApiResult> {
let mut tx = state.db.begin().await?;
- // The link of a site invitation, or of a "how compatible are we?" one a user had us e-mail.
+ // The link of a site invitation, of a "how compatible are we?" one a user
+ // had us e-mail, or of the waitlist confirmation.
let email: Option = sqlx::query_scalar(
"SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1 \
UNION ALL SELECT invitee_email FROM synastry_invites WHERE token_hash = $1 AND invitee_email IS NOT NULL \
+ UNION ALL SELECT email FROM waitlist WHERE token_hash = $1 \
LIMIT 1",
)
.bind(db::token_hash(q.token.trim()))
@@ -607,6 +609,7 @@ pub async fn unsubscribe(
.bind(&email)
.execute(&mut *tx)
.await?;
+ sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(&email).execute(&mut *tx).await?;
tx.commit().await?;
Ok(Json(json!({ "unsubscribed": true })))
}
@@ -621,19 +624,46 @@ pub struct WaitlistRequest {
/// Joins the waitlist. Always answers the same, so it does not reveal who has an account.
pub async fn join_waitlist(
State(state): St,
+ headers: axum::http::HeaderMap,
WithRejection(Json(req), _): Body,
) -> ApiResult<(StatusCode, Json)> {
let email = normalize_email(&req.email)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
- sqlx::query(
- "INSERT INTO waitlist (email, locale) SELECT $1, $2 \
+ // Every sign-up sends an e-mail: a few per address, so the form cannot be used to flood someone.
+ let ip = headers
+ .get("x-forwarded-for")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.split(',').next())
+ .map(str::trim)
+ .unwrap_or("unknown");
+ let key = format!("waitlist:{ip}");
+ state.login_limiter.check(&key)?;
+ let token = db::new_token();
+ let mut tx = state.db.begin().await?;
+ let added = sqlx::query(
+ "INSERT INTO waitlist (email, locale, token_hash) SELECT $1, $2, $3 \
WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = $1) \
AND (SELECT count(*) FROM waitlist) < 10000 \
ON CONFLICT DO NOTHING",
)
.bind(&email)
.bind(&locale)
- .execute(&state.db)
- .await?;
+ .bind(db::token_hash(&token))
+ .execute(&mut *tx)
+ .await?
+ .rows_affected()
+ == 1;
+ // A confirmation, once, unless the address asked for no more mail from us.
+ if added && !opted_out(&mut tx, &email).await? {
+ let (_, unsubscribe_url, unsubscribe_post_url) = links(&state, &token);
+ let payload = json!({
+ "url": state.config.public_base_url,
+ "unsubscribe_url": unsubscribe_url,
+ "unsubscribe_post_url": unsubscribe_post_url,
+ });
+ queue_email_to(&mut tx, None, &email, "waitlist_joined", &locale, payload).await?;
+ state.login_limiter.failed(&key);
+ }
+ tx.commit().await?;
Ok((StatusCode::ACCEPTED, Json(json!({ "ok": true }))))
}
diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs
index 3336334..ce27b7f 100644
--- a/services/backend/src/routes/mod.rs
+++ b/services/backend/src/routes/mod.rs
@@ -162,6 +162,7 @@ async fn public_config(State(state): St) -> Json {
"locales": c.supported_locales,
"password_login": c.password_login,
"mock_payments": c.mock_payments,
+ "user_invites": c.user_invites,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
diff --git a/services/backend/src/routes/synastries.rs b/services/backend/src/routes/synastries.rs
index 151ad5e..3370eca 100644
--- a/services/backend/src/routes/synastries.rs
+++ b/services/backend/src/routes/synastries.rs
@@ -260,6 +260,9 @@ pub async fn create_invite(
auth: AuthUser,
WithRejection(Json(req), _): Body,
) -> ApiResult<(StatusCode, Json)> {
+ if !state.config.user_invites && !auth.user.has_role(db::Role::Admin) {
+ return Err(ApiError::conflict("invites_disabled", "A meghívás hamarosan indul."));
+ }
let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
// No links: the message may go out in an e-mail from our domain.
let message = super::invitations::clean_message(req.message)?;
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index 5738de3..6051d5b 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -2056,3 +2056,84 @@ async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) {
(Some(2), Some(1), Some(5))
);
}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn the_waitlist_confirms_and_can_be_left(pool: PgPool) {
+ let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
+ let admin = app.register("admin@example.com", "Admin").await;
+ let from = |ip: &'static str| [("x-forwarded-for", ip)];
+
+ // one confirmation per address, even when sent again
+ for _ in 0..2 {
+ let r = app
+ .call_with(
+ "POST",
+ "/v1/public/waitlist",
+ None,
+ Some(json!({"email": "Wait@Example.com"})),
+ &from("198.51.100.7"),
+ )
+ .await;
+ assert_eq!(r.status, StatusCode::ACCEPTED);
+ }
+ let mails: Vec<(Value,)> = sqlx::query_as(
+ "SELECT payload FROM email_outbox WHERE to_email = 'wait@example.com' AND template = 'waitlist_joined'",
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(mails.len(), 1);
+ let leave = mails[0].0["unsubscribe_post_url"].as_str().unwrap().to_string();
+ let token = leave.rsplit("token=").next().unwrap().to_string();
+
+ // leaving: off the list, and no invitation can be sent there any more
+ let r = app.call("POST", &format!("/v1/public/invitations/unsubscribe?token={token}"), None, None).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ assert!(app.get("/v1/admin/invitations", Some(&admin)).await.body["waitlist"].as_array().unwrap().is_empty());
+ let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["wait@example.com"]})).await;
+ assert_eq!(r.body["results"][0]["status"], "opted_out");
+ // and signing up again sends nothing
+ app.call_with(
+ "POST",
+ "/v1/public/waitlist",
+ None,
+ Some(json!({"email": "wait@example.com"})),
+ &from("198.51.100.8"),
+ )
+ .await;
+ let count: i64 = sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE to_email = 'wait@example.com'")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, 1);
+
+ // one address cannot flood the form
+ let mut last = StatusCode::OK;
+ for i in 0..12 {
+ let r = app
+ .call_with(
+ "POST",
+ "/v1/public/waitlist",
+ None,
+ Some(json!({"email": format!("w{i}@example.com")})),
+ &from("203.0.113.9"),
+ )
+ .await;
+ last = r.status;
+ }
+ assert_eq!(last, StatusCode::TOO_MANY_REQUESTS);
+}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn user_invitations_wait_for_the_launch(pool: PgPool) {
+ let app = TestApp::with_config(pool, |c| c.user_invites = false).await;
+ assert_eq!(app.get("/v1/config", None).await.body["user_invites"], false);
+ let anna = app.register("anna@example.com", "Anna").await;
+ app.chart(&anna, "Saját", true, "1990-03-15").await;
+ let r = app.post("/v1/invites", Some(&anna), json!({"label": "Béla"})).await;
+ assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("invites_disabled")));
+ // admins may, to try it
+ let admin = app.register("admin@example.com", "Admin").await;
+ app.chart(&admin, "Saját", true, "1980-01-01").await;
+ assert_eq!(app.post("/v1/invites", Some(&admin), json!({})).await.status, StatusCode::CREATED);
+}
diff --git a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx
index 90b281c..0602de8 100644
--- a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx
+++ b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx
@@ -403,13 +403,15 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onChange: () => Promise }) {
const [busy, setBusy] = useState(null);
const [note, setNote] = useState(null);
+ const [pkg, setPkg] = useState("");
+ const packages = usePackages();
async function invite(w: WaitlistEntry) {
setBusy(w.email);
setNote(null);
try {
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
- body: { emails: [w.email], locale: w.locale },
+ body: { emails: [w.email], locale: w.locale, package: pkg || null },
});
const r = res.results[0];
if (r && r.status !== "invited") setNote(`${r.email}: ${RESULT[r.status]}`);
@@ -440,6 +442,20 @@ function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onCh
Várólista
Akik meghívó nélkül próbáltak belépni, és kérték, hogy szóljunk nekik.
+ {waitlist.some((w) => w.invitation === null) && (
+
+ Ajándék csomag a meghívottaknak
+ setPkg(e.target.value)}>
+ nincs
+ {(packages ?? []).map((p) => (
+
+ {p.name}
+
+ ))}
+
+ A „Meghívás” gomb ezzel a csomaggal küldi a meghívót; a regisztrációkor magától jóváíródik.
+
+ )}
{note && (
{note}
diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css
index 812d425..58e9666 100644
--- a/services/frontend/src/app/globals.css
+++ b/services/frontend/src/app/globals.css
@@ -909,3 +909,8 @@ a.pair-row:hover strong { color: var(--gold); }
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
}
+
+.mode-option:disabled { cursor: not-allowed; opacity: 0.75; }
+.mode-option:disabled:hover { border-color: var(--line-2); }
+.mode-soon { margin-left: 8px; vertical-align: middle; font-family: var(--font-body); font-size: 11px; }
+.invite-soon .btn:disabled { cursor: not-allowed; }
diff --git a/services/frontend/src/app/leiratkozas/Unsubscribe.tsx b/services/frontend/src/app/leiratkozas/Unsubscribe.tsx
index a83346a..19b84f2 100644
--- a/services/frontend/src/app/leiratkozas/Unsubscribe.tsx
+++ b/services/frontend/src/app/leiratkozas/Unsubscribe.tsx
@@ -20,7 +20,7 @@ export function Unsubscribe({ token }: { token: string | null }) {
if (state === "done") {
return (
- Leiratkoztál: erre a címre nem küldünk több meghívót.
+ Leiratkoztál: erre a címre nem küldünk több meghívót, és levettük a várólistáról.
);
}
@@ -40,7 +40,8 @@ export function Unsubscribe({ token }: { token: string | null }) {
return (
- Ha leiratkozol, erre az e-mail-címre többé nem küldünk meghívót, és a mostani meghívód is érvényét veszti.
+ Ha leiratkozol, erre az e-mail-címre többé nem küldünk meghívót, levesszük a várólistáról, és a mostani meghívód
+ is érvényét veszti.
diff --git a/services/frontend/src/app/leiratkozas/page.tsx b/services/frontend/src/app/leiratkozas/page.tsx
index dbca4c4..2c3473a 100644
--- a/services/frontend/src/app/leiratkozas/page.tsx
+++ b/services/frontend/src/app/leiratkozas/page.tsx
@@ -12,7 +12,7 @@ export default async function UnsubscribePage({ searchParams }: { searchParams:
Leiratkozás
-
Nem kérsz több meghívót a Sorsfonalakra.
+
Nem kérsz több levelet és meghívót a Sorsfonalakról.
diff --git a/services/frontend/src/app/szemelyek/page.tsx b/services/frontend/src/app/szemelyek/page.tsx
index 28a7ba3..4cd9fe1 100644
--- a/services/frontend/src/app/szemelyek/page.tsx
+++ b/services/frontend/src/app/szemelyek/page.tsx
@@ -23,6 +23,7 @@ export default async function PersonsPage() {
const isAdmin = me.user.roles.includes("admin");
const slots = me.persons;
const full = slots.left === 0;
+ const invitesOpen = (config?.user_invites ?? false) || isAdmin;
const now = Date.now();
return (
@@ -47,22 +48,46 @@ export default async function PersonsPage() {
))}
-
-
- +
-
- Új személy
-
- {full
- ? "Meghívással bármikor"
- : slots.unlimited
- ? "Adatokkal vagy meghívással"
- : `Még ${slots.left} személyt vehetsz fel, vagy hívd meg`}
-
-
+ {(!full || invitesOpen) && (
+
+
+ +
+
+ Új személy
+
+ {!invitesOpen
+ ? slots.unlimited
+ ? "Korlátlan számú személy"
+ : `Még ${slots.left} személyt vehetsz fel`
+ : full
+ ? "Meghívással bármikor"
+ : slots.unlimited
+ ? "Adatokkal vagy meghívással"
+ : `Még ${slots.left} személyt vehetsz fel, vagy hívd meg`}
+
+
+ )}
-
+ {invitesOpen ? (
+
+ ) : (
+
+
+
Hívd meg, akit szeretsz
+ Hamarosan
+
+
+ Hamarosan te is meghívhatod a barátaidat, a családodat vagy a párodat: ők megadják a saját születési adataikat,
+ ingyen megkapják a képletüket, és együtt megnézitek, mennyire illetek össze.
+
+
+
+ Meghívó küldése
+
+
+
+ )}
{!slots.unlimited && (
diff --git a/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx b/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
index 495745e..baa3250 100644
--- a/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
+++ b/services/frontend/src/app/szemelyek/uj/NewPersonChooser.tsx
@@ -14,16 +14,19 @@ import { NewPerson } from "./NewPerson";
export function NewPersonChooser({
canAdd,
hasOwnChart,
+ invitesOpen,
full,
}: {
/** A slot is free for typed-in data. */
canAdd: boolean;
+ /** Inviting is on (until the launch it is shown, but off). */
+ invitesOpen: boolean;
/** Inviting compares with the user's own chart. */
hasOwnChart: boolean;
/** Shown instead of the form when no slot is left. */
full: React.ReactNode;
}) {
- const [mode, setMode] = useState<"data" | "invite">(canAdd ? "data" : "invite");
+ const [mode, setMode] = useState<"data" | "invite">(canAdd || !invitesOpen ? "data" : "invite");
return (
@@ -41,11 +44,19 @@ export function NewPersonChooser({
type="button"
role="tab"
aria-selected={mode === "invite"}
+ aria-disabled={!invitesOpen}
+ disabled={!invitesOpen}
className="mode-option"
onClick={() => setMode("invite")}
>
- Meghívom
- Ő adja meg a saját adatait, és megnézitek, mennyire illetek össze. Ingyenes, nem kell hozzá hely.
+
+ Meghívom {!invitesOpen && Hamarosan }
+
+
+ {invitesOpen
+ ? "Ő adja meg a saját adatait, és megnézitek, mennyire illetek össze. Ingyenes, nem kell hozzá hely."
+ : "Hamarosan meghívhatod azokat, akiket szeretsz: ők adják meg a saját adataikat, és együtt nézitek meg, mennyire illetek össze."}
+
{mode === "data" ? (
diff --git a/services/frontend/src/app/szemelyek/uj/page.tsx b/services/frontend/src/app/szemelyek/uj/page.tsx
index d3de651..05d0fe6 100644
--- a/services/frontend/src/app/szemelyek/uj/page.tsx
+++ b/services/frontend/src/app/szemelyek/uj/page.tsx
@@ -27,6 +27,7 @@ export default async function NewPersonPage() {
Elfogytak a helyeid. Újabb személyhez válassz csomagot, vagy hívd meg.
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 26bbd3f..a687c3b 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -92,6 +92,8 @@ export interface PublicConfig {
mock_payments: boolean;
/** "invite": new accounts need an invitation. */
signup_mode: "invite" | "open";
+ /** Users may invite others (off until the launch; admins always may). */
+ user_invites: boolean;
}
export interface Position {
From 0e3eaee7351d1ebbaf25fdb9558b5bc22c8c7ded Mon Sep 17 00:00:00 2001
From: feco
Date: Thu, 19 Nov 2026 11:24:49 +0000
Subject: [PATCH 6/6] Share rewards: a question for a visit, an analysis for a
new user
A click proves little, so the first visit of a shared link now earns a
question (once per user) instead of a natal analysis. A natal analysis is
earned by bringing a new user: the share page remembers the link, the
Google sign-up sends it, and when that user makes their own chart the
sharer gets one, at most three (referrals table, referral_reward). This is
off until sign-up opens (REFERRAL_REWARDS, default false). The share button
and its small print follow; /v1/me tells what was earned.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
---
crates/db/migrations/0026_referrals.sql | 19 +++++
deploy/docker-compose.yml | 2 +
docs/megosztas.md | 20 +++--
services/backend/src/config.rs | 6 ++
services/backend/src/routes/account.rs | 5 +-
services/backend/src/routes/auth.rs | 7 ++
services/backend/src/routes/charts.rs | 4 +
services/backend/src/routes/mod.rs | 1 +
services/backend/src/routes/shares.rs | 74 ++++++++++++++++-
services/backend/src/tests.rs | 80 +++++++++++++++++--
.../frontend/src/app/belepes/GoogleLogin.tsx | 13 ++-
.../frontend/src/app/kepletek/[id]/page.tsx | 2 +
.../frontend/src/components/ChartSummary.tsx | 14 +++-
.../frontend/src/components/ShareChart.tsx | 35 +++++---
.../frontend/src/components/ShareVisit.tsx | 6 ++
services/frontend/src/lib/types.ts | 6 +-
16 files changed, 265 insertions(+), 29 deletions(-)
create mode 100644 crates/db/migrations/0026_referrals.sql
diff --git a/crates/db/migrations/0026_referrals.sql b/crates/db/migrations/0026_referrals.sql
new file mode 100644
index 0000000..be3c4b2
--- /dev/null
+++ b/crates/db/migrations/0026_referrals.sql
@@ -0,0 +1,19 @@
+-- Sharing pays in two steps: the first visit of a shared link earns a
+-- question (`share_reward`, see shares.rs), and someone who signs up from a
+-- shared link and makes their own chart earns the sharer a natal analysis
+-- (`referral_reward`, at most three per user).
+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',
+ 'question', 'share_reward', 'referral_reward'));
+
+-- Who came through whose shared link (one row per new user).
+CREATE TABLE referrals (
+ user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
+ referrer_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ share_id uuid REFERENCES shares (id) ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ -- Set when the new user made their own chart (rewarded or over the limit).
+ rewarded_at timestamptz
+);
+CREATE INDEX referrals_referrer_idx ON referrals (referrer_id);
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index e5af6d7..b09292f 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -90,6 +90,8 @@ services:
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-false}
# Users inviting others ("Meghívom"): shown but off until the launch.
USER_INVITES: ${USER_INVITES:-false}
+ # A new user from a shared link earns the sharer an analysis: off until sign-up opens.
+ REFERRAL_REWARDS: ${REFERRAL_REWARDS:-false}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
diff --git a/docs/megosztas.md b/docs/megosztas.md
index b706466..ce3150e 100644
--- a/docs/megosztas.md
+++ b/docs/megosztas.md
@@ -6,20 +6,28 @@ A képletoldalon, a rövid összefoglaló alatt van a **Megosztás** gomb. Ez eg
- **Visszavonás:** a „Link visszavonása” gomb után az oldal és a kép is 404-et ad.
- **Keresők:** az oldal `noindex`, a keresők nem listázzák.
-## Ajándék elemzés a megosztásért
+## Jutalom a megosztásért
-**Mit kap:** felhasználónként **egyszer** +1 képletelemzést, amikor valaki más először megnyitja a megosztott linkjét. A gomb apró betűvel kiírja: „+1 ajándék elemzés jár érte, ha valaki megnézi”. Ha már megkapta, ezt: „Az ajándék elemzést már megkaptad”.
+Egy kattintás önmagában semmit nem bizonyít, ezért kétféle jutalom van:
-**Hogyan számolunk:**
+- **Ajándék kérdés (megtekintésért):** felhasználónként **egyszer** +1 kérdés, amikor valaki más először megnyitja a megosztott linkjét. A gomb apró betűvel: „+1 ajándék kérdés, ha valaki megnézi”.
+- **Ajándék képletelemzés (új felhasználóért):** +1 képletelemzés, ha valaki a megosztott linkről regisztrál és elkészíti a saját képletét. Felhasználónként legfeljebb 3 (`REFERRAL_LIMIT`). Az élesítésig ki van kapcsolva (`REFERRAL_REWARDS=false`), mert meghívásos regisztrációnál a linkről úgysem lehet regisztrálni.
-- **A böngésző jelez.** A látogatást a megosztott oldal betöltése után maga a látogató böngészője jelzi (`POST /v1/public/shares/{slug}/visit`). Az előnézet-robotok nem futtatják az oldal szkriptjét, így ők nem számítanak.
+**Megtekintés számolása:**
+
+- **A böngésző jelez:** a megosztott oldal betöltése után maga a látogató böngészője jelzi a látogatást (`POST /v1/public/shares/{slug}/visit`). Az előnézet-robotok nem futtatják az oldal szkriptjét, így ők nem számítanak.
- **Ami nem számít:**
- robotnak látszó vagy hiányzó böngészőazonosító;
- a belépett tulajdonos;
- látogatás arról az IP-címről, ahonnan a linket létrehozták. A cím a sluggal sózva, hash-ként van tárolva (`shares.owner_ip_hash`).
- **Számláló:** a `shares.view_count` csak ezeket a valódi látogatásokat számolja.
-- **Jutalom egyszer:** a `credit_ledger` `share_reward` sora egyedi indexszel felhasználónként csak egyszer jöhet létre (`credit_ledger_share_reward_once`).
-- **`/v1/me`:** a `share_reward_granted` jelzi, ha már megkapta.
+- **Jutalom egyszer:** a `share_reward` sor egyedi indexszel felhasználónként egyszer jöhet létre.
+
+**Új felhasználó:**
+
+- **Megjegyzés:** a megosztott oldal a böngészőben megjegyzi a link kódját (`localStorage` `sf_ref`). A Google-regisztráció elküldi (`referral`), és a backend a `referrals` táblába írja, hogy kit ki hozott. Saját link, visszavont link vagy kikapcsolt jutalom esetén nem írja be.
+- **Jutalom:** amikor az új felhasználó elkészíti a saját képletét, a megosztó +1 képletelemzést kap (`referral_reward`), ha még nem érte el a hármat. Új felhasználónként egyszer.
+- **`/v1/me`:** a `share_reward_granted` és a `referral_rewards` (`{earned, limit}`) mezők mutatják az állapotot.
## Robotok
diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs
index 499e2d4..d9fbc77 100644
--- a/services/backend/src/config.rs
+++ b/services/backend/src/config.rs
@@ -49,6 +49,10 @@ pub struct Config {
/// compatible are we?" links, which also let the invitee sign up). Off
/// until the launch; admins may always.
pub user_invites: bool,
+ /// `REFERRAL_REWARDS` (default `false`): someone who signs up from a
+ /// shared link and makes their own chart earns the sharer a natal
+ /// analysis (at most three). Off until sign-up opens.
+ pub referral_rewards: bool,
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
/// ID token audience; empty disables Google login.
pub google_client_ids: Vec,
@@ -124,6 +128,7 @@ impl Config {
password_login: parsed("PASSWORD_LOGIN", false)?,
mock_payments: parsed("MOCK_PAYMENTS", false)?,
user_invites: parsed("USER_INVITES", false)?,
+ referral_rewards: parsed("REFERRAL_REWARDS", false)?,
google_client_ids: list("GOOGLE_CLIENT_IDS"),
google_jwks_url: var("GOOGLE_JWKS_URL")
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
@@ -162,6 +167,7 @@ impl Config {
password_login: true,
mock_payments: true,
user_invites: true,
+ referral_rewards: true,
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
google_jwks_url,
bootstrap_admin_emails: vec!["admin@example.com".into()],
diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs
index b46b8c3..46951f3 100644
--- a/services/backend/src/routes/account.rs
+++ b/services/backend/src/routes/account.rs
@@ -34,6 +34,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> {
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
let package = crate::packages::current(&mut conn, auth.id()).await?;
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
+ let referrals = super::shares::referral_rewards(&mut conn, auth.id()).await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::>(),
@@ -42,8 +43,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult> {
"birth_change": birth_change,
"persons": persons.view(),
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
- // The free analysis for a shared link is used up (once per user).
+ // The free question for a shared link is used up (once per user).
"share_reward_granted": share_reward,
+ // Natal analyses earned by bringing new users, and how many can be.
+ "referral_rewards": { "earned": referrals, "limit": super::shares::REFERRAL_LIMIT },
})))
}
diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs
index e0576bc..092eba5 100644
--- a/services/backend/src/routes/auth.rs
+++ b/services/backend/src/routes/auth.rs
@@ -170,6 +170,8 @@ pub struct RegisterRequest {
locale: Option,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option,
+ /// The slug of the shared link the visitor came from.
+ referral: Option,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
@@ -224,6 +226,7 @@ pub async fn register(
state.config.free_person_slots,
)
.await?;
+ super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref()).await?;
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
queue_verification(&state, &mut tx, &user).await?;
@@ -291,6 +294,8 @@ pub struct GoogleRequest {
id_token: String,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option,
+ /// The slug of the shared link the visitor came from.
+ referral: Option,
}
/// Logs in with Google. An unknown Google account is linked to the existing
@@ -362,6 +367,8 @@ pub async fn google(
state.config.free_person_slots,
)
.await?;
+ super::shares::record_referral(&mut tx, state.config.referral_rewards, id, req.referral.as_deref())
+ .await?;
(id, true)
}
};
diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs
index 7758778..b84fe88 100644
--- a/services/backend/src/routes/charts.rs
+++ b/services/backend/src/routes/charts.rs
@@ -184,6 +184,7 @@ pub async fn create(
birth_changes::record(&mut tx, &auth, row.id).await?;
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
+ super::shares::reward_referral(&state, auth.id()).await?;
return Ok((StatusCode::OK, Json(row.owner_view())));
}
queue_summary(&state, &auth, &chart).await;
@@ -231,6 +232,9 @@ pub async fn create(
}
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
+ if row.is_primary {
+ super::shares::reward_referral(&state, auth.id()).await?;
+ }
Ok((StatusCode::CREATED, Json(row.owner_view())))
}
diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs
index ce27b7f..915a04f 100644
--- a/services/backend/src/routes/mod.rs
+++ b/services/backend/src/routes/mod.rs
@@ -163,6 +163,7 @@ async fn public_config(State(state): St) -> Json {
"password_login": c.password_login,
"mock_payments": c.mock_payments,
"user_invites": c.user_invites,
+ "referral_rewards": c.referral_rewards,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
diff --git a/services/backend/src/routes/shares.rs b/services/backend/src/routes/shares.rs
index 2253f22..c122198 100644
--- a/services/backend/src/routes/shares.rs
+++ b/services/backend/src/routes/shares.rs
@@ -9,8 +9,10 @@
//! share page reports a visit from the visitor's browser
//! (`POST /v1/public/shares/{slug}/visit`): it is counted unless it comes
//! from a robot or from the sharer (logged in, or from the address the link
-//! was made at). The sharer's first such visit earns one free natal analysis,
-//! once per user.
+//! was made at). The sharer's first such visit earns one free question, once
+//! per user: a click proves little. A natal analysis is earned by bringing a
+//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
+//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
use axum::Json;
use axum::extract::{Path, State};
@@ -332,7 +334,7 @@ pub async fn visit(
sqlx::query("UPDATE shares SET view_count = view_count + 1 WHERE id = $1").bind(share.id).execute(&mut *tx).await?;
let rewarded = sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
- VALUES ($1, $2, 'natal', 1, 'share_reward', $3) ON CONFLICT DO NOTHING",
+ VALUES ($1, $2, 'question', 1, 'share_reward', $3) ON CONFLICT DO NOTHING",
)
.bind(Uuid::now_v7())
.bind(share.owner_id)
@@ -348,6 +350,72 @@ pub async fn visit(
Ok(Json(json!({ "counted": true })))
}
+/// Natal analyses a user can earn by bringing new users through shared links.
+pub const REFERRAL_LIMIT: i64 = 3;
+
+/// A new user came from a shared link (`slug`): remembered for the reward,
+/// unless rewards are off, the link is unknown or revoked, or it is their own.
+pub(super) async fn record_referral(
+ conn: &mut sqlx::PgConnection,
+ enabled: bool,
+ user_id: Uuid,
+ slug: Option<&str>,
+) -> Result<(), sqlx::Error> {
+ let Some(slug) = slug.map(str::trim).filter(|s| enabled && !s.is_empty()) else {
+ return Ok(());
+ };
+ sqlx::query(
+ "INSERT INTO referrals (user_id, referrer_id, share_id) \
+ SELECT $1, owner_id, id FROM shares WHERE slug = $2 AND revoked_at IS NULL AND owner_id <> $1 \
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(user_id)
+ .bind(slug)
+ .execute(conn)
+ .await?;
+ Ok(())
+}
+
+/// The new user made their own chart: the sharer who brought them gets a
+/// natal analysis, while under the limit. Runs once per new user.
+pub(super) async fn reward_referral(state: &crate::AppState, user_id: Uuid) -> Result<(), ApiError> {
+ if !state.config.referral_rewards {
+ return Ok(());
+ }
+ let mut tx = state.db.begin().await?;
+ let referrer: Option =
+ sqlx::query_scalar("SELECT referrer_id FROM referrals WHERE user_id = $1 AND rewarded_at IS NULL FOR UPDATE")
+ .bind(user_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some(referrer) = referrer else { return Ok(()) };
+ sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(referrer).execute(&mut *tx).await?;
+ let earned = referral_rewards(&mut tx, referrer).await?;
+ if earned < REFERRAL_LIMIT {
+ sqlx::query(
+ "INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
+ VALUES ($1, $2, 'natal', 1, 'referral_reward', $3)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(referrer)
+ .bind(format!("new user {user_id} from a shared link"))
+ .execute(&mut *tx)
+ .await?;
+ tracing::info!(referrer = %referrer, user = %user_id, "referral reward granted");
+ }
+ sqlx::query("UPDATE referrals SET rewarded_at = now() WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(())
+}
+
+/// Natal analyses the user has earned by bringing new users.
+pub async fn referral_rewards(conn: &mut sqlx::PgConnection, user_id: Uuid) -> Result {
+ sqlx::query_scalar("SELECT count(*) FROM credit_ledger WHERE user_id = $1 AND reason = 'referral_reward'")
+ .bind(user_id)
+ .fetch_one(conn)
+ .await
+}
+
/// Whether the user has already received the reward for sharing.
pub async fn reward_granted(db: &PgPool, user_id: Uuid) -> Result {
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM credit_ledger WHERE user_id = $1 AND reason = 'share_reward')")
diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs
index 6051d5b..a6aa502 100644
--- a/services/backend/src/tests.rs
+++ b/services/backend/src/tests.rs
@@ -801,7 +801,7 @@ const PUBLIC_ROUTES: [&str; 15] = [
];
#[sqlx::test(migrator = "db::MIGRATOR")]
-async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
+async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) {
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
@@ -812,7 +812,7 @@ async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
let visit = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
let browser = ("user-agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148");
let me = || async { app.get("/v1/me", Some(&anna)).await.body };
- let before = me().await["analyses_left"]["natal"].as_i64().unwrap();
+ let before = me().await["analyses_left"]["question"].as_i64().unwrap();
// robots, a missing user agent, the sharer's address and the sharer do not count
let elsewhere = ("x-forwarded-for", "198.51.100.1, 172.70.1.1");
@@ -826,7 +826,10 @@ async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
assert_eq!((r.status, &r.body["counted"]), (StatusCode::OK, &json!(false)), "{headers:?}");
}
let body = me().await;
- assert_eq!((body["analyses_left"]["natal"].as_i64(), &body["share_reward_granted"]), (Some(before), &json!(false)));
+ assert_eq!(
+ (body["analyses_left"]["question"].as_i64(), &body["share_reward_granted"]),
+ (Some(before), &json!(false))
+ );
// reading the share counts nothing either
app.get(&visit.replace("/visit", ""), None).await;
@@ -837,7 +840,7 @@ async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
}
let body = me().await;
assert_eq!(
- (body["analyses_left"]["natal"].as_i64(), &body["share_reward_granted"]),
+ (body["analyses_left"]["question"].as_i64(), &body["share_reward_granted"]),
(Some(before + 1), &json!(true))
);
let r = app.get("/v1/shares", Some(&anna)).await;
@@ -848,7 +851,7 @@ async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
app.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart["id"], "title": "Új"})).await;
let other = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
app.call_with("POST", &other, None, None, &[browser, elsewhere]).await;
- assert_eq!(me().await["analyses_left"]["natal"].as_i64(), Some(before + 1));
+ assert_eq!(me().await["analyses_left"]["question"].as_i64(), Some(before + 1));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -2137,3 +2140,70 @@ async fn user_invitations_wait_for_the_launch(pool: PgPool) {
app.chart(&admin, "Saját", true, "1980-01-01").await;
assert_eq!(app.post("/v1/invites", Some(&admin), json!({})).await.status, StatusCode::CREATED);
}
+
+#[sqlx::test(migrator = "db::MIGRATOR")]
+async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
+ let app = TestApp::new(pool.clone()).await;
+ let anna = app.register("anna@example.com", "Anna").await;
+ let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
+ let r = app.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart["id"]})).await;
+ let slug = r.body["slug"].as_str().unwrap().to_string();
+ let natal = |token: String| {
+ let app = &app;
+ async move { app.get("/v1/me", Some(&token)).await.body["analyses_left"]["natal"].as_i64().unwrap() }
+ };
+ let before = natal(anna.clone()).await;
+ let join = |email: String| {
+ let (app, slug) = (&app, slug.clone());
+ async move {
+ let r = app
+ .post(
+ "/v1/auth/register",
+ None,
+ json!({"email": email, "password": "titkos-jelszo-123", "referral": slug}),
+ )
+ .await;
+ assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
+ r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| {
+ let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
+ cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string()
+ })
+ }
+ };
+
+ // signing up is not enough: the reward comes with their own chart
+ let bela = join("bela@example.com".into()).await;
+ assert_eq!(natal(anna.clone()).await, before);
+ app.chart(&bela, "Saját", true, "1985-08-02").await;
+ assert_eq!(natal(anna.clone()).await, before + 1);
+ // a second chart of theirs changes nothing
+ app.chart(&bela, "Másik", false, "1970-01-01").await;
+ assert_eq!(natal(anna.clone()).await, before + 1);
+
+ // at most three
+ for i in 0..3 {
+ let t = join(format!("p{i}@example.com")).await;
+ app.chart(&t, "Saját", true, "1980-05-05").await;
+ }
+ assert_eq!(natal(anna.clone()).await, before + 3);
+ let me = app.get("/v1/me", Some(&anna)).await.body;
+ assert_eq!(me["referral_rewards"], json!({"earned": 3, "limit": 3}));
+
+ // nothing while the rewards are off
+ let off = TestApp::with_config(pool, |c| c.referral_rewards = false).await;
+ let r = off
+ .post(
+ "/v1/auth/register",
+ None,
+ json!({"email": "late@example.com", "password": "titkos-jelszo-123", "referral": slug}),
+ )
+ .await;
+ assert_eq!(r.status, StatusCode::CREATED);
+ let count: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM referrals r JOIN users u ON u.id = r.user_id WHERE u.email = 'late@example.com'",
+ )
+ .fetch_one(&off.pool)
+ .await
+ .unwrap();
+ assert_eq!(count, 0);
+}
diff --git a/services/frontend/src/app/belepes/GoogleLogin.tsx b/services/frontend/src/app/belepes/GoogleLogin.tsx
index c38fb57..11a317f 100644
--- a/services/frontend/src/app/belepes/GoogleLogin.tsx
+++ b/services/frontend/src/app/belepes/GoogleLogin.tsx
@@ -72,7 +72,18 @@ export function GoogleLogin({
setError(null);
setUninvited(null);
try {
- await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken } });
+ let referral: string | null = null;
+ try {
+ referral = localStorage.getItem("sf_ref");
+ } catch {
+ // storage blocked
+ }
+ await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken, referral } });
+ try {
+ localStorage.removeItem("sf_ref");
+ } catch {
+ // storage blocked
+ }
router.replace(target);
router.refresh();
} catch (e) {
diff --git a/services/frontend/src/app/kepletek/[id]/page.tsx b/services/frontend/src/app/kepletek/[id]/page.tsx
index 880b2df..e985071 100644
--- a/services/frontend/src/app/kepletek/[id]/page.tsx
+++ b/services/frontend/src/app/kepletek/[id]/page.tsx
@@ -78,6 +78,8 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
detailedDone={detailed?.status === "done"}
isAdmin={me.user.roles.includes("admin")}
shareRewardGranted={me.share_reward_granted}
+ referralOpen={config?.referral_rewards ?? false}
+ referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
/>
{(elements || modalities || phase) && (
diff --git a/services/frontend/src/components/ChartSummary.tsx b/services/frontend/src/components/ChartSummary.tsx
index 1b8839d..9566748 100644
--- a/services/frontend/src/components/ChartSummary.tsx
+++ b/services/frontend/src/components/ChartSummary.tsx
@@ -26,6 +26,8 @@ export function ChartSummary({
detailedDone = false,
isAdmin = false,
shareRewardGranted = false,
+ referralOpen = false,
+ referralsLeft = 0,
}: {
chartId: string;
initial: Analysis | null;
@@ -33,8 +35,11 @@ export function ChartSummary({
detailedDone?: boolean;
/** Admins can write the summary again. */
isAdmin?: boolean;
- /** The free analysis for sharing is used up. */
+ /** The free question for sharing is used up. */
shareRewardGranted?: boolean;
+ /** New users from shared links earn analyses, and how many more can be. */
+ referralOpen?: boolean;
+ referralsLeft?: number;
}) {
const [summary, setSummary] = useState(initial);
const [gaveUp, setGaveUp] = useState(false);
@@ -85,7 +90,12 @@ export function ChartSummary({
-
+
0;
+ const perks = [
+ !rewardGranted && "+1 ajándék kérdés, ha valaki megnézi",
+ referral && "+1 elemzés, ha valaki a linkedről csatlakozik",
+ ].filter(Boolean);
const [share, setShare] = useState(null);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState(false);
@@ -88,11 +105,7 @@ export function ShareChart({ chartId, rewardGranted = false }: { chartId: string
{busy ? "Link készül…" : "Oszd meg a képleted"}
-
- {rewardGranted
- ? "Küldd el a barátaidnak, vagy tedd ki Facebookra"
- : "+1 ajándék elemzés jár érte, ha valaki megnézi"}
-
+ {perks.length > 0 ? perks.join(" · ") : "Küldd el a barátaidnak, vagy tedd ki Facebookra"}
{revoked && A linket visszavontad.
}
@@ -114,8 +127,10 @@ export function ShareChart({ chartId, rewardGranted = false }: { chartId: string
{rewardGranted
- ? "Az ajándék elemzést már megkaptad. Köszönjük, hogy megosztottad!"
- : "Ajándék képletelemzés egyszer jár: amikor valaki más először megnyitja a linkedet. A saját megnyitásod nem számít."}
+ ? "Az ajándék kérdést már megkaptad. Köszönjük, hogy megosztottad!"
+ : "Ajándék kérdés egyszer jár: amikor valaki más először megnyitja a linkedet. A saját megnyitásod nem számít."}
+ {referral &&
+ ` Ha valaki a linkedről regisztrál és elkészíti a képletét, egy képletelemzést is kapsz (még ${referralsLeft} szerezhető).`}
{
const key = `share-visit:${slug}`;
+ try {
+ // If they sign up later, the sharer who brought them is remembered.
+ localStorage.setItem("sf_ref", slug);
+ } catch {
+ // storage blocked
+ }
try {
if (sessionStorage.getItem(key)) return;
sessionStorage.setItem(key, "1");
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index a687c3b..e74b3e1 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -21,8 +21,10 @@ export interface Me {
persons: PersonSlots;
/** The latest main package bought or given (null: none). */
package: { id: string; name: string; since: string } | null;
- /** The free analysis for a shared link is used up (once per user). */
+ /** The free question for a shared link is used up (once per user). */
share_reward_granted: boolean;
+ /** Natal analyses earned by bringing new users through shared links. */
+ referral_rewards: { earned: number; limit: number };
}
/** A package from the catalog (`GET /v1/packages`). */
@@ -94,6 +96,8 @@ export interface PublicConfig {
signup_mode: "invite" | "open";
/** Users may invite others (off until the launch; admins always may). */
user_invites: boolean;
+ /** A new user from a shared link earns the sharer an analysis (off until sign-up opens). */
+ referral_rewards: boolean;
}
export interface Position {