diff --git a/crates/db/migrations/0030_terms_consent.sql b/crates/db/migrations/0030_terms_consent.sql new file mode 100644 index 0000000..765fcb8 --- /dev/null +++ b/crates/db/migrations/0030_terms_consent.sql @@ -0,0 +1,6 @@ +-- The buyer accepted the terms (ÁSZF) and asked for immediate delivery, giving +-- up the 14-day withdrawal right, on Stripe's payment page: when, and which +-- version of the terms. Kept as the proof of the consent. +ALTER TABLE stripe_checkouts + ADD COLUMN terms_accepted_at timestamptz, + ADD COLUMN terms_version text; diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index 73b97b8..d2b11ab 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -160,6 +160,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result invitation(lang, payload, url)?, ("synastry_invite", _) => synastry_invite(lang, payload, url)?, ("waitlist_joined", _) => waitlist_joined(lang, payload, url)?, + ("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?, _ => return Err(TemplateError::UnknownTemplate(template.to_owned())), }; Ok(content.render(lang)) @@ -284,6 +285,69 @@ fn name(payload: &Value, field: &str) -> Option { (!name.is_empty()).then(|| name.to_owned()) } +/// The confirmation of a purchase: what was bought, and that the buyer asked +/// for immediate delivery and so gave up the 14-day withdrawal right (the +/// confirmation 45/2014. Korm. rendelet 29. § asks for). +fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result { + let package = name(payload, "package_name").ok_or(TemplateError::MissingField("package_name"))?; + let amount = field(payload, "amount")?; + let contents = + payload["contents"].as_str().map(|c| c.chars().filter(|c| !c.is_control()).take(300).collect::()); + let paid_on = + payload["paid_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("paid_on"))?; + let terms_url = field(payload, "terms_url")?; + let invoices_url = field(payload, "invoices_url")?; + let greeting = |hu: bool| match (hu, name(payload, "display_name")) { + (true, Some(n)) => format!("Szia {n}!"), + (true, None) => "Szia!".to_owned(), + (false, Some(n)) => format!("Hi {n},"), + (false, None) => "Hi,".to_owned(), + }; + Ok(match lang { + Lang::Hu => Content { + subject: format!("Köszönjük a vásárlást: {package}"), + preheader: Some(format!("A(z) {package} csomag a tiéd.")), + greeting: greeting(true), + intro: format!( + "Megkaptuk a fizetésed ({amount}, {paid_on}), és jóváírtuk a(z) „{package}” csomagot.{}", + contents.map(|c| format!(" Tartalma: {c}.")).unwrap_or_default() + ), + quote: Some( + "A fizetés előtt kérted a szolgáltatás azonnali megkezdését, és tudomásul vetted, hogy ezzel elveszíted a 14 napos elállási jogodat. A csomagot ennek megfelelően azonnal teljesítettük." + .into(), + ), + points: None, + button: "Megnézem a csomagjaimat", + url, + note: format!( + "A számlát külön e-mailben küldjük, és a Számláim oldalon is letöltheted: {invoices_url}. A vásárlás feltételei (ÁSZF): {terms_url}. Ha valami nem működik, írj nekünk az info@sorsfonalak.hu címre." + ), + reason: Some("Ezt a levelet a vásárlásod visszaigazolásaként kaptad.".into()), + unsubscribe: None, + unsubscribe_post_url: None, + }, + Lang::En => Content { + subject: format!("Thank you for your purchase: {package}"), + preheader: Some(format!("The {package} package is yours.")), + greeting: greeting(false), + intro: format!("We received your payment ({amount}, {paid_on}) and added the “{package}” package to your account."), + quote: Some( + "Before paying you asked us to start the service at once and acknowledged that you thereby lose your 14-day right of withdrawal. The package was delivered at once accordingly." + .into(), + ), + points: None, + button: "See my packages", + url, + note: format!( + "The invoice comes in a separate e-mail and can be downloaded on the Invoices page: {invoices_url}. Terms of purchase (ÁSZF): {terms_url}. If something does not work, write to info@sorsfonalak.hu." + ), + reason: Some("You got this e-mail as the confirmation of your purchase.".into()), + unsubscribe: None, + unsubscribe_post_url: None, + }, + }) +} + /// 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")?; @@ -651,6 +715,24 @@ mod tests { assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url"))); } + #[test] + fn purchase_confirmations_confirm_the_waiver() { + let payload = serde_json::json!({ + "url": "https://sorsfonalak.hu/csomagok", "display_name": "Anna", "package_name": "Páros", + "contents": "2 részletes képletelemzés, 1 kapcsolati elemzés", "amount": "6\u{a0}000\u{a0}Ft", + "paid_on": "2026-11-20", "terms_url": "https://sorsfonalak.hu/aszf", "invoices_url": "https://sorsfonalak.hu/szamlak" + }); + let hu = render("purchase_confirmation", "hu", &payload).unwrap(); + assert_eq!(hu.subject, "Köszönjük a vásárlást: Páros"); + assert!(hu.text.contains("2026. november 20.") && hu.text.contains("Tartalma: 2 részletes képletelemzés")); + assert!(hu.text.contains("elveszíted a 14 napos elállási jogodat")); + assert!(hu.text.contains("https://sorsfonalak.hu/aszf") && hu.text.contains("https://sorsfonalak.hu/szamlak")); + let en = render("purchase_confirmation", "en", &payload).unwrap(); + assert!(en.text.contains("right of withdrawal")); + let missing = serde_json::json!({"url": "u", "package_name": "Páros"}); + assert_eq!(render("purchase_confirmation", "hu", &missing), Err(TemplateError::MissingField("amount"))); + } + #[test] fn dates() { assert_eq!(date(Lang::Hu, "2027-01-05").as_deref(), Some("2027. január 5.")); diff --git a/docs/fizetes.md b/docs/fizetes.md index 2528039..6ac38a6 100644 --- a/docs/fizetes.md +++ b/docs/fizetes.md @@ -13,6 +13,14 @@ A csomagokat a Stripe Checkout fizetési oldalán lehet megvenni. A csomagok nev A session id miatt egy fizetés csak egyszer ír jóvá (`package_orders.source = 'stripe'`). +## ÁSZF és elállási jog + +Minden vásárlásnál a Stripe fizetési oldalán kötelező bepipálni: „Elfogadom az ÁSZF-et, kérem a szolgáltatás azonnali megkezdését, és tudomásul veszem, hogy ezzel elveszítem a 14 napos elállási jogomat.” (`consent_collection[terms_of_service]=required` és `custom_text[terms_of_service_acceptance]`). Digitális tartalomnál így szűnik meg az elállási jog (45/2014. Korm. rendelet 29. §). Ehhez **a Stripe felületén meg kell adni az ÁSZF címét** (Settings → Business → Public details → Terms of service: `https://sorsfonalak.hu/aszf`), különben a Stripe nem indítja el a fizetést. + +Az elfogadás idejét és az ÁSZF változatát (`TERMS_VERSION`, a frontend `TERMS_UPDATED`-jével együtt kell léptetni) a `stripe_checkouts` sor őrzi (`terms_accepted_at`, `terms_version`). Fizetés után a backend visszaigazoló e-mailt küld (`purchase_confirmation`): a csomag, az összeg, a dátum és a lemondás az elállási jogról; ez a rendelet szerinti visszaigazolás. + +Az ÁSZF az `/aszf` oldalon van (`services/frontend/src/app/aszf/page.tsx`); a céges adatok a `lib/legal.ts`-ből jönnek. Megnyitás előtt jogásszal át kell nézetni. + ## Mit tárolunk Bankkártyaadatot soha: a vásárló a Stripe oldalán adja meg, hozzánk nem jut el. A `stripe_checkouts` sorban a fizetés igazolásakor eltároljuk: diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index b0b76f4..2596424 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -202,6 +202,22 @@ impl Source { } impl Package { + /// What the package gives, as a phrase: "2 részletes képletelemzés, 1 kapcsolati elemzés, …". + pub fn contents_text(&self) -> String { + [ + (self.natal, "részletes képletelemzés"), + (self.synastry, "kapcsolati elemzés"), + (self.forecast, "éves előrejelzés"), + (self.persons, "személyhely"), + (self.questions, "kérdés"), + ] + .into_iter() + .filter(|&(n, _)| n > 0) + .map(|(n, what)| format!("{n} {what}")) + .collect::>() + .join(", ") + } + /// The invoice item: a name that says what the service is (online, /// software-made content; no profession implied), and what the package /// contains (Áfa tv. 169. § e). diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 64381c4..ccbf998 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -16,7 +16,7 @@ mod invitations; mod invoices_user; mod jobs; mod models; -mod payments; +pub(crate) mod payments; mod promo; mod prompts; mod questions; diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index ce4eb21..8472dd6 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -84,6 +84,9 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> { } } +/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`. +pub const TERMS_VERSION: &str = "2026-11-20"; + /// Only admins can buy through Stripe: until purchases open, and always with a /// test key (nobody gets packages with Stripe's test cards, nobody types a /// real card into a test page). @@ -149,6 +152,18 @@ pub async fn checkout( field("metadata[user_id]", &auth.id().to_string()), field("payment_intent_data[description]", &format!("Sorsfonalak – {}", package.name)), field("payment_intent_data[metadata][package]", package.id), + // Every purchase accepts the terms and asks for immediate delivery, + // giving up the 14-day withdrawal right (45/2014. Korm. rendelet 29. §). + // Stripe needs the terms URL in its dashboard (Public details) for this. + field("consent_collection[terms_of_service]", "required"), + field( + "custom_text[terms_of_service_acceptance][message]", + &format!( + "Elfogadom az [ÁSZF-et]({}/aszf), kérem a szolgáltatás azonnali megkezdését, és tudomásul veszem, \ + hogy ezzel elveszítem a 14 napos elállási jogomat.", + state.config.public_base_url + ), + ), field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")), field("cancel_url", &format!("{back}?fizetes=megszakitva")), ]; @@ -195,17 +210,24 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result None, }; + if !session.terms_accepted() { + tracing::warn!(session = %session.id, "paid without the terms consent"); + } sqlx::query( "UPDATE stripe_checkouts SET completed_at = now(), order_id = $2, payment_intent = $3, amount_huf = $4, \ - customer = $5 WHERE id = $1", + customer = $5, terms_accepted_at = CASE WHEN $6 THEN now() END, terms_version = CASE WHEN $6 THEN $7 END \ + WHERE id = $1", ) .bind(&session.id) .bind(order) .bind(&session.payment_intent) .bind(amount_huf.map(|a| a as i32)) .bind(&session.customer_details) + .bind(session.terms_accepted()) + .bind(TERMS_VERSION) .execute(&mut *tx) .await?; + confirm_by_email(&mut tx, state, session, user_id, package, amount_huf.unwrap_or(i64::from(price_huf))).await?; let buyer = invoices::Buyer::from_stripe(session.customer_details.as_ref().unwrap_or(&Value::Null), None); let (item, comment) = package.invoice_item(); let gross = amount_huf.unwrap_or(i64::from(price_huf)); @@ -215,6 +237,60 @@ async fn complete(state: &AppState, session: &stripe::Session) -> Result, + package: &packages::Package, + amount_huf: i64, +) -> Result<(), ApiError> { + let account: Option<(String, String, Option)> = match user_id { + Some(id) => { + sqlx::query_as("SELECT email, locale, display_name FROM users WHERE id = $1") + .bind(id) + .fetch_optional(&mut *tx) + .await? + } + None => None, + }; + let stripe_email = session.customer_details.as_ref().and_then(|c| c["email"].as_str()).map(str::to_string); + let (to, locale, name) = match account { + Some((email, locale, name)) => (email, locale, name), + None => match stripe_email { + Some(email) => (email, "hu".to_string(), None), + None => return Ok(()), + }, + }; + let base = &state.config.public_base_url; + let payload = json!({ + "url": format!("{base}/csomagok"), + "display_name": name, + "package_name": package.name, + "contents": package.contents_text(), + "amount": format_huf(amount_huf), + "paid_on": OffsetDateTime::now_utc().date().to_string(), + "terms_url": format!("{base}/aszf"), + "invoices_url": format!("{base}/szamlak"), + }); + super::auth::queue_email_to(tx, user_id, &to, "purchase_confirmation", &locale, payload).await +} + +/// "6 000 Ft" +fn format_huf(amount: i64) -> String { + let digits = amount.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push('\u{a0}'); + } + out.push(c); + } + format!("{out}\u{a0}Ft") +} + /// Where a payment stands (the return page asks until it is paid). If the /// webhook has not arrived yet, Stripe is asked directly. pub async fn checkout_status( diff --git a/services/backend/src/stripe.rs b/services/backend/src/stripe.rs index 8d27c9d..aeb9383 100644 --- a/services/backend/src/stripe.rs +++ b/services/backend/src/stripe.rs @@ -36,6 +36,16 @@ pub struct Session { /// Name, e-mail, billing address; for a company its name and tax ids. #[serde(default)] pub customer_details: Option, + /// `{"terms_of_service": "accepted"}` once the buyer ticked the terms box. + #[serde(default)] + pub consent: Option, +} + +impl Session { + /// The buyer accepted the terms (and gave up the withdrawal right). + pub fn terms_accepted(&self) -> bool { + self.consent.as_ref().is_some_and(|c| c["terms_of_service"] == "accepted") + } } impl Session { diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 6fde45a..3bb3e5e 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -2335,6 +2335,12 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { assert_eq!(stripe_form(&id, "customer_email").as_deref(), Some("anna@example.com")); assert_eq!(stripe_form(&id, "tax_id_collection[enabled]").as_deref(), Some("true")); assert_eq!(stripe_form(&id, "billing_address_collection").as_deref(), Some("required")); + // Every purchase accepts the terms and gives up the withdrawal right. + assert_eq!(stripe_form(&id, "consent_collection[terms_of_service]").as_deref(), Some("required")); + let consent = stripe_form(&id, "custom_text[terms_of_service_acceptance][message]").unwrap(); + assert!( + consent.contains("[ÁSZF-et](https://sorsfonalak.test/aszf)") && consent.contains("14 napos elállási jogomat") + ); assert_eq!( stripe_form(&id, "success_url").as_deref(), Some("https://sorsfonalak.test/kepletek/abc?fizetes={CHECKOUT_SESSION_ID}") @@ -2362,6 +2368,7 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { // and Stripe's retries do not grant it again. let event = json!({"id": "evt_1", "type": "checkout.session.completed", "data": {"object": {"id": id, "payment_status": "paid", "status": "complete", + "consent": {"terms_of_service": "accepted"}, "amount_total": 600000, "currency": "huf", "payment_intent": "pi_1", "customer_details": {"name": "Kovács Anna", "email": "anna@example.com", "business_name": "Csillag Kft.", @@ -2384,13 +2391,29 @@ async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) { } assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 6000)]); // What the invoice needs is kept, and the invoice is queued. - let (intent, amount, customer): (String, i32, Value) = - sqlx::query_as("SELECT payment_intent, amount_huf, customer FROM stripe_checkouts WHERE id = $1") - .bind(&id) - .fetch_one(&app.pool) - .await - .unwrap(); - assert_eq!((intent.as_str(), amount), ("pi_1", 6000)); + let (intent, amount, customer, terms): (String, i32, Value, Option) = sqlx::query_as( + "SELECT payment_intent, amount_huf, customer, terms_version FROM stripe_checkouts \ + WHERE id = $1 AND terms_accepted_at IS NOT NULL", + ) + .bind(&id) + .fetch_one(&app.pool) + .await + .unwrap(); + assert_eq!( + (intent.as_str(), amount, terms.as_deref()), + ("pi_1", 6000, Some(crate::routes::payments::TERMS_VERSION)) + ); + // The confirmation e-mail (once, though the webhook came twice). + let mails: Vec<(Value,)> = sqlx::query_as( + "SELECT payload FROM email_outbox WHERE to_email = 'anna@example.com' AND template = 'purchase_confirmation'", + ) + .fetch_all(&app.pool) + .await + .unwrap(); + assert_eq!(mails.len(), 1); + assert_eq!((&mails[0].0["package_name"], &mails[0].0["amount"]), (&json!("Páros"), &json!("6\u{a0}000\u{a0}Ft"))); + assert!(mails[0].0["contents"].as_str().unwrap().starts_with("2 részletes képletelemzés")); + email_templates::render("purchase_confirmation", "hu", &mails[0].0).unwrap(); assert_eq!(customer["tax_ids"][0]["value"], "12345678-1-23"); #[derive(sqlx::FromRow, Debug)] struct Queued { diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index eb7a511..7c142db 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -454,6 +454,7 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {