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.

+
+ +
+ {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 ( +
+
+ + +
+ {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()} + /> + +
+
+ {typeof navigator !== "undefined" && "share" in navigator && ( + + )} + + WhatsApp + + + Facebook + + +
+

+ A meghívó 14 napig érvényes. Amikor elfogadja, levelet kapsz, és az összevetés megjelenik az Összevetéseid + között. +

+
+ ); + } + + return ( +
+
+
+ + setLabel(e.target.value)} + placeholder="pl. Anna" + /> + Csak te látod, a meghívóid között. +
+
+ + setEmail(e.target.value)} + placeholder="anna@pelda.hu" + autoComplete="off" + /> + Ha megadod, levélben is elküldjük neki. +
+
+
+ +