diff --git a/crates/db/migrations/0022_promo_codes.sql b/crates/db/migrations/0022_promo_codes.sql new file mode 100644 index 0000000..816e00e --- /dev/null +++ b/crates/db/migrations/0022_promo_codes.sql @@ -0,0 +1,23 @@ +-- Promo codes: an admin makes them for a package, a user redeems one once +-- and gets the package (a `package_orders` row with source `promo`). +CREATE TABLE promo_codes ( + id uuid PRIMARY KEY, + -- Upper case, without separators (shown in groups of four). + code text NOT NULL UNIQUE CHECK (code ~ '^[2-9A-HJKMNP-Z]{8,32}$'), + package text NOT NULL, + -- Who it is for or which campaign (admin only). + note text, + created_by uuid REFERENCES users (id) ON DELETE SET NULL, + created_at timestamptz NOT NULL DEFAULT now(), + redeemed_by uuid REFERENCES users (id) ON DELETE SET NULL, + redeemed_at timestamptz, + order_id uuid REFERENCES package_orders (id) ON DELETE SET NULL, + -- An unused code can be withdrawn. + revoked_at timestamptz, + CHECK (redeemed_at IS NULL OR revoked_at IS NULL) +); +CREATE INDEX promo_codes_created_idx ON promo_codes (created_at DESC); + +ALTER TABLE package_orders DROP CONSTRAINT package_orders_source_check; +ALTER TABLE package_orders ADD CONSTRAINT package_orders_source_check + CHECK (source IN ('admin', 'mock', 'stripe', 'promo')); diff --git a/crates/db/migrations/0023_invitation_package.sql b/crates/db/migrations/0023_invitation_package.sql new file mode 100644 index 0000000..7336315 --- /dev/null +++ b/crates/db/migrations/0023_invitation_package.sql @@ -0,0 +1,3 @@ +-- An invitation can come with a package: a promo code made with it, sent in +-- the e-mail and redeemed by itself when the invitee signs up. +ALTER TABLE promo_codes ADD COLUMN invitation_id uuid UNIQUE REFERENCES invitations (id) ON DELETE SET NULL; 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/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/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/crates/db/src/lib.rs b/crates/db/src/lib.rs index 0f73e30..f34e6ac 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -104,6 +104,15 @@ pub fn random_token(bytes: usize) -> String { URL_SAFE_NO_PAD.encode(buf) } +/// Letters and digits that cannot be mixed up when typed (no 0/O, 1/I/L). +pub const CODE_ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ"; + +/// A random code of `len` characters from [`CODE_ALPHABET`] (about 5 bits each). +pub fn random_code(len: usize) -> String { + let mut rng = rand::rng(); + (0..len).map(|_| CODE_ALPHABET[rand::Rng::random_range(&mut rng, 0..CODE_ALPHABET.len())] as char).collect() +} + /// Stored form of a secret token. pub fn token_hash(token: &str) -> Vec { Sha256::digest(token.as_bytes()).to_vec() diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index a5305ea..73b97b8 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -158,6 +158,8 @@ 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)) @@ -173,6 +175,26 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result()) + .filter(|c| !c.is_empty()), + ); + let gift_line = |hu: bool| { + gift.as_ref().map(|(package, code)| { + if hu { + format!( + " Ajándékba egy „{package}” csomagot is kapsz: a regisztrációval magától jóváíródik. Ha mégis kellene, a promókódod: {code}." + ) + } else { + format!( + " You also get the “{package}” package as a gift: it is added when you sign up. Should you need it, your promo code is {code}." + ) + } + }) + }; Ok(match lang { Lang::Hu => Content { subject: match &inviter { @@ -188,7 +210,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result { "Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into() } - }, + } + &gift_line(true).unwrap_or_default(), quote: message, points: Some(( "Mit találsz ott?", @@ -226,7 +248,7 @@ fn invitation(lang: Lang, payload: &Value, url: String) -> Result format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."), None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(), - }, + } + &gift_line(false).unwrap_or_default(), quote: message, points: Some(( "What you will find there:", @@ -262,6 +284,129 @@ 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"); + 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 = @@ -445,6 +590,31 @@ 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(); + 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(); @@ -468,6 +638,14 @@ mod tests { assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> ")); assert!(!en.html.contains("border-left")); + let mut gift = invitation_payload(); + gift["package_name"] = json!("Páros"); + gift["promo_code"] = json!("ABCD-EFGH-JKLM"); + let hu = render("invitation", "hu", &gift).unwrap(); + assert!(hu.text.contains("Ajándékba egy „Páros” csomagot is kapsz"), "{}", hu.text); + assert!(hu.html.contains("ABCD-EFGH-JKLM")); + assert!(!render("invitation", "hu", &invitation_payload()).unwrap().text.contains("Ajándék")); + let mut broken = invitation_payload(); broken["unsubscribe_url"] = Value::Null; assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url"))); diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f4a3aa3..b09292f 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -85,8 +85,13 @@ services: ANALYSIS_MODEL: ${ANALYSIS_MODEL:-} SUMMARY_MODEL: ${SUMMARY_MODEL:-} PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false} - # Stand-in payment (adds an analysis unit at once) until Stripe is connected. - MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} + # 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} + # 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/docs/promokodok.md b/docs/promokodok.md new file mode 100644 index 0000000..de80cc5 --- /dev/null +++ b/docs/promokodok.md @@ -0,0 +1,58 @@ +# Promókódok + +Amíg a fizetés nincs bekötve, a csomagokat promókóddal (és admin ajándékkal) lehet megkapni. Élesben a vásárlás ki van kapcsolva: a `MOCK_PAYMENTS` alapértéke a `deploy/docker-compose.yml`-ben `false`. A csomagkártyákon ilyenkor „Hamarosan” felirat áll. + +## Admin: Admin → Promókódok + +- **Kódkészítés:** + - Csomag (a fő csomagok és a kiegészítők közül), darab (1–500) és egy megjegyzés: kinek szól, melyik kampány. + - Az elkészült kódok egy listában jelennek meg, a „Mind másolása” gombbal kimásolhatók. + - A kód formája `ABCD-EFGH-JKLM`: 12 karakter, összetéveszthető betűk és számok nélkül (nincs 0/O, 1/I/L). +- **Lista:** + - Szűrhető állapotra: **fel nem használt** (ez az alapértelmezés), beváltott, visszavont, mind. + - Szűrhető csomagra, és kereshető kódrészletre, megjegyzésre vagy a beváltó e-mail-címére. + - A beváltott kódnál látszik, ki és mikor váltotta be. +- **Visszavonás:** fel nem használt kódot vissza lehet vonni. Utána nem váltható be. + +## Felhasználó: beváltás + +- **Hol lehet beváltani:** + - a fejléc „Kód beváltása” linkje (`/bevaltas`); + - a Csomagok oldal „Van promókódod?” doboza; + - a részletes elemzés ajánlata és a kérdés-válasz rész is ide vezet, ha nincs felhasználható egység. +- **Kitöltött link:** a `sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKLM` link kitöltve nyitja meg a kódot. Aki nincs belépve, a belépés után ide tér vissza. Elég ezt a linket elküldeni a meghívottaknak. +- **Beírás:** a kód kis- vagy nagybetűvel, kötőjellel vagy anélkül is beírható. +- **Beváltás = feltöltés:** a kód nem hozzáad, hanem **feltölti** az egyenleget a csomag szintjéig. Minden egységnél (képletelemzés, kapcsolati elemzés, előrejelzés, kérdés, szabad személyhely) az új egyenleg a csomag mennyisége lesz, ha addig kevesebb volt. + - Ami elhasznált belőle, visszajön; ami ennél több van (például vett hozzá), megmarad. + - Példa: a „Páros” csomag 2 képletelemzést ad. Ha valakinek 0 maradt, 2 lesz; ha 5 van, 5 marad. + - Ha a felhasználónak már mindenből megvan a csomag mennyisége, a kódot nem váltjuk be (megmarad későbbre), és ezt üzenetben meg is mondjuk. + - Könyvelés: egy `package_orders` sor `promo` forrással, 0 Ft-tal, és `credit_ledger` sorok csak a ténylegesen hozzáadott mennyiségekkel. A válaszban az `added` mező mondja meg, mi került hozzá. +- **Egyszer:** egy kód egyszer váltható be. A „már felhasználták”, „már nem érvényes” és „nincs ilyen kód” esetekre külön üzenet van. +- **Találgatás ellen:** 10 sikertelen próbálkozás után a felhasználó negyed óráig nem próbálkozhat. + +## Meghívó csomaggal + +Az Admin → Meghívók oldalon az „Ajándék csomag” választóval minden meghívott kap egy promókódot a választott csomagra (megjegyzés: „meghívó: ”). + +- **A levélben** benne van a csomag neve és a kód. A levél előnézete is mutatja (minta kóddal). +- **Regisztrációkor** a kód magától beváltódik, ugyanazzal a feltöltéssel, mint a kézi beváltásnál. Ha mégsem, a kód kézzel is beváltható. +- **Ú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 + +| Végpont | Ki | Mit csinál | +|---|---|---| +| `POST /v1/admin/promo-codes` `{package, count, note?}` | admin | kódok készítése | +| `GET /v1/admin/promo-codes?status=unused\|used\|revoked\|all&package=&q=&limit=&offset=` | admin | lista | +| `POST /v1/admin/promo-codes/{id}/revoke` | admin | visszavonás | +| `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | beváltás (feltöltés); a válaszban az új egyenleg, a csomag és az `added` | +| `POST /v1/admin/invitations` `{emails, message?, locale?, package?}` | admin | meghívó, opcionálisan csomaggal | diff --git a/docs/szemely-meghivas.md b/docs/szemely-meghivas.md new file mode 100644 index 0000000..e114392 --- /dev/null +++ b/docs/szemely-meghivas.md @@ -0,0 +1,32 @@ +# 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. + +**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. +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/config.rs b/services/backend/src/config.rs index 308e89b..d9fbc77 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -45,6 +45,14 @@ 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, + /// `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, @@ -119,6 +127,8 @@ 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)?, + 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()), @@ -156,6 +166,8 @@ impl Config { session_ttl_days: 30, 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/packages.rs b/services/backend/src/packages.rs index fc757c2..939a277 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -184,6 +184,8 @@ impl Package { pub enum Source { Admin, Mock, + /// A redeemed promo code. + Promo, } impl Source { @@ -191,11 +193,25 @@ impl Source { match self { Source::Admin => "admin", Source::Mock => "mock", + Source::Promo => "promo", } } } -/// Records an order and gives its contents, inside the caller's transaction. +impl Package { + /// What the package gives, unit by unit. + pub fn contents(&self) -> [(Unit, i64); 5] { + [ + (Unit::Natal, self.natal), + (Unit::Synastry, self.synastry), + (Unit::Forecast, self.forecast), + (Unit::Person, self.persons), + (Unit::Question, self.questions), + ] + } +} + +/// Records an order and adds its contents, inside the caller's transaction. pub async fn grant( tx: &mut PgConnection, user_id: Uuid, @@ -203,10 +219,55 @@ pub async fn grant( source: Source, created_by: Option, note: Option<&str>, +) -> Result { + record(tx, user_id, package, source, created_by, note, &package.contents()).await +} + +/// Fills the user's units up to what the package gives (promo codes): a unit +/// below the package's amount is raised to it, used units come back, more +/// than that stays as it is. `persons_left` is the free person slots now +/// (`None`: unlimited, nothing to add). Returns the order and what was added +/// (nothing at all: no order is recorded). +pub async fn top_up( + tx: &mut PgConnection, + user_id: Uuid, + package: &Package, + persons_left: Option, + note: Option<&str>, +) -> Result)>, ApiError> { + sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(user_id).execute(&mut *tx).await?; + let balance = crate::credits::balance(tx, user_id).await?; + let added: Vec<(Unit, i64)> = package + .contents() + .into_iter() + .map(|(unit, n)| { + let have = match unit { + Unit::Person => persons_left.unwrap_or(i64::MAX), + unit => balance.of(unit), + }; + (unit, (n - have).max(0)) + }) + .filter(|&(_, n)| n > 0) + .collect(); + if added.is_empty() { + return Ok(None); + } + let order = record(tx, user_id, package, Source::Promo, None, note, &added).await?; + Ok(Some((order, added))) +} + +async fn record( + tx: &mut PgConnection, + user_id: Uuid, + package: &Package, + source: Source, + created_by: Option, + note: Option<&str>, + contents: &[(Unit, i64)], ) -> Result { let order = Uuid::now_v7(); let price = match source { - Source::Admin => 0, + Source::Admin | Source::Promo => 0, Source::Mock => package.price_huf, }; sqlx::query( @@ -222,14 +283,7 @@ pub async fn grant( .bind(created_by) .execute(&mut *tx) .await?; - let contents = [ - (Unit::Natal, package.natal), - (Unit::Synastry, package.synastry), - (Unit::Forecast, package.forecast), - (Unit::Person, package.persons), - (Unit::Question, package.questions), - ]; - for (unit, n) in contents { + for &(unit, n) in contents { if n == 0 { continue; } diff --git a/services/backend/src/persons.rs b/services/backend/src/persons.rs index 266abca..6de5ae7 100644 --- a/services/backend/src/persons.rs +++ b/services/backend/src/persons.rs @@ -62,6 +62,20 @@ pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Resul Ok(Slots { used, granted: free + bought, unlimited: entitled || auth.user.has_role(Role::Admin) }) } +/// The free person slots of a user without unlimited slots (for topping up). +pub async fn left(conn: &mut PgConnection, user_id: Uuid, free: i64) -> Result { + let (used, bought): (i64, i64) = sqlx::query_as( + "SELECT \ + (SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \ + (SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \ + WHERE user_id = $1 AND unit = 'person' AND reason <> 'person')", + ) + .bind(user_id) + .fetch_one(conn) + .await?; + Ok((free + bought - used).max(0)) +} + /// Fails when no slot is left (a quick check before calculating a chart). pub async fn check(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<(), ApiError> { if slots(conn, auth, free).await?.left() == Some(0) { 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 9ac9888..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. @@ -216,7 +218,15 @@ pub async fn register( .bind(&email) .execute(&mut *tx) .await?; - super::invitations::mark_accepted(&mut tx, user_id, &email, req.invite_token.as_deref()).await?; + super::invitations::mark_accepted( + &mut tx, + user_id, + &email, + req.invite_token.as_deref(), + 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?; @@ -284,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 @@ -347,7 +359,16 @@ pub async fn google( .bind(locale) .execute(&mut *tx) .await?; - super::invitations::mark_accepted(&mut tx, id, &email, req.invite_token.as_deref()).await?; + super::invitations::mark_accepted( + &mut tx, + id, + &email, + req.invite_token.as_deref(), + 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/invitations.rs b/services/backend/src/routes/invitations.rs index 9440dd9..c36b859 100644 --- a/services/backend/src/routes/invitations.rs +++ b/services/backend/src/routes/invitations.rs @@ -7,6 +7,10 @@ //! //! People who asked for no more invitations are kept as the hash of their //! address. People without an invitation can join the waitlist. +//! +//! An invitation can come with a package: a promo code is made with it, the +//! e-mail shows it with its redeem link, and it is redeemed by itself when +//! the invitee signs up (revoking the invitation withdraws it). use axum::Json; use axum::extract::{Path, Query, State}; @@ -24,8 +28,12 @@ use crate::AppState; use crate::auth::AdminUser; use crate::config::SignupMode; use crate::error::{ApiError, ApiResult}; +use crate::packages; use crate::views::{rfc3339, rfc3339_opt}; +/// The package of an invitation, as shown in its e-mail: (code as shown, package name). +type Gift = (String, &'static str); + pub const INVITATION_TTL: time::Duration = time::Duration::days(30); /// A resend is possible this often, and at most this many sendings in all. const RESEND_GAP: time::Duration = time::Duration::hours(24); @@ -68,12 +76,15 @@ pub async fn admit( } } -/// After a new account is created: its invitations count as accepted, and it leaves the waitlist. +/// After a new account is created: its invitations count as accepted, it +/// leaves the waitlist, and the packages of those invitations are redeemed +/// (`free_slots`: the person slots everyone gets). pub async fn mark_accepted( conn: &mut PgConnection, user_id: Uuid, email: &str, token: Option<&str>, + free_slots: i64, ) -> Result<(), ApiError> { let hash = token.map(|t| db::token_hash(t.trim())); sqlx::query( @@ -87,12 +98,36 @@ pub async fn mark_accepted( .execute(&mut *conn) .await?; sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email).execute(&mut *conn).await?; + let codes: Vec<(Uuid, String, String)> = sqlx::query_as( + "SELECT p.id, p.code, p.package FROM promo_codes p JOIN invitations i ON i.id = p.invitation_id \ + WHERE i.accepted_by = $1 AND p.redeemed_at IS NULL AND p.revoked_at IS NULL FOR UPDATE OF p", + ) + .bind(user_id) + .fetch_all(&mut *conn) + .await?; + for (id, code, package) in codes { + let Some(package) = packages::find(&package) else { continue }; + let persons_left = crate::persons::left(conn, user_id, free_slots).await?; + super::promo::redeem_code(conn, id, &code, package, user_id, Some(persons_left)).await?; + tracing::info!(user = %user_id, package = package.id, "invitation package redeemed"); + } Ok(()) } +/// The open promo code of an invitation, for its e-mail. +async fn gift_of(conn: &mut PgConnection, invitation_id: Uuid) -> Result, sqlx::Error> { + let row: Option<(String, String)> = sqlx::query_as( + "SELECT code, package FROM promo_codes WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", + ) + .bind(invitation_id) + .fetch_optional(conn) + .await?; + Ok(row.and_then(|(code, package)| packages::find(&package).map(|p| (super::promo::display(&code), p.name)))) +} + // --- sending --------------------------------------------------------------------------------- -fn clean_message(message: Option) -> 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); }; @@ -107,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}"), @@ -122,9 +157,14 @@ fn payload( inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, + gift: Option<&Gift>, ) -> Value { let (url, unsubscribe_url, unsubscribe_post_url) = links(state, token); + let base = &state.config.public_base_url; json!({ + "package_name": gift.map(|g| g.1), + "promo_code": gift.map(|g| g.0.as_str()), + "redeem_url": gift.map(|g| format!("{base}/bevaltas?kod={}", g.0)), "url": url, "unsubscribe_url": unsubscribe_url, "unsubscribe_post_url": unsubscribe_post_url, @@ -145,6 +185,7 @@ async fn send( inviter: Option<&str>, message: Option<&str>, expires: OffsetDateTime, + gift: Option<&Gift>, ) -> Result { let token = db::new_token(); sqlx::query("INSERT INTO invitation_tokens (token_hash, invitation_id) VALUES ($1, $2)") @@ -152,13 +193,13 @@ async fn send( .bind(id) .execute(&mut *conn) .await?; - let payload = payload(state, &token, inviter, message, expires); + let payload = payload(state, &token, inviter, message, expires, gift); let url = payload["url"].as_str().unwrap_or_default().to_owned(); queue_email_to(conn, None, email, "invitation", locale, payload).await?; 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) @@ -173,6 +214,8 @@ pub struct CreateInvitations { emails: Vec, message: Option, locale: Option, + /// A package from the catalog the invitees get (as a promo code). + package: Option, } /// Invites a list of addresses. Each gets a result: `invited` (with the @@ -188,6 +231,10 @@ pub async fn create( } let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; + let package = match req.package.as_deref().filter(|p| !p.is_empty()) { + Some(id) => Some(packages::find(id).ok_or(ApiError::NotFound("package"))?), + None => None, + }; let inviter = admin.user.display_name.clone(); let mut results = Vec::new(); let mut seen = std::collections::HashSet::new(); @@ -240,8 +287,20 @@ pub async fn create( results.push(json!({ "email": email, "status": "already_invited" })); continue; } - let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; - results.push(json!({ "email": email, "status": "invited", "id": id, "url": url })); + let gift = match package { + Some(p) => { + let note = format!("meghívó: {email}"); + let code = super::promo::new_code(&mut tx, p.id, Some(¬e), Some(admin.id()), Some(id)).await?; + Some((super::promo::display(&code), p.name)) + } + None => None, + }; + let url = + send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) + .await?; + results.push(json!({ + "email": email, "status": "invited", "id": id, "url": url, "promo_code": gift.as_ref().map(|g| &g.0), + })); } tx.commit().await?; Ok((StatusCode::CREATED, Json(json!({ "results": results })))) @@ -265,6 +324,9 @@ struct Row { mail_sent_at: Option, mail_failed_at: Option, mail_error: Option, + promo_code: Option, + promo_package: Option, + promo_redeemed_at: Option, } fn status(accepted: Option, revoked: Option, expires: OffsetDateTime) -> &'static str { @@ -285,8 +347,10 @@ pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> "SELECT i.id, i.email, i.message, i.locale, i.created_at, i.expires_at, i.sent_count, i.last_sent_at, \ i.accepted_at, i.revoked_at, inv.display_name AS invited_by_name, \ coalesce(acc.display_name, acc.email) AS accepted_by_name, \ - m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error \ + m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error, \ + pc.code AS promo_code, pc.package AS promo_package, pc.redeemed_at AS promo_redeemed_at \ FROM invitations i \ + LEFT JOIN promo_codes pc ON pc.invitation_id = i.id \ LEFT JOIN users inv ON inv.id = i.invited_by \ LEFT JOIN users acc ON acc.id = i.accepted_by \ LEFT JOIN LATERAL (SELECT created_at, sent_at, failed_at, last_error FROM email_outbox \ @@ -318,6 +382,12 @@ pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> "accepted_at": rfc3339_opt(r.accepted_at), "accepted_by": r.accepted_by_name, "invited_by": r.invited_by_name, "mail": mail, "mail_error": r.mail_error, "can_resend": can_resend, + "package": r.promo_package.as_deref().map(|p| json!({ + "id": p, + "name": packages::find(p).map(|p| p.name), + "code": r.promo_code.as_deref().map(super::promo::display), + "redeemed_at": rfc3339_opt(r.promo_redeemed_at), + })), }) }) .collect(); @@ -391,22 +461,34 @@ pub async fn resend( .execute(&mut *tx) .await?; let inviter = admin.user.display_name.clone(); - let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; + let gift = gift_of(&mut tx, id).await?; + let url = + send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires, gift.as_ref()) + .await?; tx.commit().await?; Ok(Json(json!({ "id": id, "url": url, "expires_at": rfc3339(expires) }))) } pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult { + let mut tx = state.db.begin().await?; let done = sqlx::query( "UPDATE invitations SET revoked_at = now() WHERE id = $1 AND accepted_at IS NULL AND revoked_at IS NULL", ) .bind(id) - .execute(&state.db) + .execute(&mut *tx) .await? .rows_affected(); if done == 0 { return Err(ApiError::NotFound("open invitation")); } + // Its package goes with it. + sqlx::query( + "UPDATE promo_codes SET revoked_at = now() WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", + ) + .bind(id) + .execute(&mut *tx) + .await?; + tx.commit().await?; Ok(StatusCode::NO_CONTENT) } @@ -427,6 +509,8 @@ pub struct PreviewRequest { /// Also send it to the admin's own address. #[serde(default)] send_to_me: bool, + /// Show it with this package (a sample code). + package: Option, } /// The invitation e-mail with sample links (they lead nowhere), and @@ -438,12 +522,17 @@ pub async fn preview( ) -> ApiResult> { let message = clean_message(req.message)?; let locale = validate_locale(&state, req.locale.as_deref())?; + let gift = match req.package.as_deref().filter(|p| !p.is_empty()) { + Some(id) => Some(("MINT-AKOD-XXXX".to_string(), packages::find(id).ok_or(ApiError::NotFound("package"))?.name)), + None => None, + }; let payload = payload( &state, "minta", admin.user.display_name.as_deref(), message.as_deref(), OffsetDateTime::now_utc() + INVITATION_TTL, + gift.as_ref(), ); let mail = email_templates::render("invitation", &locale, &payload) .map_err(|e| ApiError::Internal(format!("invitation template: {e}")))?; @@ -498,8 +587,13 @@ pub async fn unsubscribe( WithRejection(Query(q), _): WithRejection, ApiError>, ) -> ApiResult> { let mut tx = state.db.begin().await?; + // 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", + "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())) .fetch_optional(&mut *tx) @@ -515,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 }))) } @@ -529,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 baea8bd..915a04f 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -16,6 +16,7 @@ mod invitations; mod jobs; mod models; mod payments; +mod promo; mod prompts; mod questions; mod recalculate; @@ -96,6 +97,9 @@ pub fn router(state: Arc) -> Router { .route("/v1/analyses/{id}/questions", get(questions::list).post(questions::ask)) .route("/v1/questions/{id}", get(questions::get_one)) // sharing + .route("/v1/promo-codes/redeem", post(promo::redeem)) + .route("/v1/admin/promo-codes", get(promo::list).post(promo::create)) + .route("/v1/admin/promo-codes/{id}/revoke", post(promo::revoke)) .route("/v1/shares", get(shares::list).post(shares::create)) .route("/v1/shares/{id}", delete(shares::revoke)) // public, no login @@ -158,6 +162,8 @@ 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, + "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/promo.rs b/services/backend/src/routes/promo.rs new file mode 100644 index 0000000..060ecb4 --- /dev/null +++ b/services/backend/src/routes/promo.rs @@ -0,0 +1,277 @@ +//! Promo codes. An admin makes a batch for one package (or one comes with an +//! invitation); a logged-in user redeems a code once. Redeeming fills the +//! user's units up to the package's amounts (used ones come back, more than +//! that stays), recorded as an order with source `promo`. Unused codes can be +//! withdrawn. Failed redemptions are rate limited per user, so codes cannot +//! be guessed. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::payments::holdings; +use super::{Body, IdPath, St}; +use crate::auth::{AdminUser, AuthUser}; +use crate::credits::Unit; +use crate::error::{ApiError, ApiResult}; +use crate::packages; +use crate::views::{rfc3339, rfc3339_opt}; + +/// Characters of a code (12 × ~5 bits: not guessable within the rate limit). +const CODE_LEN: usize = 12; +const MAX_BATCH: i64 = 500; + +/// `ABCD-EFGH-JKLM`: the stored code in groups of four. +pub(super) fn display(code: &str) -> String { + code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::>().join("-") +} + +/// What the user typed, as stored: upper case, without spaces and dashes. +fn normalize(input: &str) -> String { + input.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect() +} + +/// Makes one code for a package inside the caller's transaction; returns the stored code. +pub(super) async fn new_code( + tx: &mut sqlx::PgConnection, + package: &str, + note: Option<&str>, + created_by: Option, + invitation_id: Option, +) -> Result { + loop { + let code = db::random_code(CODE_LEN); + // A clash is practically impossible; another code is drawn if it happens. + let inserted = sqlx::query( + "INSERT INTO promo_codes (id, code, package, note, created_by, invitation_id) \ + VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (code) DO NOTHING", + ) + .bind(Uuid::now_v7()) + .bind(&code) + .bind(package) + .bind(note) + .bind(created_by) + .bind(invitation_id) + .execute(&mut *tx) + .await? + .rows_affected(); + if inserted == 1 { + return Ok(code); + } + } +} + +/// Redeems an open code for the user inside the caller's transaction (the +/// code row must be locked). Returns what was added; `None`: the user already +/// has everything the package gives, the code stays open. +pub(super) async fn redeem_code( + tx: &mut sqlx::PgConnection, + code_id: Uuid, + code: &str, + package: &packages::Package, + user_id: Uuid, + persons_left: Option, +) -> Result>, ApiError> { + let note = format!("promo code {}", display(code)); + let Some((order, added)) = packages::top_up(tx, user_id, package, persons_left, Some(¬e)).await? else { + return Ok(None); + }; + sqlx::query("UPDATE promo_codes SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1") + .bind(code_id) + .bind(user_id) + .bind(order) + .execute(&mut *tx) + .await?; + Ok(Some(added)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NewCodes { + package: String, + count: i64, + note: Option, +} + +/// Admin: makes `count` new codes for a package. +pub async fn create( + State(state): St, + admin: AdminUser, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?; + if !(1..=MAX_BATCH).contains(&req.count) { + return Err(ApiError::BadRequest(format!("count must be 1 to {MAX_BATCH}"))); + } + let note = req.note.map(|n| n.trim().chars().take(200).collect::()).filter(|n| !n.is_empty()); + let mut tx = state.db.begin().await?; + let mut codes = Vec::new(); + for _ in 0..req.count { + codes.push(display(&new_code(&mut tx, package.id, note.as_deref(), Some(admin.0.id()), None).await?)); + } + tx.commit().await?; + tracing::info!(admin = %admin.0.id(), package = package.id, count = codes.len(), "promo codes created"); + Ok((StatusCode::CREATED, Json(json!({ "package": package.id, "note": note, "codes": codes })))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CodeQuery { + /// `unused` (default), `used`, `revoked` or `all`. + status: Option, + package: Option, + /// Part of the code, the note or the redeemer's e-mail. + q: Option, + limit: Option, + offset: Option, +} + +type Row = ( + Uuid, + String, + String, + Option, + OffsetDateTime, + Option, + Option, + Option, + Option, +); + +/// Admin: the codes, newest first, filtered. +pub async fn list( + State(state): St, + _admin: AdminUser, + WithRejection(Query(query), _): WithRejection, ApiError>, +) -> ApiResult> { + let status = query.status.as_deref().unwrap_or("unused"); + let condition = match status { + "unused" => "p.redeemed_at IS NULL AND p.revoked_at IS NULL", + "used" => "p.redeemed_at IS NOT NULL", + "revoked" => "p.revoked_at IS NOT NULL", + "all" => "true", + other => return Err(ApiError::BadRequest(format!("unknown status '{other}'"))), + }; + let limit = query.limit.unwrap_or(100).clamp(1, 500); + let offset = query.offset.unwrap_or(0).max(0); + let package = query.package.filter(|p| !p.is_empty()); + let search = query.q.map(|q| q.trim().to_string()).filter(|q| !q.is_empty()); + // A code is searched for without its dashes. + let code_search = search.as_deref().map(normalize).filter(|c| !c.is_empty()); + let filter = format!( + "FROM promo_codes p LEFT JOIN users u ON u.id = p.redeemed_by \ + WHERE {condition} AND ($1::text IS NULL OR p.package = $1) \ + AND ($2::text IS NULL OR p.note ILIKE '%' || $2 || '%' OR u.email ILIKE '%' || $2 || '%' \ + OR ($3::text IS NOT NULL AND p.code LIKE '%' || $3 || '%'))" + ); + let rows: Vec = sqlx::query_as(&format!( + "SELECT p.id, p.code, p.package, p.note, p.created_at, p.redeemed_at, p.revoked_at, u.email, u.display_name \ + {filter} ORDER BY p.created_at DESC, p.id DESC LIMIT $4 OFFSET $5" + )) + .bind(&package) + .bind(&search) + .bind(&code_search) + .bind(limit) + .bind(offset) + .fetch_all(&state.db) + .await?; + let total: i64 = sqlx::query_scalar(&format!("SELECT count(*) {filter}")) + .bind(&package) + .bind(&search) + .bind(&code_search) + .fetch_one(&state.db) + .await?; + let codes: Vec = rows + .into_iter() + .map(|(id, code, package, note, created, redeemed, revoked, email, name)| { + json!({ + "id": id, + "code": display(&code), + "package": package, + "package_name": packages::find(&package).map(|p| p.name), + "note": note, + "created_at": rfc3339(created), + "redeemed_at": rfc3339_opt(redeemed), + "revoked_at": rfc3339_opt(revoked), + "redeemed_by": email.map(|e| json!({ "email": e, "name": name })), + }) + }) + .collect(); + Ok(Json(json!({ "codes": codes, "total": total, "status": status, "limit": limit, "offset": offset }))) +} + +/// Admin: withdraws an unused code. +pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult { + let result = sqlx::query( + "UPDATE promo_codes SET revoked_at = now() WHERE id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL", + ) + .bind(id) + .execute(&state.db) + .await?; + if result.rows_affected() == 0 { + return Err(ApiError::conflict("promo_not_open", "Csak fel nem használt kódot lehet visszavonni.")); + } + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Redeem { + code: String, +} + +/// Redeems a code: the user gets its package. One use per code. +pub async fn redeem( + State(state): St, + auth: AuthUser, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let key = format!("promo:{}", auth.id()); + state.login_limiter.check(&key)?; + let code = normalize(&req.code); + let mut tx = state.db.begin().await?; + let found: Option<(Uuid, String, Option, Option)> = + sqlx::query_as("SELECT id, package, redeemed_at, revoked_at FROM promo_codes WHERE code = $1 FOR UPDATE") + .bind(&code) + .fetch_optional(&mut *tx) + .await?; + let (id, package_id) = match found { + Some((id, package, None, None)) => (id, package), + Some((_, _, Some(_), _)) => { + state.login_limiter.failed(&key); + return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták.")); + } + Some((_, _, _, Some(_))) => { + state.login_limiter.failed(&key); + return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes.")); + } + None => { + state.login_limiter.failed(&key); + return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be.")); + } + }; + let package = packages::find(&package_id).ok_or(ApiError::NotFound("package"))?; + sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?; + let persons_left = crate::persons::slots(&mut tx, &auth, state.config.free_person_slots).await?.left(); + let Some(added) = redeem_code(&mut tx, id, &code, package, auth.id(), persons_left).await? else { + return Err(ApiError::conflict( + "promo_nothing_to_add", + format!( + "Most is megvan minden, amit ez a kód adna ({}), ezért nem váltottuk be. Tedd el későbbre.", + package.name + ), + )); + }; + tx.commit().await?; + state.login_limiter.succeeded(&key); + tracing::info!(user = %auth.id(), package = package.id, "promo code redeemed"); + let mut body = holdings(&state, &auth).await?; + body["package"] = json!({ "id": package.id, "name": package.name }); + body["added"] = added.iter().map(|(unit, n)| (unit.as_str().to_string(), json!(n))).collect(); + Ok(Json(body)) +} 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/routes/synastries.rs b/services/backend/src/routes/synastries.rs index f488e4b..3370eca 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 { @@ -254,14 +260,61 @@ 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?; - 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 +322,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 +363,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 +377,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 +486,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 f3aab45..a6aa502 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(); @@ -740,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; @@ -751,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"); @@ -765,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; @@ -776,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; @@ -787,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")] @@ -1839,3 +1903,307 @@ async fn admins_read_the_error_log(pool: PgPool) { assert_eq!(r.body["attempts"], 0); assert!(r.body["next_attempt_at"].is_string()); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn promo_codes_are_made_by_admins_and_redeemed_once(pool: PgPool) { + let app = TestApp::new(pool).await; + let admin = app.register("admin@example.com", "Admin").await; // BOOTSTRAP_ADMIN_EMAILS + let anna = app.register("anna@example.com", "Anna").await; + let bela = app.register("bela@example.com", "Béla").await; + + // only admins make codes + let r = app.post("/v1/admin/promo-codes", Some(&anna), json!({"package": "single", "count": 1})).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "nincs", "count": 1})).await; + assert_eq!(r.status, StatusCode::NOT_FOUND); + let r = app + .post("/v1/admin/promo-codes", Some(&admin), json!({"package": "single", "count": 3, "note": "meghívottak"})) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let codes: Vec = r.body["codes"].as_array().unwrap().iter().map(|c| c.as_str().unwrap().into()).collect(); + assert_eq!(codes.len(), 3); + assert!(codes.iter().all(|c| c.len() == 14 && c.matches('-').count() == 2), "{codes:?}"); + + // redeemed in any spelling: the package arrives + let before = app.get("/v1/me", Some(&anna)).await.body["analyses_left"]["natal"].as_i64().unwrap(); + let typed = format!(" {} ", codes[0].replace('-', " ").to_lowercase()); + let r = app.post("/v1/promo-codes/redeem", Some(&anna), json!({"code": typed})).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["package"]["id"], "single"); + let me = app.get("/v1/me", Some(&anna)).await.body; + assert_eq!(me["analyses_left"]["natal"].as_i64(), Some(before + 1)); + assert_eq!(me["package"]["id"], "single"); + + // once only, also for someone else + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[0]})).await; + assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("promo_used"))); + // a withdrawn code and an unknown one do not work + let list = app.get("/v1/admin/promo-codes", Some(&admin)).await.body; + assert_eq!(list["total"], 2, "unused is the default filter: {list}"); + let withdrawn = list["codes"].as_array().unwrap().iter().find(|c| c["code"] == codes[1].as_str()).unwrap().clone(); + let r = app + .post(&format!("/v1/admin/promo-codes/{}/revoke", withdrawn["id"].as_str().unwrap()), Some(&admin), json!({})) + .await; + assert_eq!(r.status, StatusCode::NO_CONTENT); + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[1]})).await; + assert_eq!(r.body["error"]["code"], "promo_revoked"); + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": "AAAA-BBBB-CCCC"})).await; + assert_eq!(r.body["error"]["code"], "promo_unknown"); + + // the filters + let get = |q: &str| { + let uri = format!("/v1/admin/promo-codes?{q}"); + let app = &app; + let admin = &admin; + async move { app.get(&uri, Some(admin)).await } + }; + let used = get("status=used").await.body; + assert_eq!( + (used["total"].as_i64(), &used["codes"][0]["redeemed_by"]["email"]), + (Some(1), &json!("anna@example.com")) + ); + assert_eq!(get("status=revoked").await.body["total"], 1); + assert_eq!(get("status=all").await.body["total"], 3); + assert_eq!(get("status=all&package=addon_questions").await.body["total"], 0); + assert_eq!(get("status=all&q=anna@").await.body["total"], 1); + assert_eq!(get("status=all&q=megh").await.body["total"], 3); + let part = codes[2].split('-').nth(1).unwrap().to_lowercase(); + assert_eq!(get(&format!("status=unused&q={part}")).await.body["total"], 1); + + // guessing is cut off + for _ in 0..10 { + app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": "ZZZZ-ZZZZ-ZZZZ"})).await; + } + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": codes[2]})).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn an_invitation_brings_its_package_and_codes_fill_up(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 r = app + .post( + "/v1/admin/invitations", + Some(&admin), + json!({"emails": ["guest@example.com", "other@example.com"], "package": "couple"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let guest = &r.body["results"][0]; + let guest_token = invite_token(guest["url"].as_str().unwrap()); + let other_id = r.body["results"][1]["id"].as_str().unwrap().to_string(); + + // the e-mail shows the package and its code + let (payload,): (Value,) = sqlx::query_as( + "SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(payload["package_name"], "Páros"); + assert_eq!(payload["promo_code"], guest["promo_code"]); + assert!( + payload["redeem_url"] + .as_str() + .unwrap() + .ends_with(&format!("/bevaltas?kod={}", guest["promo_code"].as_str().unwrap())) + ); + let list = app.get("/v1/admin/invitations", Some(&admin)).await.body; + assert_eq!(list["invitations"][0]["package"]["name"], "Páros"); + + // revoking an invitation withdraws its code + let r = app.call("DELETE", &format!("/v1/admin/invitations/{other_id}"), Some(&admin), None).await; + assert_eq!(r.status, StatusCode::NO_CONTENT); + let codes = app.get("/v1/admin/promo-codes?status=revoked", Some(&admin)).await.body; + assert_eq!((codes["total"].as_i64(), &codes["codes"][0]["note"]), (Some(1), &json!("meghívó: other@example.com"))); + + // signing up redeems it by itself + let r = google_signup(&app, "g-guest", "guest@example.com", Some(&guest_token)).await; + assert!(r.status.is_success(), "{}", r.body); + let token = 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() + }); + let me = app.get("/v1/me", Some(&token)).await.body; + let left = &me["analyses_left"]; + assert_eq!( + (left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()), + (Some(2), Some(1), Some(2)), + "{me}" + ); + assert_eq!(me["package"]["id"], "couple"); + let used = app.get("/v1/admin/promo-codes?status=used", Some(&admin)).await.body; + assert_eq!(used["codes"][0]["redeemed_by"]["email"], "guest@example.com"); + + // a code fills up: nothing to add while everything is there… + let r = app.post("/v1/admin/promo-codes", Some(&admin), json!({"package": "couple", "count": 1})).await; + let spare = r.body["codes"][0].as_str().unwrap().to_string(); + let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await; + assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("promo_nothing_to_add"))); + // …used units come back, extra ones stay + sqlx::query( + "INSERT INTO credit_ledger (id, user_id, unit, delta, reason) \ + SELECT gen_random_uuid(), id, unit, delta, 'admin_adjust' FROM users, \ + (VALUES ('natal', -2), ('forecast', 3)) AS v(unit, delta) WHERE email = 'guest@example.com'", + ) + .execute(&pool) + .await + .unwrap(); + let r = app.post("/v1/promo-codes/redeem", Some(&token), json!({"code": spare})).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["added"], json!({"natal": 2})); + let left = &app.get("/v1/me", Some(&token)).await.body["analyses_left"]; + assert_eq!( + (left["natal"].as_i64(), left["synastry"].as_i64(), left["forecast"].as_i64()), + (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); +} + +#[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/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 ( +
+
+ + + + Belépés + +
+ +
+ +
+
+ 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) => ( +
+

{s.title}

+

+ +

+
+ ))} +
+
+ Részlet egy kitalált képlet teljes elemzéséből + Elolvasom a teljes példaelemzést → +
+
+ +
+
+ {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. +

+
+
+ +
    + {EVENTS.map((e) => ( +
  1. + {e.date} + + {e.text} +
  2. + ))} +
+ 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. +

+
+
+ +
+ + Te + + + Ő + +
+
+
+ {SYNASTRY_TOPICS.map((c) => ( + + {c} + + ))} +
+
+
+
+
+ +
+
+

Így működik

+
    +
  1. + 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. +
  3. + 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ó. +

    +
  4. +
  5. + 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. +

    +
  6. +
+
+
+ +
+
+ +

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. +

+
+
+ +
+
+ + + © {new Date().getFullYear()} Sorsfonalak +
+
+
+ ); +} diff --git a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx index 3bcba3a..0602de8 100644 --- a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx +++ b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; +import { usePackages } from "@/components/PackageCards"; import { api, errorText } from "@/lib/api"; import { formatDate } from "@/lib/astro"; import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types"; @@ -104,6 +105,8 @@ function InviteForm({ onSent }: { onSent: () => Promise }) { const [emails, setEmails] = useState(""); const [message, setMessage] = useState(""); const [locale, setLocale] = useState("hu"); + const [pkg, setPkg] = useState(""); + const packages = usePackages(); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [results, setResults] = useState(null); @@ -116,7 +119,7 @@ function InviteForm({ onSent }: { onSent: () => Promise }) { setResults(null); try { const res = await api<{ results: InvitationResult[] }>("/admin/invitations", { - body: { emails: parseEmails(emails), message: message.trim() || null, locale }, + body: { emails: parseEmails(emails), message: message.trim() || null, locale, package: pkg || null }, }); setResults(res.results); if (res.results.some((r) => r.status === "invited")) setEmails(""); @@ -163,6 +166,17 @@ function InviteForm({ onSent }: { onSent: () => Promise }) {
+
+ + +
setPkg(e.target.value)}> + + {(packages ?? []).map((p) => ( + + ))} + + 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/admin/promokodok/PromoCodes.tsx b/services/frontend/src/app/admin/promokodok/PromoCodes.tsx new file mode 100644 index 0000000..174fa5f --- /dev/null +++ b/services/frontend/src/app/admin/promokodok/PromoCodes.tsx @@ -0,0 +1,285 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +import { api, errorText } from "@/lib/api"; +import { formatDate } from "@/lib/astro"; +import type { Package, PromoCode } from "@/lib/types"; + +const PAGE = 100; + +const STATUSES: Record = { + unused: "fel nem használt", + used: "beváltott", + revoked: "visszavont", + all: "mind", +}; + +interface Page { + codes: PromoCode[]; + total: number; +} + +/** Making promo codes and the filtered list of them. */ +export function PromoCodes({ packages }: { packages: Package[] }) { + return ( + <> + + + + ); +} + +function NewCodes({ packages }: { packages: Package[] }) { + const [pkg, setPkg] = useState(packages.find((p) => p.id === "single")?.id ?? packages[0]?.id ?? ""); + const [count, setCount] = useState(1); + const [note, setNote] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [made, setMade] = useState<{ codes: string[]; package: string } | null>(null); + const [copied, setCopied] = useState(false); + + async function create(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + try { + const r = await api<{ codes: string[]; package: string }>("/admin/promo-codes", { + body: { package: pkg, count, note: note || null }, + }); + setMade(r); + setCopied(false); + window.dispatchEvent(new Event("promo-codes-changed")); + } catch (err) { + setError(errorText(err)); + } finally { + setBusy(false); + } + } + + async function copy() { + if (!made) return; + await navigator.clipboard.writeText(made.codes.join("\n")); + setCopied(true); + } + + return ( +

+

Új kódok

+
+
+ + +
+
+ + setCount(Math.max(1, Math.min(500, Number(e.target.value) || 1)))} + /> +
+
+ + setNote(e.target.value)} + placeholder="pl. meghívottak, első kör" + /> +
+ +
+ {error && ( +

+ {error} +

+ )} + {made && ( +
+

+ {made.codes.length} új kód: {packages.find((p) => p.id === made.package)?.name ?? made.package} +

+