diff --git a/crates/db/migrations/0035_gifts.sql b/crates/db/migrations/0035_gifts.sql index 695786e..04f677b 100644 --- a/crates/db/migrations/0035_gifts.sql +++ b/crates/db/migrations/0035_gifts.sql @@ -2,8 +2,10 @@ -- as for any package (stripe_checkouts.gift_id); when the payment is -- confirmed the gift gets its code, which is e-mailed to the recipient, or -- the buyer hands it over (the gift card can be downloaded as a PDF). --- A gift code is not a promo code: it cannot be withdrawn (it was paid for), --- and it adds the whole package. +-- A gift code is not a promo code: it adds the whole package, and it is only +-- withdrawn when the buyer gets the money back (the buyer may withdraw from +-- the purchase within 14 days, while it is not redeemed). The refund is +-- made by an admin: Stripe pays back, the invoice gets a storno. CREATE TABLE gifts ( id uuid PRIMARY KEY, buyer_id uuid REFERENCES users (id) ON DELETE SET NULL, @@ -27,13 +29,43 @@ CREATE TABLE gifts ( -- E-mails to the recipient so far (sending again is limited). sendings integer NOT NULL DEFAULT 0, last_sent_at timestamptz, + -- Refunded: the code is withdrawn (set before Stripe is asked). + refunded_at timestamptz, + refunded_by uuid REFERENCES users (id) ON DELETE SET NULL, + -- Stripe's refund (re_…), or why Stripe refused it (an admin tries again). + refund_id text, + refund_error text, CHECK (paid_at IS NULL OR code IS NOT NULL), - CHECK (redeemed_at IS NULL OR paid_at IS NOT NULL) + CHECK (redeemed_at IS NULL OR paid_at IS NOT NULL), + CHECK (redeemed_at IS NULL OR refunded_at IS NULL) ); CREATE INDEX gifts_buyer_idx ON gifts (buyer_id, created_at DESC); ALTER TABLE stripe_checkouts ADD COLUMN gift_id uuid UNIQUE REFERENCES gifts (id) ON DELETE SET NULL; +-- The storno of a refunded payment's invoice: the worker cancels the issued +-- invoice in Billingo (the cancellation document is the storno invoice), +-- and Billingo e-mails it to the buyer. +CREATE TABLE invoice_cancellations ( + id uuid PRIMARY KEY, + invoice_id uuid NOT NULL UNIQUE REFERENCES invoices (id) ON DELETE RESTRICT, + reason text NOT NULL, + -- pending → done; failed after the last retry or a lost answer (an admin looks at it). + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'done', 'failed')), + attempts integer NOT NULL DEFAULT 0, + next_attempt_at timestamptz NOT NULL DEFAULT now(), + last_error text, + -- Set before Billingo is asked: after a lost answer the storno is not + -- asked for again (an admin checks it in Billingo). + requested_at timestamptz, + -- The storno invoice, from Billingo. + billingo_document_id bigint UNIQUE, + invoice_number text, + document jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + done_at timestamptz +); + -- A redeemed gift is recorded as an order with source `gift`. ALTER TABLE package_orders DROP CONSTRAINT package_orders_source_check; ALTER TABLE package_orders ADD CONSTRAINT package_orders_source_check diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index 0c827ca..7510916 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -375,7 +375,7 @@ fn purchase_confirmation(lang: Lang, payload: &Value, url: String) -> Result Result` (PDF és PNG). A `/ajandek` oldal mintaképe (`public/img/ajandek-utalvany.webp`) is ezzel készült, `CODE=MINT-AKOD-2026` mintakóddal, ami valódi kód nem lehet. +## Elállás és visszatérítés + +- **A szabály (ÁSZF 5–6.):** ajándéknál a teljesítés a kód beváltásával kezdődik. A vásárló a vásárlástól számított 14 napon belül, amíg a kódot nem váltották be, indoklás nélkül elállhat (pl. e-mailben az info@sorsfonalak.hu címre). A beváltással az elállási jog megszűnik. +- **Admin → Ajándékok:** a lista mutatja a kódot, a vásárlót és a címzettet, a fizetést, az állapotot (beváltatlan / beváltva / visszatérítve), hogy benne van-e még a 14 napban, a számlát és a sztornót. Kereshető kódra, a vásárló vagy a címzett címére, a címzett nevére. +- **„Visszatérítés” gomb** (csak beváltatlan ajándéknál): + 1. Zárolja az ajándékot, és ellenőrzi, hogy nincs-e beváltva (a beváltás ugyanezt a sort zárolja, így a kettő nem futhat össze). Beváltott ajándékot nem téríthet vissza. + 2. Érvényteleníti a kódot (`refunded_at`): utána nem váltható be, nem küldhető el, és az utalvány sem tölthető le. + 3. Sorba állítja a számla sztornóját (`invoice_cancellations`). + 4. A Stripe-on visszatéríti a teljes árat (`POST /v1/refunds` a `payment_intent`-re, `Idempotency-Key: gift-refund-`, így kétszer nem téríthet vissza). A visszatérítés azonosítója (`re_…`) a `gifts.refund_id`-be kerül. + - Ha a Stripe visszautasítja (pl. vitatott fizetés), a kód érvénytelen marad, a hiba látszik a listában, és a gomb „Újrapróbálás” lesz. + - A 14 nap után is megnyomható (méltányosságból); ilyenkor a megerősítés figyelmeztet. +- **Sztornó (worker):** amint a számla ki van állítva, a worker a Billingóban sztornózza (`POST /documents/{id}/cancel`, a vásárló e-mail-címével, hogy a Billingo elküldje neki). A sztornószámla azonosítója és száma az `invoice_cancellations` sorba kerül. + - Ha a Billingo elutasítja, a worker később újra próbálja; a végén „sztornó hiba”. + - Ha a válasz elveszik vagy szerverhiba jön, nem kéri újra (a kétszeres sztornó rosszabb): „sztornó hiba”, és a Billingóban kell megnézni. + - Fejlesztői környezetben nincs Billingo-kulcs: a sztornó (mint a számla) függőben marad. +- A vásárló „Ajándékaim” oldalán „Visszatérítve” áll. + ## Admin -- Az ajándékkódok nem jelennek meg az Admin → Promókódok listában, és nem vonhatók vissza. -- Ha egy ajándékot mégis érvényteleníteni kell (pl. visszatérítés), az most csak az adatbázisban lehetséges. +- Az ajándékkódok nem jelennek meg az Admin → Promókódok listában; az ajándékok az Admin → Ajándékok oldalon vannak. ## Adatok - **Táblák:** - `gifts`: vásárló, csomag, a címzett neve és címe, a küldő neve, üzenet, fizetés ideje, a kód, a beváltás (ki, mikor, melyik rendelés), kiküldött levelek; - - `stripe_checkouts.gift_id`: a fizetés ajándéka. + - `stripe_checkouts.gift_id`: a fizetés ajándéka; + - `gifts.refunded_at`, `refunded_by`, `refund_id`, `refund_error`: a visszatérítés; + - `invoice_cancellations`: a számla sztornója (állapot, próbálkozások, a Billingo sztornószámlája). - **A kód:** ugyanolyan formájú, mint a promókód (`ABCD-EFGH-JKLM`), és sosem egyezik eggyel sem (mindkét oldal ellenőrzi a másik táblát). - **Fiók törlése:** az ajándék beváltható marad, de a címzett neve és címe, a küldő neve és az üzenet törlődik. - **Takarítás:** a ki nem fizetett ajándékokat egy hét után törli a worker (a Stripe fizetési oldala ennél jóval hamarabb lejár). @@ -90,3 +108,5 @@ Az ajándékkód **nem promókód**: külön tárolódik (a `gifts` táblában), | `POST /v1/gifts/{id}/send` `{recipient_email, recipient_email_confirm}` | a vásárló | küldés e-mailben (újra, vagy másik címre) | | `POST /v1/promo-codes/redeem` `{code}` | belépett felhasználó | promókód vagy ajándékkód beváltása; ajándéknál `gift: {from_name}` is | | `GET /v1/payments/checkout/{id}` | a vásárló | a fizetés állapota; ajándéknál `gift: {id, recipient_name, recipient_email}` is | +| `GET /v1/admin/gifts?q=` | admin | az ajándékok, fizetéssel, számlával, sztornóval | +| `POST /v1/admin/gifts/{id}/refund` | admin | visszatérítés (csak beváltatlan ajándéknál; újrapróbálható, ha a Stripe visszautasította) | diff --git a/services/backend/src/routes/gifts.rs b/services/backend/src/routes/gifts.rs index cc9e168..8d62d9d 100644 --- a/services/backend/src/routes/gifts.rs +++ b/services/backend/src/routes/gifts.rs @@ -8,9 +8,12 @@ //! download the card, and send it by e-mail (again, or to another address) //! while it is not redeemed. //! -//! A gift code is not a promo code: it cannot be withdrawn (it was paid -//! for), and it adds the whole package, while a promo code only fills the -//! units up to the package's. Both are redeemed in the same place. +//! A gift code is not a promo code: it adds the whole package, while a promo +//! code only fills the units up to the package's (both are redeemed in the +//! same place). It is not withdrawn like a promo code either: only when the +//! buyer withdraws from the purchase (within 14 days, while it is not +//! redeemed). Then an admin refunds it: the code is withdrawn, Stripe pays +//! the money back, and the worker cancels the invoice in Billingo (storno). use axum::Json; use axum::extract::{Path, State}; @@ -27,7 +30,7 @@ use super::auth::{normalize_email, queue_email_to}; use super::promo::{CODE_LEN, display}; use super::{Body, IdPath, St, payments}; use crate::AppState; -use crate::auth::AuthUser; +use crate::auth::{AdminUser, AuthUser}; use crate::credits::Unit; use crate::error::{ApiError, ApiResult}; use crate::packages::{self, Package, Source, Tier}; @@ -87,10 +90,12 @@ struct Gift { redeemed_at: Option, sendings: i32, last_sent_at: Option, + refunded_at: Option, + refund_id: Option, } const COLUMNS: &str = "id, buyer_id, package, recipient_name, recipient_email, from_name, message, paid_at, code, \ - redeemed_at, sendings, last_sent_at"; + redeemed_at, sendings, last_sent_at, refunded_at, refund_id"; impl Gift { fn package(&self) -> Result<&'static Package, ApiError> { @@ -115,8 +120,26 @@ impl Gift { })) } + fn status(&self) -> &'static str { + match (self.redeemed_at, self.refunded_at) { + (Some(_), _) => "redeemed", + (_, Some(_)) => "refunded", + _ => "open", + } + } + + /// Withdrawn by a refund: it cannot be redeemed, sent or downloaded. + fn refused_if_refunded(&self) -> Result<(), ApiError> { + match self.refunded_at { + Some(_) => { + Err(ApiError::conflict("gift_refunded", "Ezt az ajándékot visszatérítettük, a kód már nem érvényes.")) + } + None => Ok(()), + } + } + fn view(&self) -> Value { - let status = if self.redeemed_at.is_some() { "redeemed" } else { "open" }; + let status = self.status(); let next_send = self.last_sent_at.map(|t| t + SEND_GAP).filter(|t| *t > OffsetDateTime::now_utc()); json!({ "id": self.id, @@ -129,6 +152,7 @@ impl Gift { "code": self.code.as_deref().map(display), "status": status, "redeemed_at": rfc3339_opt(self.redeemed_at), + "refunded_at": rfc3339_opt(self.refunded_at), "sendings": self.sendings, "can_send": status == "open" && self.sendings < MAX_SENDINGS, "send_again_at": rfc3339_opt(next_send), @@ -310,6 +334,7 @@ pub async fn card( let mut conn = state.db.acquire().await?; let gift = own_gift(&mut conn, id, auth.id(), false).await?; drop(conn); + gift.refused_if_refunded()?; let package = gift.package()?; let code = display(gift.code()?); let url = redeem_url(&state, gift.code()?); @@ -361,6 +386,7 @@ pub async fn send_again( if gift.redeemed_at.is_some() { return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották.")); } + gift.refused_if_refunded()?; if gift.sendings >= MAX_SENDINGS { return Err(ApiError::conflict( "gift_send_limit", @@ -399,6 +425,9 @@ pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) -> if gift.redeemed_at.is_some() { return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták.")); } + if gift.refunded_at.is_some() { + return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes.")); + } let package = gift.package()?; let note = format!("ajándékkód {}", display(code)); let order = packages::grant(tx, user_id, package, Source::Gift, None, Some(¬e)).await?; @@ -411,3 +440,197 @@ pub(super) async fn redeem(tx: &mut PgConnection, code: &str, user_id: Uuid) -> let added = package.contents().into_iter().filter(|&(_, n)| n > 0).collect(); Ok(Some(Redeemed { package, added, from_name: gift.from_name })) } + +// --- admin ------------------------------------------------------------------------------------- + +/// The buyer may withdraw from a gift purchase this long (ÁSZF 6.). +const WITHDRAWAL_DAYS: i64 = 14; + +/// A gift as admins see it, with its payment, invoice and storno. +#[derive(sqlx::FromRow)] +struct AdminGift { + id: Uuid, + package: String, + buyer_email: Option, + recipient_name: Option, + recipient_email: Option, + paid_at: Option, + code: Option, + redeemed_at: Option, + redeemed_by: Option, + refunded_at: Option, + refund_id: Option, + refund_error: Option, + checkout_id: Option, + live: Option, + amount_huf: Option, + invoice_number: Option, + invoice_status: Option, + storno_status: Option, + storno_number: Option, + storno_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdminQuery { + /// Part of the code, the buyer's or the recipient's address, or the recipient's name. + q: Option, +} + +/// Admin: the paid gifts, newest first (at most 200). +pub async fn admin_list( + State(state): St, + _admin: AdminUser, + WithRejection(axum::extract::Query(query), _): WithRejection, ApiError>, +) -> ApiResult> { + 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: String = + search.as_deref().unwrap_or("").chars().filter(char::is_ascii_alphanumeric).collect::().to_uppercase(); + let rows: Vec = sqlx::query_as( + "SELECT g.id, g.package, b.email AS buyer_email, g.recipient_name, g.recipient_email, g.paid_at, g.code, \ + g.redeemed_at, r.email AS redeemed_by, g.refunded_at, g.refund_id, g.refund_error, \ + c.id AS checkout_id, c.live, coalesce(c.amount_huf, c.price_huf) AS amount_huf, \ + i.invoice_number, i.status AS invoice_status, \ + x.status AS storno_status, x.invoice_number AS storno_number, x.last_error AS storno_error \ + FROM gifts g LEFT JOIN users b ON b.id = g.buyer_id LEFT JOIN users r ON r.id = g.redeemed_by \ + LEFT JOIN stripe_checkouts c ON c.gift_id = g.id LEFT JOIN invoices i ON i.checkout_id = c.id \ + LEFT JOIN invoice_cancellations x ON x.invoice_id = i.id \ + WHERE g.paid_at IS NOT NULL \ + AND ($1::text IS NULL OR b.email ILIKE '%' || $1 || '%' OR g.recipient_email ILIKE '%' || $1 || '%' \ + OR g.recipient_name ILIKE '%' || $1 || '%' OR ($2 <> '' AND g.code LIKE '%' || $2 || '%')) \ + ORDER BY g.paid_at DESC LIMIT 200", + ) + .bind(&search) + .bind(&code) + .fetch_all(&state.db) + .await?; + let now = OffsetDateTime::now_utc(); + let gifts: Vec = rows + .into_iter() + .map(|g| { + let status = match (g.redeemed_at, g.refunded_at) { + (Some(_), _) => "redeemed", + (_, Some(_)) => "refunded", + _ => "open", + }; + json!({ + "id": g.id, + "package": { "id": g.package, "name": packages::find(&g.package).map(|p| p.name) }, + "buyer_email": g.buyer_email, + "recipient_name": g.recipient_name, + "recipient_email": g.recipient_email, + "paid_at": rfc3339_opt(g.paid_at), + "code": g.code.as_deref().map(display), + "status": status, + "redeemed_at": rfc3339_opt(g.redeemed_at), + "redeemed_by": g.redeemed_by, + "refunded_at": rfc3339_opt(g.refunded_at), + // Withdrawn, but Stripe has not paid back yet (it refused: try again). + "refund_pending": g.refunded_at.is_some() && g.refund_id.is_none() && g.checkout_id.is_some(), + "refund_id": g.refund_id, + "refund_error": g.refund_error, + "within_withdrawal": g.paid_at.is_some_and(|t| now - t <= time::Duration::days(WITHDRAWAL_DAYS)), + "checkout": g.checkout_id.map(|id| json!({ "id": id, "live": g.live, "amount_huf": g.amount_huf })), + "invoice": g.invoice_status.map(|s| json!({ "number": g.invoice_number, "status": s })), + "storno": g.storno_status.map(|s| json!({ "status": s, "number": g.storno_number, "error": g.storno_error })), + }) + }) + .collect(); + Ok(Json(json!({ "gifts": gifts, "withdrawal_days": WITHDRAWAL_DAYS }))) +} + +/// Admin: refunds a gift the buyer withdrew from. Refused once it is +/// redeemed (checked under the row's lock, as redeeming is). The code is +/// withdrawn first, then Stripe pays the money back (one refund per gift, +/// however often this is pressed), and the invoice's storno is queued for the +/// worker. If Stripe refuses, the gift stays withdrawn and this can be tried +/// again. +pub async fn admin_refund( + State(state): St, + admin: AdminUser, + WithRejection(Path(id), _): IdPath, +) -> ApiResult> { + let mut tx = state.db.begin().await?; + let gift: Gift = + sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1 AND paid_at IS NOT NULL FOR UPDATE")) + .bind(id) + .fetch_optional(&mut *tx) + .await? + .ok_or(ApiError::NotFound("gift"))?; + if gift.redeemed_at.is_some() { + return Err(ApiError::conflict("gift_redeemed", "Ezt az ajándékot már beváltották, nem téríthető vissza.")); + } + let checkout: Option<(String, Option)> = sqlx::query_as( + "SELECT id, payment_intent FROM stripe_checkouts WHERE gift_id = $1 AND completed_at IS NOT NULL", + ) + .bind(id) + .fetch_optional(&mut *tx) + .await?; + // Done: Stripe paid back, or there was nothing to pay back (a stand-in payment). + if gift.refund_id.is_some() || (gift.refunded_at.is_some() && checkout.is_none()) { + return Err(ApiError::conflict("gift_refunded", "Ezt az ajándékot már visszatérítettük.")); + } + sqlx::query("UPDATE gifts SET refunded_at = coalesce(refunded_at, now()), refunded_by = $2 WHERE id = $1") + .bind(id) + .bind(admin.0.id()) + .execute(&mut *tx) + .await?; + if let Some((checkout_id, _)) = &checkout { + let reason = format!("Elállás az ajándékcsomag vásárlásától (beváltás előtt), kód: {}", display(gift.code()?)); + sqlx::query( + "INSERT INTO invoice_cancellations (id, invoice_id, reason) \ + SELECT $1, i.id, $2 FROM invoices i WHERE i.checkout_id = $3 ON CONFLICT (invoice_id) DO NOTHING", + ) + .bind(Uuid::now_v7()) + .bind(&reason) + .bind(checkout_id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + tracing::info!(admin = %admin.0.id(), gift = %id, "gift withdrawn for a refund"); + + // The money back (a stand-in payment has none). + if let Some((checkout_id, payment_intent)) = checkout { + let refunded = match (state.config.stripe.as_ref(), payment_intent.as_deref()) { + (Some(config), Some(intent)) => { + let gift_id = id.to_string(); + state + .stripe + .refund( + config, + intent, + &format!("gift-refund-{id}"), + &[("gift_id", &gift_id), ("checkout", &checkout_id)], + ) + .await + } + _ => Err(ApiError::conflict("refund_failed", "Ehhez a fizetéshez nem érhető el a Stripe.")), + }; + match refunded { + Ok(refund) => { + sqlx::query("UPDATE gifts SET refund_id = $2, refund_error = NULL WHERE id = $1") + .bind(id) + .bind(&refund.id) + .execute(&state.db) + .await?; + tracing::info!(gift = %id, refund = %refund.id, status = ?refund.status, "gift refunded"); + } + Err(e) => { + sqlx::query("UPDATE gifts SET refund_error = $2 WHERE id = $1") + .bind(id) + .bind(e.to_string()) + .execute(&state.db) + .await?; + return Err(e); + } + } + } + let gift: Gift = + sqlx::query_as(&format!("SELECT {COLUMNS} FROM gifts WHERE id = $1")).bind(id).fetch_one(&state.db).await?; + Ok(Json( + json!({ "status": gift.status(), "refund_id": gift.refund_id, "refunded_at": rfc3339_opt(gift.refunded_at) }), + )) +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index b21e54f..a9a8950 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -122,6 +122,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/gifts/checkout", post(gifts::checkout)) .route("/v1/gifts/{id}/card.pdf", get(gifts::card)) .route("/v1/gifts/{id}/send", post(gifts::send_again)) + .route("/v1/admin/gifts", get(gifts::admin_list)) + .route("/v1/admin/gifts/{id}/refund", post(gifts::admin_refund)) .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)) diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index d443a01..ace0031 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -86,7 +86,7 @@ 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-22"; +pub const TERMS_VERSION: &str = "2026-11-23"; /// 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 @@ -181,15 +181,22 @@ pub(super) async fn start_checkout( // 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. + // A gift is performed when its code is redeemed: until then (within + // the 14 days) the buyer may withdraw. + let terms = format!("{}/aszf", state.config.public_base_url); + let message = if gift.is_some() { + format!( + "Elfogadom az [ÁSZF-et]({terms}), és kérem, hogy az ajándékkód beváltásakor a szolgáltatás azonnal \ + megkezdődjön. Tudomásul veszem, hogy a beváltással a 14 napos elállási jog megszűnik." + ) + } else { + format!( + "Elfogadom az [ÁSZF-et]({terms}), 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." + ) + }; form.push(field("consent_collection[terms_of_service]", "required")); - form.push(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 - ), - )); + form.push(field("custom_text[terms_of_service_acceptance][message]", &message)); } let session = state.stripe.create_session(config, &form).await?; let url = session.url.ok_or_else(|| ApiError::Internal(format!("checkout session {} has no url", session.id)))?; diff --git a/services/backend/src/stripe.rs b/services/backend/src/stripe.rs index aeb9383..d66ac41 100644 --- a/services/backend/src/stripe.rs +++ b/services/backend/src/stripe.rs @@ -1,5 +1,6 @@ //! The little of Stripe's API we use: Checkout Sessions (a hosted payment -//! page for one package) and webhook signature checking. The package catalog +//! page for one package), refunds (a gift given back) and webhook signature +//! checking. The package catalog //! stays in `packages.rs`; each session carries its name and price, so no //! products have to be kept in the Stripe dashboard. @@ -54,6 +55,15 @@ impl Session { } } +/// A refund (`re_…`). +#[derive(Debug, Deserialize)] +pub struct Refund { + pub id: String, + /// `pending`, `succeeded`, `failed`, … + #[serde(default)] + pub status: Option, +} + pub struct Client { http: reqwest::Client, } @@ -100,6 +110,40 @@ impl Client { Self::session(res).await } + /// Pays a PaymentIntent back in full. The same `key` (Stripe's + /// Idempotency-Key, kept for a day) never refunds twice. + pub async fn refund( + &self, + config: &StripeConfig, + payment_intent: &str, + key: &str, + metadata: &[(&str, &str)], + ) -> Result { + let mut form = vec![ + ("payment_intent".to_string(), payment_intent.to_string()), + ("reason".to_string(), "requested_by_customer".to_string()), + ]; + form.extend(metadata.iter().map(|(k, v)| (format!("metadata[{k}]"), (*v).to_string()))); + let res = self + .http + .post(format!("{}/v1/refunds", config.api_url)) + .bearer_auth(&config.secret_key) + .header("Idempotency-Key", key) + .form(&form) + .send() + .await + .map_err(|e| unavailable(e.to_string()))?; + let status = res.status(); + if !status.is_success() { + // Stripe says why (e.g. already refunded): the admin sees it. + let body: Value = res.json().await.unwrap_or_default(); + let message = body["error"]["message"].as_str().unwrap_or("ismeretlen hiba").to_string(); + tracing::error!(%status, %message, "stripe refund refused"); + return Err(ApiError::conflict("refund_failed", format!("A Stripe nem téríti vissza: {message}"))); + } + res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}"))) + } + async fn session(res: reqwest::Response) -> Result { let status = res.status(); if !status.is_success() { diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index d87367e..eb99e06 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -160,6 +160,27 @@ async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path) - } } +/// Refunds the fake Stripe made: Idempotency-Key and form; a PaymentIntent in +/// REFUND_FAILS is refused once. +type FakeRefunds = std::sync::Mutex)>>; +static STRIPE_REFUNDS: std::sync::LazyLock = std::sync::LazyLock::new(Default::default); +static REFUND_FAILS: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + +async fn fake_stripe_refund( + headers: HeaderMap, + axum::Form(form): axum::Form>, +) -> (StatusCode, Json) { + let intent = form.iter().find(|(k, _)| k == "payment_intent").map(|(_, v)| v.clone()).unwrap_or_default(); + if REFUND_FAILS.lock().unwrap().remove(&intent) { + return (StatusCode::BAD_REQUEST, Json(json!({"error": {"message": "Charge has a dispute."}}))); + } + let key = headers.get("idempotency-key").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + let mut refunds = STRIPE_REFUNDS.lock().unwrap(); + refunds.push((key, form)); + (StatusCode::OK, Json(json!({"id": format!("re_fake_{}", refunds.len()), "status": "succeeded"}))) +} + async fn fake_billingo_pdf( headers: HeaderMap, axum::extract::Path(id): axum::extract::Path, @@ -213,6 +234,7 @@ async fn fake_services_with(s3: FakeS3) -> String { .route("/openrouter/models", get(fake_openrouter_models)) .route("/v1/checkout/sessions", post(fake_stripe_create)) .route("/v1/checkout/sessions/{id}", get(fake_stripe_get)) + .route("/v1/refunds", post(fake_stripe_refund)) .route("/v1/natal", post(fake_natal)) .route("/v1/countries", get(|| async { Json(json!({"countries": [{"iso2": "HU", "name": "Hungary"}]})) })) .route( @@ -3537,3 +3559,151 @@ async fn a_gift_handed_over_by_the_buyer(pool: PgPool) { let r = app.post("/v1/promo-codes/redeem", Some(&bea), json!({"code": code})).await; assert_eq!((r.status, &r.body["added"]["natal"]), (StatusCode::OK, &json!(6))); } + +/// Buys a gift as `token` through the fake Stripe and its webhook; returns +/// the gift's id, its code and the checkout. +async fn paid_gift(app: &TestApp, token: &str, package: &str, intent: &str) -> (String, String, String) { + let r = app + .post( + "/v1/gifts/checkout", + Some(token), + json!({"package": package, "recipient_name": "Bea", "recipient_email": "bea@example.com", + "recipient_email_confirm": "bea@example.com"}), + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let gift = r.body["id"].as_str().unwrap().to_string(); + let session = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string(); + let event = json!({"id": format!("evt_{session}"), "type": "checkout.session.completed", + "data": {"object": {"id": session, "payment_status": "paid", "status": "complete", + "consent": {"terms_of_service": "accepted"}, + "amount_total": 600000, "currency": "huf", "payment_intent": intent, + "customer_details": {"name": "Kovács Anna", "email": "anna@example.com", + "address": {"line1": "Fő utca 1.", "city": "Szeged", "postal_code": "6720", "country": "HU"}, + "tax_ids": []}}}}); + let signature = crate::stripe::sign( + "whsec_fake", + event.to_string().as_bytes(), + time::OffsetDateTime::now_utc().unix_timestamp(), + ); + let r = app + .call_with("POST", "/v1/payments/stripe/webhook", None, Some(event), &[("stripe-signature", &signature)]) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let code: String = sqlx::query_scalar("SELECT code FROM gifts WHERE id = $1::uuid") + .bind(&gift) + .fetch_one(&app.pool) + .await + .unwrap(); + (gift, code, session) +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn a_gift_is_refunded_only_while_it_is_not_redeemed(pool: PgPool) { + let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_live_fake")).await; + let anna = app.register("anna@example.com", "Anna").await; + let admin = app.register("admin@example.com", "Admin").await; + let bela = app.register("bela@example.com", "Béla").await; + let (gift, code, session) = paid_gift(&app, &anna, "couple", "pi_refund_1").await; + // The buyer's consent says the gift is performed when it is redeemed. + let consent = stripe_form(&session, "custom_text[terms_of_service_acceptance][message]").unwrap(); + assert!( + consent.contains("az ajándékkód beváltásakor") && consent.contains("a beváltással a 14 napos"), + "{consent}" + ); + + let r = app.get("/v1/admin/gifts", Some(&admin)).await; + let row = &r.body["gifts"][0]; + assert_eq!( + (&row["status"], &row["within_withdrawal"], &row["buyer_email"]), + (&json!("open"), &json!(true), &json!("anna@example.com")) + ); + assert_eq!((&row["invoice"]["status"], &row["checkout"]["amount_huf"]), (&json!("pending"), &json!(6000))); + let refund_url = format!("/v1/admin/gifts/{gift}/refund"); + assert_eq!(app.post(&refund_url, Some(&anna), json!({})).await.status, StatusCode::FORBIDDEN); + + // Refunded: Stripe pays back once, the invoice's storno is queued, the code is withdrawn. + let r = app.post(&refund_url, Some(&admin), json!({})).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.body["status"], "refunded"); + let refund_id = r.body["refund_id"].as_str().unwrap().to_string(); + let (key, form) = STRIPE_REFUNDS + .lock() + .unwrap() + .iter() + .find(|(_, f)| f.iter().any(|(k, v)| k == "payment_intent" && v == "pi_refund_1")) + .cloned() + .unwrap(); + assert_eq!(key, format!("gift-refund-{gift}")); + assert!(form.contains(&("metadata[gift_id]".to_string(), gift.clone()))); + let r = app.post(&refund_url, Some(&admin), json!({})).await; + assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_refunded"))); + let (reason, status): (String, String) = sqlx::query_as( + "SELECT x.reason, x.status FROM invoice_cancellations x JOIN invoices i ON i.id = x.invoice_id WHERE i.checkout_id = $1", + ) + .bind(&session) + .fetch_one(&app.pool) + .await + .unwrap(); + assert!(reason.contains("Elállás") && reason.contains(&code[..4]) && status == "pending", "{reason}"); + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await; + assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("promo_revoked"))); + let r = app.get("/v1/gifts", Some(&anna)).await; + assert_eq!((&r.body["gifts"][0]["status"], &r.body["gifts"][0]["can_send"]), (&json!("refunded"), &json!(false))); + assert_eq!(gift_card_pdf(&app, &anna, &gift).await.0, StatusCode::CONFLICT); + let r = app.get("/v1/admin/gifts", Some(&admin)).await; + assert_eq!( + (&r.body["gifts"][0]["refund_id"], &r.body["gifts"][0]["storno"]["status"]), + (&json!(refund_id), &json!("pending")) + ); + + // Redeemed first: no refund, nothing changes. + let (redeemed, code, _) = paid_gift(&app, &anna, "single", "pi_refund_2").await; + assert_eq!(app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await.status, StatusCode::OK); + let r = app.post(&format!("/v1/admin/gifts/{redeemed}/refund"), Some(&admin), json!({})).await; + assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("gift_redeemed"))); + let refunded: Option = + sqlx::query_scalar("SELECT refunded_at FROM gifts WHERE id = $1::uuid") + .bind(&redeemed) + .fetch_one(&app.pool) + .await + .unwrap(); + assert!(refunded.is_none()); + + // Stripe refuses: the code stays withdrawn, the admin sees why and tries again. + REFUND_FAILS.lock().unwrap().insert("pi_refund_3".into()); + let (flaky, code, _) = paid_gift(&app, &anna, "family", "pi_refund_3").await; + let r = app.post(&format!("/v1/admin/gifts/{flaky}/refund"), Some(&admin), json!({})).await; + assert_eq!((r.status, &r.body["error"]["code"]), (StatusCode::CONFLICT, &json!("refund_failed"))); + assert!(r.body["error"]["message"].as_str().unwrap().contains("Charge has a dispute.")); + let r = app.post("/v1/promo-codes/redeem", Some(&bela), json!({"code": code})).await; + assert_eq!(r.body["error"]["code"], "promo_revoked"); + let r = app.get("/v1/admin/gifts", Some(&admin)).await; + let row = r.body["gifts"].as_array().unwrap().iter().find(|g| g["id"] == json!(flaky)).unwrap().clone(); + assert!(row["refund_error"].as_str().unwrap().contains("dispute") && row["refund_pending"] == json!(true)); + let r = app.post(&format!("/v1/admin/gifts/{flaky}/refund"), Some(&admin), json!({})).await; + assert_eq!((r.status, &r.body["status"]), (StatusCode::OK, &json!("refunded")), "{}", r.body); + + // Searching by the code (with or without dashes). + let r = app.get(&format!("/v1/admin/gifts?q={}", display_code(&code).to_lowercase()), Some(&admin)).await; + assert_eq!(r.body["gifts"].as_array().unwrap().len(), 1); +} + +fn display_code(code: &str) -> String { + code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::>().join("-") +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn a_gift_paid_with_the_stand_in_is_refunded_without_stripe(pool: PgPool) { + let app = TestApp::new(pool).await; + let anna = app.register("anna@example.com", "Anna").await; + let admin = app.register("admin@example.com", "Admin").await; + let r = app.post("/v1/gifts/checkout", Some(&anna), json!({"package": "single", "recipient_name": "Bea"})).await; + let id = r.body["id"].as_str().unwrap().to_string(); + let url = format!("/v1/admin/gifts/{id}/refund"); + let r = app.post(&url, Some(&admin), json!({})).await; + assert_eq!((r.status, &r.body["status"]), (StatusCode::OK, &json!("refunded")), "{}", r.body); + let r = app.get("/v1/admin/gifts", Some(&admin)).await; + assert_eq!((&r.body["gifts"][0]["refund_pending"], &r.body["gifts"][0]["checkout"]), (&json!(false), &Value::Null)); + assert_eq!(app.post(&url, Some(&admin), json!({})).await.body["error"]["code"], "gift_refunded"); +} diff --git a/services/frontend/src/app/admin/ajandekok/AdminGifts.tsx b/services/frontend/src/app/admin/ajandekok/AdminGifts.tsx new file mode 100644 index 0000000..ad18e43 --- /dev/null +++ b/services/frontend/src/app/admin/ajandekok/AdminGifts.tsx @@ -0,0 +1,176 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +import { api, errorText } from "@/lib/api"; +import { formatDate } from "@/lib/astro"; +import type { AdminGift } from "@/lib/types"; + +const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`; + +const STORNO: Record = { pending: "sztornó folyamatban", done: "sztornózva", failed: "sztornó hiba" }; + +/** The gifts with their payment, invoice and storno, and the refund button. */ +export function AdminGifts() { + const [gifts, setGifts] = useState(null); + const [q, setQ] = useState(""); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(null); + const [done, setDone] = useState(null); + + const load = useCallback(async (search: string) => { + try { + const r = await api<{ gifts: AdminGift[] }>(`/admin/gifts${search ? `?q=${encodeURIComponent(search)}` : ""}`); + setGifts(r.gifts); + } catch (e) { + setError(errorText(e)); + } + }, []); + + useEffect(() => { + const t = setTimeout(() => load(q.trim()), 250); + return () => clearTimeout(t); + }, [q, load]); + + async function refund(g: AdminGift) { + const late = g.within_withdrawal ? "" : "\n\nFigyelem: a 14 napos elállási idő már letelt."; + const money = g.checkout?.amount_huf ? ` (${huf(g.checkout.amount_huf)})` : ""; + if ( + !window.confirm( + `Visszatéríted a(z) „${g.package.name}” ajándékot${money}? A ${g.code} kód érvénytelen lesz, a Stripe visszautalja az árát, a számla sztornózódik.${late}`, + ) + ) + return; + setBusy(g.id); + setError(null); + setDone(null); + try { + await api(`/admin/gifts/${g.id}/refund`, { method: "POST", body: {} }); + setDone(`Visszatérítve: ${g.code}.`); + } catch (e) { + setError(errorText(e)); + } finally { + setBusy(null); + await load(q.trim()); + } + } + + return ( +
+
+ + setQ(e.target.value)} + placeholder="Kód, a vásárló vagy a címzett e-mail-címe, a címzett neve" + /> +
+ {error && ( +

+ {error} +

+ )} + {done && ( +

+ {done} +

+ )} + {gifts === null ? ( +

Betöltés…

+ ) : gifts.length === 0 ? ( +

Nincs ilyen ajándék.

+ ) : ( +
+ + + + + + + + + + + + + {gifts.map((g) => ( + + + + + + + + + + ))} + +
KódCsomagVásárló → címzettFizetveÁllapotSzámla +
+ {g.code} + + {g.package.name ?? g.package.id} + {g.checkout?.amount_huf ? {huf(g.checkout.amount_huf)} : null} + {g.checkout && g.checkout.live === false && teszt fizetés} + + {g.buyer_email ?? törölt fiók} + + → {g.recipient_name ?? "?"} + {g.recipient_email ? ` (${g.recipient_email})` : " (maga adja át)"} + + {formatDate(g.paid_at, true)} + {g.status === "redeemed" ? ( + <> + beváltva {g.redeemed_at ? formatDate(g.redeemed_at, true) : ""} + {g.redeemed_by && {g.redeemed_by}} + + ) : g.status === "refunded" ? ( + <> + {g.refund_pending ? ( + visszatérítés félbemaradt + ) : ( + "visszatérítve" + )}{" "} + {g.refunded_at ? formatDate(g.refunded_at, true) : ""} + {g.refund_pending && g.refund_error && {g.refund_error}} + + ) : ( + <> + beváltatlan + {g.within_withdrawal ? "14 napon belül" : "14 nap letelt"} + + )} + + {g.invoice ? ( + <> + {g.invoice.number ?? (g.invoice.status === "pending" ? "kiállítás alatt" : g.invoice.status)} + {g.storno && ( + + {STORNO[g.storno.status] ?? g.storno.status} + {g.storno.number ? `: ${g.storno.number}` : ""} + {g.storno.error ? ` – ${g.storno.error}` : ""} + + )} + + ) : ( + – + )} + + {(g.status === "open" || g.refund_pending) && ( + + )} +
+
+ )} +
+ ); +} diff --git a/services/frontend/src/app/admin/ajandekok/page.tsx b/services/frontend/src/app/admin/ajandekok/page.tsx new file mode 100644 index 0000000..ebb6d77 --- /dev/null +++ b/services/frontend/src/app/admin/ajandekok/page.tsx @@ -0,0 +1,29 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; + +import { AdminNav } from "@/components/AdminNav"; +import { requireMe } from "@/lib/server"; + +import { AdminGifts } from "./AdminGifts"; + +export const metadata: Metadata = { title: "Ajándékok" }; + +export default async function AdminGiftsPage() { + const me = await requireMe("/admin/ajandekok"); + if (!me.user.roles.includes("admin")) notFound(); + return ( +
+ +
+

Ajándékok

+

+ Az ajándékba vett csomagok. A vásárló a vásárlástól számított 14 napon belül, amíg a kódot nem váltották be, + elállhat (ÁSZF 6.). Ilyenkor a „Visszatérítés” gomb érvényteleníti a kódot, a Stripe-on visszatéríti az árát, + és a számlát sztornózza a Billingóban (a worker, a számla kiállítása után; a sztornót a Billingo e-mailben + elküldi a vásárlónak). Beváltott ajándékot nem lehet visszatéríteni. +

+
+ +
+ ); +} diff --git a/services/frontend/src/app/ajandek/GiftForm.tsx b/services/frontend/src/app/ajandek/GiftForm.tsx index 21662da..e9c6644 100644 --- a/services/frontend/src/app/ajandek/GiftForm.tsx +++ b/services/frontend/src/app/ajandek/GiftForm.tsx @@ -235,8 +235,8 @@ export function GiftForm({ {termsConsent && ( <> {" "} - Az ajándékkód a fizetés után azonnal elkészül, ezért a fizetésnél kéred a teljesítés megkezdését, és ezzel - lemondasz a 14 napos elállási jogról. ÁSZF + A vásárlástól számított 14 napon belül, amíg a kódot nem váltották be, elállhatsz, és visszatérítjük az + árát. A kód beváltásával az elállási jog megszűnik. ÁSZF )}

diff --git a/services/frontend/src/app/ajandek/page.tsx b/services/frontend/src/app/ajandek/page.tsx index bb40163..221d906 100644 --- a/services/frontend/src/app/ajandek/page.tsx +++ b/services/frontend/src/app/ajandek/page.tsx @@ -66,7 +66,10 @@ export default async function GiftPage({ searchParams }: Props) {
  • E-mailben elküldjük neki, vagy letöltöd a PDF-et, és te adod át.
  • Belép vagy regisztrál, beváltja a kódot, és a csomag az övé.
  • -

    A kód nem jár le, és egyszer váltható be. A számlát te kapod.

    +

    + A kód nem jár le, és egyszer váltható be. A számlát te kapod. Ha meggondolod magad, 14 napon belül, + beváltás előtt visszakérheted az árát: írj az info@sorsfonalak.hu címre. +

    diff --git a/services/frontend/src/app/ajandekaim/GiftList.tsx b/services/frontend/src/app/ajandekaim/GiftList.tsx index 120604a..c48d896 100644 --- a/services/frontend/src/app/ajandekaim/GiftList.tsx +++ b/services/frontend/src/app/ajandekaim/GiftList.tsx @@ -75,6 +75,8 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void {gift.status === "redeemed" ? ( Beváltva{gift.redeemed_at ? `: ${day(gift.redeemed_at)}` : ""} + ) : gift.status === "refunded" ? ( + Visszatérítve{gift.refunded_at ? `: ${day(gift.refunded_at)}` : ""} ) : ( Még nincs beváltva )} @@ -94,23 +96,29 @@ function GiftItem({ gift, onChange }: { gift: Gift; onChange: (g: Gift) => void E-mailben elküldve ide: {gift.recipient_email} {gift.sendings > 1 ? ` (${gift.sendings}×)` : ""} - ) : ( + ) : open ? ( "Te adod át: töltsd le az utalványt." + ) : ( + "Nem e-mailben ment." )} {gift.from_name && · Kitől: {gift.from_name}}

    {gift.message &&
    {gift.message}
    } -
    - - Utalvány letöltése (PDF) - - {open && gift.can_send && !sending && ( - - )} -
    + {gift.status === "refunded" ? ( +

    Elálltál a vásárlástól: a kód már nem érvényes, az árát visszatérítettük.

    + ) : ( +
    + + Utalvány letöltése (PDF) + + {open && gift.can_send && !sending && ( + + )} +
    + )} {open && !gift.can_send && gift.sendings > 0 && (

    E-mailben már többször elküldtük. Ha nem érkezett meg, töltsd le az utalványt, és küldd el te.

    )} diff --git a/services/frontend/src/app/aszf/page.tsx b/services/frontend/src/app/aszf/page.tsx index 064af3c..05d68a2 100644 --- a/services/frontend/src/app/aszf/page.tsx +++ b/services/frontend/src/app/aszf/page.tsx @@ -64,10 +64,13 @@ export default async function TermsPage() { is) és a fizetési adatokat. Az adatokat a fizetés előtt ott javíthatja.
  • - A fizetés előtt elfogadja ezt az ÁSZF-et, kéri a szolgáltatás azonnali megkezdését, és tudomásul veszi, - hogy ezzel elveszíti az elállási jogát (6. pont). + A fizetés előtt elfogadja ezt az ÁSZF-et, kéri a szolgáltatás azonnali megkezdését (ajándékcsomagnál: a + kód beváltásakor), és tudomásul veszi, hogy ezzel elveszíti az elállási jogát (6. pont). +
  • +
  • + A fizetéssel a szerződés létrejön. A csomagot azonnal jóváírjuk (ajándékcsomagnál az ajándékkódot azonnal + kiállítjuk), és e-mailben visszaigazoljuk.
  • -
  • A fizetéssel a szerződés létrejön. A csomagot azonnal jóváírjuk, és e-mailben visszaigazoljuk.
  • A szerződés elektronikus úton jön létre, írásba foglalt szerződésnek nem minősül, külön nem iktatjuk. A @@ -96,6 +99,11 @@ export default async function TermsPage() { fiókban vannak. Nem járnak le, nem ruházhatók át, és pénzre nem válthatók vissza. Egy elemzés elkészítése általában néhány perc.

    +

    + Ajándékcsomagnál a vásárló egy ajándékkódot kap: a kódot és a nyomtatható utalványt e-mailben elküldjük a + megadott címzettnek, vagy a vásárló letölti, és maga adja át. A csomag egységei a kód beváltásakor kerülnek a + beváltó fiókjába. A kód nem jár le, és egyszer váltható be. +

    @@ -108,6 +116,14 @@ export default async function TermsPage() { csomagjait azonnal teljesítjük: a fizetési oldalon ezt kéri a vásárló, és a visszaigazoló e-mailben ezt megerősítjük, ezért a vásárlástól elállni nem lehet.

    +

    + Ajándékcsomagnál a teljesítés a kód beváltásával kezdődik meg. A vásárló a vásárlástól számított 14 napon + belül, amíg a kódot nem váltották be, indoklás nélkül elállhat a vásárlástól. Ezt bármilyen egyértelmű + nyilatkozattal, például az {OPERATOR.email} címre írt e-mailben jelezheti. Ilyenkor a kódot érvénytelenítjük, + a vételárat legkésőbb 14 napon belül ugyanarra a fizetési módra visszatérítjük, és a számlát sztornózzuk. A + kód beváltásával az elállási jog megszűnik: a vásárló a fizetés előtt kéri, hogy a teljesítés a beváltáskor + azonnal megkezdődjön, és tudomásul veszi, hogy ezzel elveszíti az elállási jogát. +

    diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx index a766c08..ab7caee 100644 --- a/services/frontend/src/components/AdminNav.tsx +++ b/services/frontend/src/components/AdminNav.tsx @@ -6,6 +6,7 @@ const PAGES = [ { href: "/admin", label: "Felhasználók" }, { href: "/admin/meghivok", label: "Meghívók" }, { href: "/admin/promokodok", label: "Promókódok" }, + { href: "/admin/ajandekok", label: "Ajándékok" }, { href: "/admin/hires-emberek", label: "Híres emberek", creator: true }, { href: "/admin/promptok", label: "Promptok" }, { href: "/admin/modellek", label: "Modellek" }, diff --git a/services/frontend/src/lib/legal.ts b/services/frontend/src/lib/legal.ts index 5cf774a..213ccba 100644 --- a/services/frontend/src/lib/legal.ts +++ b/services/frontend/src/lib/legal.ts @@ -22,4 +22,4 @@ export const PRIVACY_UPDATED = "2026. november 22."; export const PRIVACY_UPDATED_EN = "22 November 2026"; /** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */ -export const TERMS_UPDATED = "2026. november 22."; +export const TERMS_UPDATED = "2026. november 23."; diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 48273de..dae670b 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -633,6 +633,31 @@ export interface PromoCode { redeemed_by: { email: string; name: string | null } | null; } +/** A gift as admins see it (`GET /v1/admin/gifts`). */ +export interface AdminGift { + id: string; + package: { id: string; name: string | null }; + buyer_email: string | null; + recipient_name: string | null; + recipient_email: string | null; + paid_at: string; + code: string; + status: "open" | "redeemed" | "refunded"; + redeemed_at: string | null; + redeemed_by: string | null; + refunded_at: string | null; + /** Withdrawn, but Stripe has not paid back yet (it refused: see refund_error; try again). */ + refund_pending: boolean; + /** Stripe's refund id. */ + refund_id: string | null; + refund_error: string | null; + /** Within the 14 days the buyer may withdraw. */ + within_withdrawal: boolean; + checkout: { id: string; live: boolean | null; amount_huf: number | null } | null; + invoice: { number: string | null; status: string } | null; + storno: { status: string; number: string | null; error: string | null } | null; +} + /** A package the user bought as a gift (`GET /v1/gifts`). */ export interface Gift { id: string; @@ -646,8 +671,9 @@ export interface Gift { paid_at: string; /** ABCD-EFGH-JKLM */ code: string; - status: "open" | "redeemed"; + status: "open" | "redeemed" | "refunded"; redeemed_at: string | null; + refunded_at: string | null; /** E-mails sent so far. */ sendings: number; /** Whether it can be sent by e-mail (again). */ diff --git a/services/worker/src/invoices.rs b/services/worker/src/invoices.rs index de577f5..26753e8 100644 --- a/services/worker/src/invoices.rs +++ b/services/worker/src/invoices.rs @@ -10,6 +10,13 @@ //! one. An invoice that was issued but could not be e-mailed still counts as //! issued (it can be downloaded). Billingo's whole answer is kept; the PDF is //! not (the backend fetches it when the user downloads it). +//! +//! A refunded payment's invoice gets a storno: the backend queues an +//! `invoice_cancellations` row, and once the invoice is issued this job asks +//! Billingo to cancel it (the cancellation document is the storno invoice, +//! e-mailed to the buyer). The request is marked before it is sent; when the +//! answer is lost, it is not asked for again (cancelling twice is worse): +//! the row fails, and an admin checks it in Billingo. use std::time::Duration; @@ -60,6 +67,32 @@ impl Billingo { serde_json::from_str(&text).map_err(|e| format!("{method} {path}: not JSON: {e}")) } + /// Cancels a document (storno) and returns the cancellation document. The + /// error says whether Billingo surely did nothing (it refused the request): + /// after a lost answer or a server error the document may be cancelled. + async fn cancel(&self, document: i64, body: &Value) -> Result { + let path = format!("/documents/{document}/cancel"); + let res = self + .http + .post(format!("{}{path}", self.base)) + .header("X-API-KEY", &self.key) + .header("Accept", "application/json") + .json(body) + .send() + .await + .map_err(|e| (false, format!("POST {path}: {e}")))?; + let status = res.status(); + let text = res.text().await.unwrap_or_default(); + if !status.is_success() { + let refused = status.is_client_error(); + return Err(( + refused, + format!("POST {path}: HTTP {status}: {}", text.chars().take(500).collect::()), + )); + } + serde_json::from_str(&text).map_err(|e| (false, format!("POST {path}: not JSON: {e}"))) + } + async fn block(&self) -> Result { let mut block = self.block.lock().await; if let Some(id) = *block { @@ -363,11 +396,107 @@ async fn find_document(billingo: &Billingo, partner: i64) -> Result, + /// The invoice to cancel. + document_id: i64, + buyer_email: Option, +} + +/// Cancels the invoices of refunded payments (storno); returns how many were finished. +pub async fn cancel_due(db: &PgPool, billingo: &Billingo, max_attempts: i32) -> Result { + let mut done = 0; + loop { + // Only issued invoices can be cancelled: the others wait. + let due: Option = sqlx::query_as(&format!( + "UPDATE invoice_cancellations x SET attempts = x.attempts + 1, next_attempt_at = now() + interval '{LEASE}' \ + FROM invoices i \ + WHERE i.id = x.invoice_id AND x.id = (SELECT x2.id FROM invoice_cancellations x2 \ + JOIN invoices i2 ON i2.id = x2.invoice_id \ + WHERE x2.status = 'pending' AND x2.next_attempt_at <= now() AND i2.billingo_document_id IS NOT NULL \ + AND i2.status = 'issued' \ + ORDER BY x2.next_attempt_at FOR UPDATE OF x2 SKIP LOCKED LIMIT 1) \ + RETURNING x.id, x.attempts, x.reason, x.requested_at, i.billingo_document_id AS document_id, i.buyer_email" + )) + .fetch_optional(db) + .await?; + let Some(due) = due else { return Ok(done) }; + let fail = |error: String| { + sqlx::query("UPDATE invoice_cancellations SET status = 'failed', last_error = $2 WHERE id = $1") + .bind(due.id) + .bind(error) + .execute(db) + }; + if due.requested_at.is_some() { + tracing::error!(cancellation = %due.id, "storno asked for before without an answer; an admin has to check it"); + fail("Korábban már kértük a sztornót, de nem jött válasz: ellenőrizd a Billingóban.".into()).await?; + done += 1; + continue; + } + sqlx::query("UPDATE invoice_cancellations SET requested_at = now() WHERE id = $1") + .bind(due.id) + .execute(db) + .await?; + let mut body = json!({ "cancellation_reason": due.reason }); + if let Some(email) = &due.buyer_email { + body["cancellation_recipients"] = json!(email); + } + match billingo.cancel(due.document_id, &body).await { + Ok(document) => { + let number = document["invoice_number"].as_str().map(str::to_owned); + sqlx::query( + "UPDATE invoice_cancellations SET status = 'done', done_at = now(), last_error = NULL, \ + billingo_document_id = $2, invoice_number = $3, document = $4 WHERE id = $1", + ) + .bind(due.id) + .bind(document["id"].as_i64()) + .bind(&number) + .bind(&document) + .execute(db) + .await?; + tracing::info!(cancellation = %due.id, number = ?number, "invoice cancelled (storno)"); + done += 1; + } + // Refused: nothing happened, it may be asked again. + Err((true, error)) if due.attempts < max_attempts => { + let wait = backoff(due.attempts); + tracing::warn!(cancellation = %due.id, %error, retry_in = ?wait, "storno not made yet"); + sqlx::query( + "UPDATE invoice_cancellations SET requested_at = NULL, last_error = $2, \ + next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1", + ) + .bind(due.id) + .bind(&error) + .bind(wait.as_secs_f64()) + .execute(db) + .await?; + } + Err((refused, error)) => { + tracing::error!(cancellation = %due.id, %error, refused, "storno failed; an admin has to look at it"); + let error = if refused { + error + } else { + format!("Nem tudni, megtörtént-e (ellenőrizd a Billingóban): {error}") + }; + fail(error).await?; + done += 1; + } + } + } +} + pub async fn run(db: PgPool, billingo: Billingo, max_attempts: i32, interval: Duration, stop: watch::Receiver) { loop { if let Err(e) = run_once(&db, &billingo, max_attempts).await { tracing::error!(error = %e, "invoices"); } + if let Err(e) = cancel_due(&db, &billingo, max_attempts).await { + tracing::error!(error = %e, "invoice cancellations"); + } tokio::select! { () = tokio::time::sleep(interval) => {} () = crate::stopped(stop.clone()) => break, @@ -412,6 +541,8 @@ mod tests { lose_document_answer: std::sync::atomic::AtomicBool, /// The invoices made so far, for the list. made: std::sync::Mutex>, + /// Cancelling answers this status first (then 200). + cancel_status: std::sync::Mutex>, } async fn fake_billingo(fake: Arc) -> String { @@ -461,7 +592,23 @@ mod tests { } (StatusCode::OK, Json(body)) } + async fn cancel( + State(f): State>, + Path(id): Path, + Json(body): Json, + ) -> (StatusCode, Json) { + f.requests.lock().unwrap().push((format!("cancel {id}"), body)); + let status = f.cancel_status.lock().unwrap().pop(); + match status { + Some(status) => (status, Json(json!({"message": "no"}))), + None => ( + StatusCode::OK, + Json(json!({"id": 5000 + id, "invoice_number": "SF-2026-S1", "type": "cancellation"})), + ), + } + } let app = Router::new() + .route("/documents/{id}/cancel", post(cancel)) .route("/document-blocks", get(blocks)) .route("/partners", post(partner)) .route("/documents", post(document).get(documents)) @@ -511,6 +658,69 @@ mod tests { .unwrap() } + async fn cancellation(db: &PgPool, invoice: Uuid) -> Uuid { + let id = Uuid::now_v7(); + sqlx::query("INSERT INTO invoice_cancellations (id, invoice_id, reason) VALUES ($1, $2, 'Elállás')") + .bind(id) + .bind(invoice) + .execute(db) + .await + .unwrap(); + id + } + + async fn cancellation_state(db: &PgPool, id: Uuid) -> (String, Option, Option, Option) { + sqlx::query_as( + "SELECT status, invoice_number, billingo_document_id, last_error FROM invoice_cancellations WHERE id = $1", + ) + .bind(id) + .fetch_one(db) + .await + .unwrap() + } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn refunded_invoices_get_a_storno_once(db: PgPool) { + let fake = Arc::new(Fake::default()); + let billingo = Billingo::new(&fake_billingo(fake.clone()).await, "key", None); + let invoice = paid(&db, None).await; + let storno = cancellation(&db, invoice).await; + // The invoice is not issued yet: the storno waits. + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0); + assert_eq!(cancellation_state(&db, storno).await.0, "pending"); + run_once(&db, &billingo, 3).await.unwrap(); + let document = state(&db, invoice).await.2.unwrap(); + // Refused once (nothing happened): asked again later, then made. + fake.cancel_status.lock().unwrap().push(StatusCode::TOO_MANY_REQUESTS); + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0); + let (status, _, _, error) = cancellation_state(&db, storno).await; + assert!(status == "pending" && error.unwrap().contains("429")); + sqlx::query("UPDATE invoice_cancellations SET next_attempt_at = now()").execute(&db).await.unwrap(); + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 1); + assert_eq!( + cancellation_state(&db, storno).await, + ("done".into(), Some("SF-2026-S1".into()), Some(5000 + document), None) + ); + let requests = fake.requests.lock().unwrap().clone(); + let cancels: Vec<&Value> = requests.iter().filter(|(r, _)| r.starts_with("cancel ")).map(|(_, b)| b).collect(); + assert_eq!(cancels.len(), 2); + assert_eq!( + cancels[1], + &json!({"cancellation_reason": "Elállás", "cancellation_recipients": "anna@example.com"}) + ); + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0); + + // A server error: maybe it was cancelled, so it is not asked again. + let other = paid(&db, None).await; + run_once(&db, &billingo, 3).await.unwrap(); + let storno = cancellation(&db, other).await; + fake.cancel_status.lock().unwrap().push(StatusCode::BAD_GATEWAY); + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 1); + let (status, _, _, error) = cancellation_state(&db, storno).await; + assert!(status == "failed" && error.unwrap().contains("ellenőrizd a Billingóban")); + assert_eq!(cancel_due(&db, &billingo, 3).await.unwrap(), 0); + } + #[sqlx::test(migrator = "db::MIGRATOR")] async fn invoices_are_issued_and_sent_once(db: PgPool) { let fake = Arc::new(Fake::default());