Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4231440b69 | ||
|
|
08ad7b0a79 | ||
|
|
b7665e9acc | ||
|
|
b37094e481 |
@@ -0,0 +1,10 @@
|
||||
-- Where a new member came from, for the admin statistics. Set once, at
|
||||
-- sign-up, from that visit: the kind of source (Facebook, a search engine,
|
||||
-- typed in…), the referring site's address without its path, or the link's
|
||||
-- campaign tags, and the device type. Nothing is stored about visitors who
|
||||
-- do not sign up. NULL for the members who signed up before this.
|
||||
ALTER TABLE users ADD COLUMN signup_source text
|
||||
CHECK (signup_source IN ('facebook', 'instagram', 'messenger', 'tiktok', 'google', 'bing', 'search',
|
||||
'email', 'app', 'other', 'direct'));
|
||||
ALTER TABLE users ADD COLUMN signup_detail text CHECK (char_length(signup_detail) <= 200);
|
||||
ALTER TABLE users ADD COLUMN signup_device text CHECK (signup_device IN ('mobile', 'tablet', 'desktop'));
|
||||
@@ -6,7 +6,8 @@ Ingyenes, személyes heti szöveg a tag saját képletéből és a hét égboltj
|
||||
|
||||
- **Saját oldala van:** `/heti-horoszkop`, a menüben a „Képletem” után. A saját képlet oldalán, az összefoglaló alatt egy kis kártya visz ide.
|
||||
- **Egy hónap egyszerre:** a hetek a hétfőjük hónapjához tartoznak, legelöl a legújabb. A „Korábbi hónap” és „Újabb hónap” gomb lapoz (`?honap=2026-10`); csak olyan hónapra visz, amelyben van szöveg, és előre csak az aktuális hónapig.
|
||||
- **Készül:** az aktuális hónapban az oldal először a heti szöveget kéri (`POST /v1/weekly`). Amíg a worker írja (kb. 20 másodperc), a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta.
|
||||
- **Készül:** az aktuális hónapban az oldal egyszer kéri a heti szöveget (`POST /v1/weekly`), utána csak olvassa (`GET /v1/analyses/{id}`), amíg a worker megírja (kb. 20 másodperc); közben a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta. Ha nem sikerült, az oldal nem próbálja újra magától (minden próba fizetős AI-hívás); újratöltéskor egyszer újra megírja.
|
||||
- **Kijelentkezve:** nyitóoldal belépés és regisztráció gombbal, és egy valódi példa heti horoszkóppal a példaelemzés kitalált képletéhez (`src/content/pelda-heti.json`, a helyi rendszerrel és ugyanazzal a modellel generálva). Előnézeti kép: `/kep/heti-horoszkop.png`.
|
||||
- **Csak a megnézett hetek:** régebbi hétnek csak akkor van szövege, ha a tag azon a héten megnyitotta az oldalt. Visszamenőleg nem készül.
|
||||
- API: `GET /v1/weekly/history?month=2026-11` → `{month, current_month, this_week, weeks: [{week_start, week_end, analysis}], older, newer, email}`. Minden saját képlet hetei számítanak, mert a születési adat közben változhatott.
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Admin statisztika
|
||||
|
||||
Az `/admin/statisztika` oldal (az admin menüben az első) azt mutatja, hogyan megy az oldal: hányan regisztrálnak, hányan készítenek képletet, vásárolnak, olvassák a heti horoszkópot, és honnan jönnek a tagok. Csak az admin látja.
|
||||
|
||||
## Mit mutat
|
||||
|
||||
- **Időszak:** 7, 30 vagy 90 nap, vagy minden az első tag óta. A napok magyar idő szerint számítanak.
|
||||
- **Eddig összesen:** tagok, saját képletek, fizető vásárlók, bevétel, a hétfői levél feliratkozói és a fórumtagok.
|
||||
- **Számkártyák:**
|
||||
- új tagok, saját képletek (az első saját képlet napja), vásárlás (bevétel, fizetések, vásárlók), elemzések és kérdések, heti horoszkóp olvasói, fórum-hozzászólások, AI-költség;
|
||||
- mellettük az előző, ugyanilyen hosszú időszakhoz képesti változás.
|
||||
- **Napról napra:** egy-egy kis oszlopdiagram mérőszámonként, ugyanazokra a napokra. Egy napra mutatva (telefonon koppintva) fölötte látszanak a nap számai; alatta a napi táblázat.
|
||||
- **Regisztrációtól a fizetésig:** az időszakban regisztráltak közül hányan erősítették meg a címüket, készítették el a képletüket, kezdték el a fizetést, és fizettek. Mellette: hányan kértek elemzést vagy kérdést, és hányan olvasták a heti horoszkópot.
|
||||
- **Honnan jöttek:** az időszakban regisztráltak forrás szerint (tag, saját képlet, fizetett), eszköz és regisztrációs mód szerint, és a hivatkozó oldalak és kampányok listája.
|
||||
- **Vásárlások csomagonként**, **Heti horoszkóp hetente** (olvasók és kiküldött levelek), **Amit az AI írt** (fajtánként elkészült, sikertelen, költség).
|
||||
|
||||
**Kik számítanak:**
|
||||
- A tagok számában az adminok nem szerepelnek.
|
||||
- A bevétel az éles Stripe-fizetések összege (a tesztfizetések nélkül).
|
||||
- Az AI-költség mindenkié, az adminoké is.
|
||||
|
||||
API: `GET /v1/admin/stats?days=30` (0: minden). Néhány lekérdezés, csak amikor az admin megnyitja az oldalt.
|
||||
|
||||
## Honnan jött a tag
|
||||
|
||||
Regisztrációkor (jelszavas, Google, Apple) a `users` tábla három mezőt kap. A korábbi tagoknál ezek üresek, az oldalon „Nem ismert”.
|
||||
|
||||
| Mező | Tartalma |
|
||||
|---|---|
|
||||
| `signup_source` | `facebook`, `instagram`, `messenger`, `tiktok`, `google`, `bing`, `search` (más kereső), `email`, `app` (más alkalmazás), `other` (más oldal), `direct` |
|
||||
| `signup_detail` | a hivatkozó oldal címe az elérési útja nélkül (`m.facebook.com`), vagy a link kampánycímkéi (`utm_source=fb&utm_campaign=heti`) |
|
||||
| `signup_device` | `mobile`, `tablet` vagy `desktop` |
|
||||
|
||||
**Honnan tudjuk:**
|
||||
- **A böngészőben:** az oldal az első betöltéskor megjegyzi a hivatkozó oldal címét, az `utm_*` címkéket, az `fbclid`/`gclid`/`ttclid` meglétét és a `forras` paramétert, csak a memóriában (`src/lib/arrival.ts`), és a regisztráció elküldi (`came_from`). A böngészőben semmi nem tárolódik.
|
||||
- **A backendben:** a besorolás a `services/backend/src/signup_source.rs`-ben van. Elsőbbségi sorrend:
|
||||
1. kampánycímke;
|
||||
2. egy alkalmazás beépített böngészője (a böngésző neve alapján);
|
||||
3. a `forras` paraméter;
|
||||
4. a kattintásazonosító;
|
||||
5. a hivatkozó oldal;
|
||||
6. különben `direct`.
|
||||
- **Facebook beépített böngészője:** a belépőoldal Chrome-ba vivő linkje `?forras=facebook`-ot kap, így az ott regisztrálók is Facebookosnak számítanak.
|
||||
- **Megosztott link, meghívó:** a statisztikában ez a forrás, ha volt (`referrals`, `invitations`, illetve egy összevetés-meghívó, amely a fiók előtt készült).
|
||||
|
||||
**Kampánycímke:** a saját Facebook-bejegyzések linkjére írható, például `https://sorsfonalak.hu/heti-horoszkop?utm_source=facebook&utm_campaign=heti`. A „Hivatkozó oldalak és kampányok” listában külön sorban látszik.
|
||||
|
||||
**Adatvédelem:**
|
||||
- Akik nem regisztrálnak, azokról semmit nem tárolunk; őket a Cloudflare Web Analytics mutatja.
|
||||
- A tájékoztatóban (adatkezelési táblázat és a 8. pont) szerepel, jogos érdek alapján.
|
||||
- Az adatexportban `signup_came_from` néven van benne, és a fiókkal együtt törlődik.
|
||||
@@ -19,6 +19,7 @@ mod packages;
|
||||
mod persons;
|
||||
mod photo;
|
||||
mod routes;
|
||||
mod signup_source;
|
||||
mod storage;
|
||||
mod stripe;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -175,6 +175,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
||||
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
||||
"user": UserView::from(&auth.user),
|
||||
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
||||
"signup_came_from": rows("SELECT json_build_object('source', signup_source, 'site_or_campaign', signup_detail, 'device', signup_device) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||
"weekly_horoscope_email": rows("SELECT json_build_object('on', weekly_email, 'last_sent_for_week', weekly_email_sent_on) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
||||
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
||||
|
||||
@@ -25,6 +25,7 @@ use crate::auth::{
|
||||
validate_password, verify_password,
|
||||
};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::signup_source::{self, CameFrom};
|
||||
use crate::views::UserView;
|
||||
|
||||
const VERIFY_EMAIL_TTL: time::Duration = time::Duration::days(3);
|
||||
@@ -230,6 +231,9 @@ pub struct RegisterRequest {
|
||||
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||
#[serde(default)]
|
||||
turnstile_token: Option<String>,
|
||||
/// Where the visit began, for the statistics.
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Before a sign-up or reset e-mail goes out: at most a few per visitor
|
||||
@@ -242,6 +246,12 @@ async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: O
|
||||
crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await
|
||||
}
|
||||
|
||||
/// Where a new member came from (see [`signup_source`]).
|
||||
fn arrival(state: &AppState, headers: &HeaderMap, came: Option<&CameFrom>) -> signup_source::Arrival {
|
||||
let ua = user_agent(headers);
|
||||
signup_source::classify(ua.as_deref(), came, &signup_source::host_of(&state.config.public_base_url))
|
||||
}
|
||||
|
||||
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
|
||||
pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
|
||||
if state.config.password_login {
|
||||
@@ -279,13 +289,20 @@ pub async fn register(
|
||||
None => {
|
||||
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
|
||||
let user_id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
|
||||
.bind(user_id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(req.display_name))
|
||||
.bind(&locale)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let arrival = arrival(&state, &headers, req.came_from.as_ref());
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, email, display_name, locale, signup_source, signup_detail, signup_device) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(req.display_name))
|
||||
.bind(&locale)
|
||||
.bind(arrival.source)
|
||||
.bind(&arrival.detail)
|
||||
.bind(arrival.device)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Packages of invitations go to this account; only whoever opens
|
||||
// the link in the mailbox can ever log in to it.
|
||||
super::invitations::mark_accepted(
|
||||
@@ -369,6 +386,9 @@ pub struct GoogleRequest {
|
||||
invite_token: Option<String>,
|
||||
/// The slug of the shared link the visitor came from.
|
||||
referral: Option<String>,
|
||||
/// Where the visit began, for the statistics of a new account.
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with Google. An unknown Google account is linked to the existing
|
||||
@@ -385,6 +405,7 @@ pub async fn google(
|
||||
locale: claims.locale.clone(),
|
||||
invite_token: req.invite_token,
|
||||
referral: req.referral,
|
||||
came_from: req.came_from,
|
||||
};
|
||||
social_login(&state, headers, jar, "google", claims, signup).await
|
||||
}
|
||||
@@ -401,6 +422,8 @@ pub struct AppleRequest {
|
||||
name: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with Apple, like [`google`]. The address may be an Apple relay
|
||||
@@ -412,7 +435,13 @@ pub async fn apple(
|
||||
WithRejection(Json(req), _): Body<AppleRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let claims = state.apple.verify(&req.id_token).await?;
|
||||
let signup = Signup { name: req.name, locale: None, invite_token: req.invite_token, referral: req.referral };
|
||||
let signup = Signup {
|
||||
name: req.name,
|
||||
locale: None,
|
||||
invite_token: req.invite_token,
|
||||
referral: req.referral,
|
||||
came_from: req.came_from,
|
||||
};
|
||||
social_login(&state, headers, jar, "apple", claims, signup).await
|
||||
}
|
||||
|
||||
@@ -422,6 +451,7 @@ struct Signup {
|
||||
locale: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with a verified provider identity: the linked user, else the user
|
||||
@@ -500,13 +530,19 @@ async fn social_login(
|
||||
.filter(|l| state.config.supported_locales.iter().any(|s| s == l))
|
||||
.unwrap_or(&state.config.supported_locales[0])
|
||||
.to_string();
|
||||
let arrival = arrival(state, &headers, signup.came_from.as_ref());
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, email, email_verified_at, display_name, locale) VALUES ($1, $2, now(), $3, $4)",
|
||||
"INSERT INTO users (id, email, email_verified_at, display_name, locale, \
|
||||
signup_source, signup_detail, signup_device) \
|
||||
VALUES ($1, $2, now(), $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(signup.name))
|
||||
.bind(locale)
|
||||
.bind(arrival.source)
|
||||
.bind(&arrival.detail)
|
||||
.bind(arrival.device)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
super::invitations::mark_accepted(
|
||||
|
||||
@@ -28,6 +28,7 @@ mod questions;
|
||||
mod recalculate;
|
||||
mod shares;
|
||||
pub mod sky;
|
||||
mod stats;
|
||||
mod synastries;
|
||||
mod tarot;
|
||||
mod weekly;
|
||||
@@ -163,6 +164,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/public/celebrities/{slug}", get(celebrities::public_view))
|
||||
.route("/v1/public/photos/{*key}", get(celebrities::photo))
|
||||
// administration
|
||||
.route("/v1/admin/stats", get(stats::admin_stats))
|
||||
.route("/v1/admin/users", get(admin::list_users))
|
||||
.route("/v1/admin/users/{id}", patch(admin::update_user))
|
||||
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
|
||||
|
||||
@@ -105,11 +105,8 @@ pub async fn put_settings(
|
||||
}
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query("UPDATE users SET weekly_email = $2, updated_at = now() WHERE id = $1")
|
||||
.bind(user)
|
||||
.bind(req.weekly_horoscope)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// As the switch on the site: turned on again, the first one comes next Monday.
|
||||
sqlx::query(&super::weekly::switch_sql()).bind(user).bind(req.weekly_horoscope).execute(&mut *tx).await?;
|
||||
if let Some(f) = &req.forum {
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET email_replies = $2, email_followed = $3, email_messages = $4, \
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Admin → Statisztika: `GET /v1/admin/stats?days=30`. Sign-ups, own charts,
|
||||
//! analyses, purchases and the weekly horoscope's readers, day by day in
|
||||
//! Hungarian time, the way from sign-up to purchase, and where the members
|
||||
//! came from. Members are counted without the admins; money is every live
|
||||
//! Stripe payment. A few queries over the database, only when an admin opens
|
||||
//! the page.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::{Date, OffsetDateTime};
|
||||
|
||||
use super::St;
|
||||
use crate::auth::AdminUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct StatsQuery {
|
||||
/// The last this many days with today; 0: since the first member.
|
||||
days: Option<i64>,
|
||||
}
|
||||
|
||||
/// Not an admin (`u`: the users row).
|
||||
const MEMBER: &str = "NOT ('admin' = ANY(u.roles))";
|
||||
/// The analyses a member orders (summaries and weekly texts come by themselves).
|
||||
const ORDERED: &str = "('natal', 'synastry', 'forecast', 'tarot')";
|
||||
|
||||
/// The headline numbers between `$1` and `$2`.
|
||||
fn kpi_sql() -> String {
|
||||
format!(
|
||||
"SELECT json_build_object(\
|
||||
'signups', (SELECT count(*) FROM users u WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2), \
|
||||
'own_charts', (SELECT count(*) FROM (SELECT min(c.created_at) AS first FROM charts c \
|
||||
JOIN users u ON u.id = c.owner_id WHERE c.kind = 'own' AND {MEMBER} GROUP BY c.owner_id) f \
|
||||
WHERE first >= $1 AND first < $2), \
|
||||
'analyses', (SELECT count(*) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind IN {ORDERED} AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2), \
|
||||
'questions', (SELECT count(*) FROM questions q JOIN users u ON u.id = q.asked_by \
|
||||
WHERE {MEMBER} AND q.created_at >= $1 AND q.created_at < $2), \
|
||||
'orders', (SELECT count(*) FROM stripe_checkouts WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'buyers', (SELECT count(DISTINCT user_id) FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'revenue_huf', (SELECT COALESCE(sum(price_huf), 0) FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'refunded_huf', (SELECT COALESCE(sum(c.price_huf), 0) FROM gifts g JOIN stripe_checkouts c ON c.gift_id = g.id \
|
||||
WHERE c.live AND g.refunded_at >= $1 AND g.refunded_at < $2), \
|
||||
'weekly_readers', (SELECT count(DISTINCT a.requested_by) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2), \
|
||||
'forum_posts', (SELECT count(*) FROM forum.posts p JOIN users u ON u.id = p.author_id \
|
||||
WHERE {MEMBER} AND p.deleted_at IS NULL AND p.created_at >= $1 AND p.created_at < $2), \
|
||||
'ai_cost_usd', (SELECT COALESCE(sum(cost_usd), 0) FROM ( \
|
||||
SELECT cost_usd FROM analyses WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT cost_usd FROM questions WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT cost_usd FROM prompt_previews WHERE created_at >= $1 AND created_at < $2) x))"
|
||||
)
|
||||
}
|
||||
|
||||
/// One row a day from `$3` to `$4` (dates in Hungarian time).
|
||||
fn daily_sql() -> String {
|
||||
let day = |col: &str| format!("({col} AT TIME ZONE 'Europe/Budapest')::date");
|
||||
format!(
|
||||
"WITH days AS (SELECT d::date AS day FROM generate_series($3::date, $4::date, interval '1 day') d), \
|
||||
signups AS (SELECT {u} AS day, count(*) AS n FROM users u \
|
||||
WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2 GROUP BY 1), \
|
||||
own AS (SELECT {first} AS day, count(*) AS n FROM (SELECT min(c.created_at) AS first FROM charts c \
|
||||
JOIN users u ON u.id = c.owner_id WHERE c.kind = 'own' AND {MEMBER} GROUP BY c.owner_id) f \
|
||||
WHERE first >= $1 AND first < $2 GROUP BY 1), \
|
||||
ordered AS (SELECT {a} AS day, count(*) AS n FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind IN {ORDERED} AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2 GROUP BY 1), \
|
||||
asked AS (SELECT {q} AS day, count(*) AS n FROM questions q JOIN users u ON u.id = q.asked_by \
|
||||
WHERE {MEMBER} AND q.created_at >= $1 AND q.created_at < $2 GROUP BY 1), \
|
||||
paid AS (SELECT {c} AS day, count(*) AS n, sum(price_huf) AS huf FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2 GROUP BY 1), \
|
||||
weekly AS (SELECT {a} AS day, count(DISTINCT a.requested_by) AS n FROM analyses a \
|
||||
JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2 GROUP BY 1), \
|
||||
posts AS (SELECT {p} AS day, count(*) AS n FROM forum.posts p JOIN users u ON u.id = p.author_id \
|
||||
WHERE {MEMBER} AND p.deleted_at IS NULL AND p.created_at >= $1 AND p.created_at < $2 GROUP BY 1) \
|
||||
SELECT COALESCE(json_agg(json_build_object(\
|
||||
'date', d.day, 'signups', COALESCE(s.n, 0), 'own_charts', COALESCE(o.n, 0), \
|
||||
'analyses', COALESCE(an.n, 0), 'questions', COALESCE(q.n, 0), 'orders', COALESCE(pd.n, 0), \
|
||||
'revenue_huf', COALESCE(pd.huf, 0), 'weekly_readers', COALESCE(w.n, 0), 'forum_posts', COALESCE(fp.n, 0)\
|
||||
) ORDER BY d.day), '[]') \
|
||||
FROM days d LEFT JOIN signups s USING (day) LEFT JOIN own o USING (day) LEFT JOIN ordered an USING (day) \
|
||||
LEFT JOIN asked q USING (day) LEFT JOIN paid pd USING (day) LEFT JOIN weekly w USING (day) \
|
||||
LEFT JOIN posts fp USING (day)",
|
||||
u = day("u.created_at"),
|
||||
first = day("first"),
|
||||
a = day("a.created_at"),
|
||||
q = day("q.created_at"),
|
||||
c = day("completed_at"),
|
||||
p = day("p.created_at"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The members who signed up between `$1` and `$2`: how far each got, and
|
||||
/// where they came from. A shared link or an invitation is the source when
|
||||
/// there was one (it was posted somewhere too, but that is what brought them).
|
||||
fn cohort_sql() -> String {
|
||||
format!(
|
||||
"WITH cohort AS (SELECT \
|
||||
u.email_verified_at IS NOT NULL AS verified, \
|
||||
EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.kind = 'own') AS own_chart, \
|
||||
EXISTS (SELECT 1 FROM analyses a WHERE a.requested_by = u.id AND a.kind IN {ORDERED}) \
|
||||
OR EXISTS (SELECT 1 FROM questions q WHERE q.asked_by = u.id) AS ordered, \
|
||||
EXISTS (SELECT 1 FROM stripe_checkouts s WHERE s.user_id = u.id AND s.live) AS checkout, \
|
||||
EXISTS (SELECT 1 FROM stripe_checkouts s WHERE s.user_id = u.id AND s.live \
|
||||
AND s.completed_at IS NOT NULL) AS bought, \
|
||||
EXISTS (SELECT 1 FROM analyses a WHERE a.requested_by = u.id AND a.kind = 'weekly') AS weekly, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM referrals r WHERE r.user_id = u.id) THEN 'shared' \
|
||||
WHEN EXISTS (SELECT 1 FROM invitations i WHERE i.accepted_by = u.id) \
|
||||
OR EXISTS (SELECT 1 FROM synastry_invites s WHERE s.accepted_by = u.id \
|
||||
AND s.created_at < u.created_at) THEN 'invite' \
|
||||
ELSE COALESCE(u.signup_source, 'unknown') END AS source, \
|
||||
u.signup_detail AS detail, \
|
||||
COALESCE(u.signup_device, 'unknown') AS device, \
|
||||
COALESCE((SELECT i.provider FROM auth_identities i WHERE i.user_id = u.id \
|
||||
ORDER BY i.created_at LIMIT 1), 'unknown') AS method \
|
||||
FROM users u WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2) \
|
||||
SELECT json_build_object(\
|
||||
'funnel', (SELECT json_build_object('signups', count(*), 'verified', count(*) FILTER (WHERE verified), \
|
||||
'own_chart', count(*) FILTER (WHERE own_chart), 'ordered', count(*) FILTER (WHERE ordered), \
|
||||
'checkout', count(*) FILTER (WHERE checkout), 'bought', count(*) FILTER (WHERE bought), \
|
||||
'weekly', count(*) FILTER (WHERE weekly)) FROM cohort), \
|
||||
'sources', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC, x.source), '[]') FROM ( \
|
||||
SELECT source, count(*) AS signups, count(*) FILTER (WHERE own_chart) AS own_chart, \
|
||||
count(*) FILTER (WHERE bought) AS bought FROM cohort GROUP BY source) x), \
|
||||
'details', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC, x.detail), '[]') FROM ( \
|
||||
SELECT detail, count(*) AS signups FROM cohort WHERE detail IS NOT NULL \
|
||||
GROUP BY detail ORDER BY count(*) DESC, detail LIMIT 10) x), \
|
||||
'devices', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC), '[]') FROM ( \
|
||||
SELECT device, count(*) AS signups FROM cohort GROUP BY device) x), \
|
||||
'methods', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC), '[]') FROM ( \
|
||||
SELECT method, count(*) AS signups FROM cohort GROUP BY method) x))"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn admin_stats(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<StatsQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let days = query.days.unwrap_or(30);
|
||||
if !(0..=366).contains(&days) {
|
||||
return Err(ApiError::BadRequest("days must be between 0 and 366".into()));
|
||||
}
|
||||
// The period in Hungarian days: its first and last day, and the moments
|
||||
// they start and end; the previous period of the same length before it.
|
||||
let (first_day, today, from, to, previous): (Date, Date, OffsetDateTime, OffsetDateTime, Option<OffsetDateTime>) =
|
||||
sqlx::query_as(
|
||||
"WITH t AS (SELECT (now() AT TIME ZONE 'Europe/Budapest')::date AS today), \
|
||||
p AS (SELECT today, CASE WHEN $1 = 0 \
|
||||
THEN LEAST(today, COALESCE((SELECT min((created_at AT TIME ZONE 'Europe/Budapest')::date) FROM users), today)) \
|
||||
ELSE today - ($1::int - 1) END AS first FROM t) \
|
||||
SELECT first, today, first::timestamp AT TIME ZONE 'Europe/Budapest', \
|
||||
(today + 1)::timestamp AT TIME ZONE 'Europe/Budapest', \
|
||||
CASE WHEN $1 = 0 THEN NULL ELSE (first - $1::int)::timestamp AT TIME ZONE 'Europe/Budapest' END \
|
||||
FROM p",
|
||||
)
|
||||
.bind(days)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
let kpi = kpi_sql();
|
||||
let period: Value = sqlx::query_scalar(&kpi).bind(from).bind(to).fetch_one(&state.db).await?;
|
||||
let before: Option<Value> = match previous {
|
||||
Some(start) => Some(sqlx::query_scalar(&kpi).bind(start).bind(from).fetch_one(&state.db).await?),
|
||||
None => None,
|
||||
};
|
||||
let daily: Value =
|
||||
sqlx::query_scalar(&daily_sql()).bind(from).bind(to).bind(first_day).bind(today).fetch_one(&state.db).await?;
|
||||
let cohort: Value = sqlx::query_scalar(&cohort_sql()).bind(from).bind(to).fetch_one(&state.db).await?;
|
||||
|
||||
// Everything so far.
|
||||
let totals: Value = sqlx::query_scalar(&format!(
|
||||
"SELECT json_build_object(\
|
||||
'members', (SELECT count(*) FROM users u WHERE {MEMBER}), \
|
||||
'own_charts', (SELECT count(*) FROM users u WHERE {MEMBER} \
|
||||
AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary)), \
|
||||
'buyers', (SELECT count(DISTINCT user_id) FROM stripe_checkouts WHERE live AND completed_at IS NOT NULL), \
|
||||
'revenue_huf', (SELECT COALESCE(sum(price_huf), 0) FROM stripe_checkouts WHERE live AND completed_at IS NOT NULL), \
|
||||
'weekly_subscribers', (SELECT count(*) FROM users u WHERE {MEMBER} AND u.weekly_email \
|
||||
AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary)), \
|
||||
'forum_members', (SELECT count(*) FROM forum.members m JOIN users u ON u.id = m.user_id WHERE {MEMBER}))"
|
||||
))
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
// Purchases in the period by package (gifts apart).
|
||||
let mut packages_sold: Value = sqlx::query_scalar(
|
||||
"SELECT COALESCE(json_agg(x ORDER BY x.revenue_huf DESC, x.package), '[]') FROM ( \
|
||||
SELECT package, gift_id IS NOT NULL AS gift, count(*) AS orders, sum(price_huf) AS revenue_huf \
|
||||
FROM stripe_checkouts WHERE live AND completed_at >= $1 AND completed_at < $2 GROUP BY 1, 2) x",
|
||||
)
|
||||
.bind(from)
|
||||
.bind(to)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if let Some(rows) = packages_sold.as_array_mut() {
|
||||
for row in rows {
|
||||
let name = row["package"].as_str().and_then(packages::find).map(|p| p.name);
|
||||
row["name"] = json!(name);
|
||||
}
|
||||
}
|
||||
|
||||
// What the AI wrote in the period, and what it cost (everyone's, admins' too).
|
||||
let content: Value = sqlx::query_scalar(
|
||||
"SELECT COALESCE(json_agg(x ORDER BY x.done DESC, x.kind), '[]') FROM ( \
|
||||
SELECT kind, count(*) FILTER (WHERE status = 'done') AS done, \
|
||||
count(*) FILTER (WHERE status = 'failed') AS failed, COALESCE(sum(cost_usd), 0) AS cost_usd \
|
||||
FROM ( \
|
||||
SELECT kind, status, cost_usd FROM analyses WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT 'question', status, cost_usd FROM questions WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT 'preview', status, cost_usd FROM prompt_previews WHERE created_at >= $1 AND created_at < $2 \
|
||||
) a GROUP BY kind) x",
|
||||
)
|
||||
.bind(from)
|
||||
.bind(to)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
// The weekly horoscope week by week since its first week (the last 12):
|
||||
// members who read it, and the Monday e-mails sent.
|
||||
let weekly: Value = sqlx::query_scalar(&format!(
|
||||
"WITH weeks AS (SELECT w::date AS week_start FROM generate_series( \
|
||||
GREATEST((SELECT min(week_start) FROM analyses WHERE kind = 'weekly'), \
|
||||
date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date - 77), \
|
||||
date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date, interval '7 days') w \
|
||||
WHERE EXISTS (SELECT 1 FROM analyses WHERE kind = 'weekly')) \
|
||||
SELECT COALESCE(json_agg(json_build_object('week_start', w.week_start, \
|
||||
'readers', (SELECT count(DISTINCT a.requested_by) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND a.week_start = w.week_start AND {MEMBER}), \
|
||||
'emails', (SELECT count(*) FROM email_outbox e WHERE e.template = 'weekly_horoscope' \
|
||||
AND e.sent_at IS NOT NULL AND e.payload->>'week_start' = w.week_start::text)) \
|
||||
ORDER BY w.week_start DESC), '[]') FROM weeks w"
|
||||
))
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"days": days,
|
||||
"from": first_day.to_string(),
|
||||
"to": today.to_string(),
|
||||
"totals": totals,
|
||||
"period": period,
|
||||
"previous": before,
|
||||
"daily": daily,
|
||||
"cohort": cohort,
|
||||
"packages": packages_sold,
|
||||
"content": content,
|
||||
"weekly": weekly,
|
||||
})))
|
||||
}
|
||||
@@ -24,7 +24,7 @@ use crate::auth::AuthUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// The Monday of the current week in Hungary.
|
||||
const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date";
|
||||
pub(super) const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date";
|
||||
|
||||
/// What a weekly text is about, for its cache key: the chart and the week.
|
||||
pub fn target_hash(chart_hash: &str, week_start: &str) -> String {
|
||||
@@ -184,22 +184,25 @@ pub struct EmailSwitch {
|
||||
|
||||
/// Turns Monday's e-mail on or off. Turned on, the first one comes next
|
||||
/// Monday (this week's horoscope is already in front of the member).
|
||||
pub(super) fn switch_sql() -> String {
|
||||
// Only a change from off to on moves the date: saving "on" again must not
|
||||
// hold back this Monday's e-mail.
|
||||
format!(
|
||||
"UPDATE users SET \
|
||||
weekly_email_sent_on = CASE WHEN $2 AND NOT weekly_email \
|
||||
THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \
|
||||
ELSE weekly_email_sent_on END, \
|
||||
weekly_email = $2, updated_at = now() \
|
||||
WHERE id = $1"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn set_email(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<EmailSwitch>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
sqlx::query(&format!(
|
||||
"UPDATE users SET weekly_email = $2, \
|
||||
weekly_email_sent_on = CASE WHEN $2 THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \
|
||||
ELSE weekly_email_sent_on END, \
|
||||
updated_at = now() \
|
||||
WHERE id = $1"
|
||||
))
|
||||
.bind(auth.id())
|
||||
.bind(req.on)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
sqlx::query(&switch_sql()).bind(auth.id()).bind(req.on).execute(&state.db).await?;
|
||||
Ok(Json(json!({ "email": req.on })))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Where a new member came from (`users.signup_source`, `signup_detail`,
|
||||
//! `signup_device`), for the admin statistics. The page sends what it saw
|
||||
//! when the visit began ([`CameFrom`]: the referring site's address and the
|
||||
//! link's campaign tags, kept in the page's memory only); the browser's name
|
||||
//! tells the apps' built-in browsers and the device type. Nothing is kept
|
||||
//! about visitors who do not sign up.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// What the page saw when the visit began, sent with a sign-up.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CameFrom {
|
||||
/// The referring page's address without its path (`l.facebook.com`), or
|
||||
/// an Android app's name (`com.facebook.katana`).
|
||||
#[serde(default)]
|
||||
pub referrer: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_source: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_medium: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_campaign: Option<String>,
|
||||
/// The name of the click id that was on the link: `fbclid`, `gclid` or `ttclid`.
|
||||
#[serde(default)]
|
||||
pub click: Option<String>,
|
||||
/// The app whose built-in browser the visitor left for the phone's own
|
||||
/// browser through the login page's way out (`facebook`, `instagram`…).
|
||||
#[serde(default)]
|
||||
pub app: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Arrival {
|
||||
pub source: &'static str,
|
||||
pub detail: Option<String>,
|
||||
pub device: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Printable text, at most `max` characters, or nothing.
|
||||
fn clean(value: Option<&str>, max: usize) -> Option<String> {
|
||||
let v: String = value?.trim().chars().filter(|c| !c.is_control()).take(max).collect();
|
||||
(!v.is_empty()).then_some(v)
|
||||
}
|
||||
|
||||
/// `host` is `domain` or one of its subdomains.
|
||||
fn is(host: &str, domain: &str) -> bool {
|
||||
host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.'))
|
||||
}
|
||||
|
||||
/// The app of a built-in browser, from the browser's name (as on the login page).
|
||||
fn in_app(ua: &str) -> Option<&'static str> {
|
||||
let lower = ua.to_ascii_lowercase();
|
||||
if lower.contains("instagram") {
|
||||
Some("instagram")
|
||||
} else if lower.contains("messengerforios") || lower.contains("orca-android") || lower.contains("fb_iab/messenger")
|
||||
{
|
||||
Some("messenger")
|
||||
} else if ["FBAN", "FBAV", "FB_IAB", "FBIOS", "FB4A"].iter().any(|m| ua.contains(m)) {
|
||||
Some("facebook")
|
||||
} else if lower.contains("tiktok") || lower.contains("musical_ly") || lower.contains("bytedance") {
|
||||
Some("tiktok")
|
||||
} else if ua.contains("Android") && ua.contains("; wv)") {
|
||||
Some("app")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn device(ua: &str) -> &'static str {
|
||||
if ua.contains("iPad") || ua.contains("Tablet") || (ua.contains("Android") && !ua.contains("Mobile")) {
|
||||
"tablet"
|
||||
} else if ua.contains("Mobi") || ua.contains("iPhone") || ua.contains("Android") {
|
||||
"mobile"
|
||||
} else {
|
||||
"desktop"
|
||||
}
|
||||
}
|
||||
|
||||
/// A campaign tag's source, as the site's own links may write it.
|
||||
fn tagged(source: &str) -> &'static str {
|
||||
let s = source.to_lowercase();
|
||||
if s.contains("facebook") || s == "fb" || s.starts_with("fb_") || s.starts_with("fb-") {
|
||||
"facebook"
|
||||
} else if s.contains("instagram") || s == "ig" {
|
||||
"instagram"
|
||||
} else if s.contains("messenger") {
|
||||
"messenger"
|
||||
} else if s.contains("tiktok") {
|
||||
"tiktok"
|
||||
} else if s.contains("google") {
|
||||
"google"
|
||||
} else if s.contains("bing") {
|
||||
"bing"
|
||||
} else if s.contains("mail") || s.contains("newsletter") || s.contains("hirlevel") || s.contains("hírlevél") {
|
||||
"email"
|
||||
} else {
|
||||
"other"
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of the referring site (`None`: the site itself).
|
||||
fn site(host: &str, own_host: &str) -> Option<&'static str> {
|
||||
let own = own_host.trim_start_matches("www.");
|
||||
if host == "localhost" || (!own.is_empty() && is(host, own)) {
|
||||
return None;
|
||||
}
|
||||
let kind = if is(host, "messenger.com") || host.starts_with("com.facebook.orca") {
|
||||
"messenger"
|
||||
} else if is(host, "facebook.com") || is(host, "fb.com") || host == "fb.me" || host.starts_with("com.facebook.") {
|
||||
"facebook"
|
||||
} else if is(host, "instagram.com") || host.starts_with("com.instagram.") {
|
||||
"instagram"
|
||||
} else if is(host, "tiktok.com") || host.starts_with("com.zhiliaoapp.") || host.starts_with("com.ss.android.") {
|
||||
"tiktok"
|
||||
} else if host.starts_with("mail.")
|
||||
|| host.starts_with("posta.")
|
||||
|| is(host, "outlook.live.com")
|
||||
|| is(host, "outlook.office.com")
|
||||
|| is(host, "freemail.hu")
|
||||
|| is(host, "citromail.hu")
|
||||
|| host == "com.google.android.gm"
|
||||
{
|
||||
"email"
|
||||
} else if host.split('.').any(|label| label == "google")
|
||||
|| host.starts_with("com.google.android.googlequicksearchbox")
|
||||
{
|
||||
"google"
|
||||
} else if is(host, "bing.com") {
|
||||
"bing"
|
||||
} else if ["duckduckgo.com", "yahoo.com", "ecosia.org", "search.brave.com", "startpage.com", "qwant.com"]
|
||||
.iter()
|
||||
.any(|d| is(host, d))
|
||||
|| host.split('.').any(|label| label == "yandex")
|
||||
{
|
||||
"search"
|
||||
} else {
|
||||
"other"
|
||||
};
|
||||
Some(kind)
|
||||
}
|
||||
|
||||
/// The source of a sign-up. In order: the link's campaign tags (the site's
|
||||
/// own links), an app's built-in browser, the app the visitor came out of,
|
||||
/// a click id, the referring site; else typed in or opened from a bookmark
|
||||
/// or an app that hides where it came from (`direct`).
|
||||
pub fn classify(user_agent: Option<&str>, came: Option<&CameFrom>, own_host: &str) -> Arrival {
|
||||
let empty = CameFrom::default();
|
||||
let came = came.unwrap_or(&empty);
|
||||
let referrer = clean(came.referrer.as_deref(), 120).map(|h| h.to_ascii_lowercase());
|
||||
let referrer = referrer.map(|h| h.split(':').next().unwrap_or_default().to_string()).filter(|h| !h.is_empty());
|
||||
let utm: Vec<String> =
|
||||
[("utm_source", &came.utm_source), ("utm_medium", &came.utm_medium), ("utm_campaign", &came.utm_campaign)]
|
||||
.into_iter()
|
||||
.filter_map(|(key, value)| clean(value.as_deref(), 60).map(|v| format!("{key}={v}")))
|
||||
.collect();
|
||||
let referring_site = referrer.as_deref().and_then(|h| site(h, own_host));
|
||||
let ua = user_agent.unwrap_or_default();
|
||||
let app = clean(came.app.as_deref(), 20).and_then(|a| {
|
||||
["facebook", "instagram", "messenger", "tiktok", "app"].into_iter().find(|known| *known == a.to_lowercase())
|
||||
});
|
||||
let click = match came.click.as_deref() {
|
||||
Some("fbclid") => Some("facebook"),
|
||||
Some("gclid") => Some("google"),
|
||||
Some("ttclid") => Some("tiktok"),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let source = clean(came.utm_source.as_deref(), 60)
|
||||
.map(|s| tagged(&s))
|
||||
.or_else(|| in_app(ua))
|
||||
.or(app)
|
||||
.or(click)
|
||||
.or(referring_site)
|
||||
.unwrap_or("direct");
|
||||
let detail = if utm.is_empty() { referring_site.and(referrer) } else { Some(utm.join("&")) };
|
||||
Arrival {
|
||||
source,
|
||||
detail: detail.map(|d| d.chars().take(200).collect()),
|
||||
device: user_agent.filter(|u| !u.is_empty()).map(device),
|
||||
}
|
||||
}
|
||||
|
||||
/// The site's own address without the scheme, port and path.
|
||||
pub fn host_of(base_url: &str) -> String {
|
||||
let rest = base_url.split("://").nth(1).unwrap_or(base_url);
|
||||
rest.split(['/', ':']).next().unwrap_or_default().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FB_ANDROID: &str = "Mozilla/5.0 (Linux; Android 14; SM-A546B Build/UP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/490.0.0.50.82;]";
|
||||
const CHROME_ANDROID: &str = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Mobile Safari/537.36";
|
||||
const MAC: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36";
|
||||
const IPAD: &str = "Mozilla/5.0 (iPad; CPU OS 26_6_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/157.0 Mobile/15E148 Safari/604.1";
|
||||
|
||||
fn came(referrer: Option<&str>) -> CameFrom {
|
||||
CameFrom { referrer: referrer.map(str::to_string), ..CameFrom::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources() {
|
||||
let own = "sorsfonalak.hu";
|
||||
// Facebook's own browser, whatever the referrer says.
|
||||
let a = classify(Some(FB_ANDROID), Some(&came(Some("m.facebook.com"))), own);
|
||||
assert_eq!((a.source, a.detail.as_deref(), a.device), ("facebook", Some("m.facebook.com"), Some("mobile")));
|
||||
// Out of the app through the login page's way out: Chrome, no referrer.
|
||||
let out = CameFrom { app: Some("facebook".into()), ..CameFrom::default() };
|
||||
assert_eq!(classify(Some(CHROME_ANDROID), Some(&out), own).source, "facebook");
|
||||
// Search engines, mail, other sites, the site itself.
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("www.google.com"))), own).source, "google");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("www.google.co.hu"))), own).source, "google");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("mail.google.com"))), own).source, "email");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("duckduckgo.com"))), own).source, "search");
|
||||
let other = classify(Some(MAC), Some(&came(Some("astro-blog.hu"))), own);
|
||||
assert_eq!((other.source, other.detail.as_deref()), ("other", Some("astro-blog.hu")));
|
||||
let internal = classify(Some(MAC), Some(&came(Some("www.sorsfonalak.hu"))), own);
|
||||
assert_eq!((internal.source, internal.detail, internal.device), ("direct", None, Some("desktop")));
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("notfacebook.com"))), own).source, "other");
|
||||
// Campaign tags win, and are the detail.
|
||||
let tags = CameFrom {
|
||||
utm_source: Some("fb".into()),
|
||||
utm_campaign: Some("heti".into()),
|
||||
referrer: Some("l.facebook.com".into()),
|
||||
..CameFrom::default()
|
||||
};
|
||||
let a = classify(Some(IPAD), Some(&tags), own);
|
||||
assert_eq!(
|
||||
(a.source, a.detail.as_deref(), a.device),
|
||||
("facebook", Some("utm_source=fb&utm_campaign=heti"), Some("tablet"))
|
||||
);
|
||||
// A click id alone; nothing at all.
|
||||
let click = CameFrom { click: Some("fbclid".into()), ..CameFrom::default() };
|
||||
assert_eq!(classify(Some(CHROME_ANDROID), Some(&click), own).source, "facebook");
|
||||
assert_eq!(classify(None, None, own), Arrival { source: "direct", detail: None, device: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn site_address() {
|
||||
assert_eq!(host_of("https://sorsfonalak.hu"), "sorsfonalak.hu");
|
||||
assert_eq!(host_of("http://localhost:3001/"), "localhost");
|
||||
}
|
||||
}
|
||||
@@ -2093,8 +2093,31 @@ async fn weekly_horoscope_of_the_own_chart(pool: PgPool) {
|
||||
let off = json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", "listener": null, "weekly": false});
|
||||
let r = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": false, "forum": off}))).await;
|
||||
assert_eq!((r.status, &r.body["weekly_horoscope"], &r.body["forum"]), (StatusCode::OK, &json!(false), &off));
|
||||
// The mail client's one-click unsubscribe turns off the weekly e-mail only.
|
||||
// Turned on again from this page: as on the site, the first one comes next Monday.
|
||||
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||
let sent_on: Option<time::Date> =
|
||||
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sent_on, Some(start));
|
||||
// Saved again while on: this Monday's e-mail is not held back.
|
||||
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||
let sent_on: Option<time::Date> =
|
||||
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sent_on, None);
|
||||
// The mail client's one-click unsubscribe turns off the weekly e-mail only.
|
||||
let r = app.call("POST", &format!("/v1/public/weekly/unsubscribe?token={token}"), None, None).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get(&page, None).await.body["weekly_horoscope"], false);
|
||||
@@ -4289,3 +4312,113 @@ async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) {
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn admin_statistics_and_where_members_came_from(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await; // BOOTSTRAP_ADMIN_EMAILS
|
||||
const FB_APP: &str = "Mozilla/5.0 (Linux; Android 14; SM-A546B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/490.0.0.50.82;]";
|
||||
const MAC: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0 Safari/537.36";
|
||||
|
||||
// From Facebook's own browser, and from a Google search on a computer.
|
||||
let mut tokens = Vec::new();
|
||||
for (email, ua, came) in [
|
||||
("anna@example.com", FB_APP, json!({"referrer": "m.facebook.com"})),
|
||||
("bela@example.com", MAC, json!({"referrer": "www.google.com"})),
|
||||
] {
|
||||
let r = app
|
||||
.call_with(
|
||||
"POST",
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
Some(json!({"email": email, "display_name": "X", "came_from": came})),
|
||||
&[("user-agent", ua)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
let url = app.outbox_url(email, "verify_email").await;
|
||||
let r = app
|
||||
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
tokens.push(r.body["session"]["token"].as_str().unwrap().to_string());
|
||||
}
|
||||
// With Google, from a tagged link of the site's own Facebook post.
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/google",
|
||||
None,
|
||||
json!({"id_token": google_token("g-9", "cili@gmail.com", GOOGLE_CLIENT),
|
||||
"came_from": {"utm_source": "fb", "utm_campaign": "heti", "referrer": "l.facebook.com"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let row: (Option<String>, Option<String>, Option<String>) = sqlx::query_as(
|
||||
"SELECT signup_source, signup_detail, signup_device FROM users WHERE email = 'anna@example.com'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(row, (Some("facebook".into()), Some("m.facebook.com".into()), Some("mobile".into())));
|
||||
let export = app.get("/v1/me/export", Some(&tokens[0])).await;
|
||||
assert_eq!(export.body["signup_came_from"]["source"], "facebook", "{}", export.body);
|
||||
|
||||
// Anna makes her chart and pays (live); Béla pays in test mode only.
|
||||
app.chart(&tokens[0], "Én", true, "1990-05-15").await;
|
||||
let ids: Vec<uuid::Uuid> = sqlx::query_scalar(
|
||||
"SELECT id FROM users WHERE email IN ('anna@example.com', 'bela@example.com') ORDER BY email",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for (n, (user, live)) in [(ids[0], true), (ids[1], false)].into_iter().enumerate() {
|
||||
sqlx::query(
|
||||
"INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live, completed_at) \
|
||||
VALUES ($1, $2, 'single', 2000, $3, now())",
|
||||
)
|
||||
.bind(format!("cs_stats_{n}"))
|
||||
.bind(user)
|
||||
.bind(live)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&tokens[0])).await.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.get("/v1/admin/stats?days=999", Some(&admin)).await.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.get("/v1/admin/stats?days=7", Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let s = &r.body;
|
||||
// The admin is not counted as a member.
|
||||
assert_eq!((&s["totals"]["members"], &s["totals"]["own_charts"]), (&json!(3), &json!(1)));
|
||||
assert_eq!((&s["totals"]["buyers"], &s["totals"]["revenue_huf"]), (&json!(1), &json!(2000)));
|
||||
let p = &s["period"];
|
||||
assert_eq!(
|
||||
(&p["signups"], &p["own_charts"], &p["orders"], &p["revenue_huf"]),
|
||||
(&json!(3), &json!(1), &json!(1), &json!(2000))
|
||||
);
|
||||
assert_eq!(s["previous"]["signups"], 0);
|
||||
let daily = s["daily"].as_array().unwrap();
|
||||
assert_eq!(daily.len(), 7);
|
||||
assert_eq!((&daily[6]["date"], &daily[6]["signups"]), (&s["to"], &json!(3)));
|
||||
let c = &s["cohort"];
|
||||
assert_eq!(
|
||||
c["funnel"],
|
||||
json!({"signups": 3, "verified": 3, "own_chart": 1, "ordered": 0, "checkout": 1, "bought": 1, "weekly": 0})
|
||||
);
|
||||
assert_eq!(
|
||||
c["sources"],
|
||||
json!([{"source": "facebook", "signups": 2, "own_chart": 1, "bought": 1}, {"source": "google", "signups": 1, "own_chart": 0, "bought": 0}])
|
||||
);
|
||||
let details = c["details"].as_array().unwrap();
|
||||
assert!(details.contains(&json!({"detail": "utm_source=fb&utm_campaign=heti", "signups": 1})), "{details:?}");
|
||||
assert!(details.contains(&json!({"detail": "www.google.com", "signups": 1})), "{details:?}");
|
||||
assert_eq!(c["methods"], json!([{"method": "password", "signups": 2}, {"method": "google", "signups": 1}]));
|
||||
assert_eq!(
|
||||
s["packages"],
|
||||
json!([{"package": "single", "gift": false, "orders": 1, "revenue_huf": 2000, "name": "Egy elemzés"}])
|
||||
);
|
||||
// Since the first member: no previous period.
|
||||
let all = app.get("/v1/admin/stats?days=0", Some(&admin)).await.body;
|
||||
assert!(all["previous"].is_null());
|
||||
assert_eq!(all["period"]["signups"], 3);
|
||||
}
|
||||
|
||||
@@ -204,6 +204,10 @@ struct Incoming {
|
||||
|
||||
/// At most one typing notice per target in this time.
|
||||
const TYPING_EVERY: Duration = Duration::from_secs(2);
|
||||
/// At most one typing notice this often per connection, whatever the place.
|
||||
const TYPING_ANY_EVERY: Duration = Duration::from_secs(1);
|
||||
/// A typing notice is a few dozen bytes; anything longer is not one.
|
||||
const TYPING_MAX_BYTES: usize = 200;
|
||||
|
||||
/// "I am typing", from the page: passed on to those who may see that place.
|
||||
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||
@@ -248,6 +252,9 @@ async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
|
||||
let (user, moderator) = (me.user, me.moderator);
|
||||
let mut last_typing: Option<(String, std::time::Instant)> = None;
|
||||
// Whatever the place: at most one notice a second per connection, so
|
||||
// alternating places cannot flood the database and the other members.
|
||||
let mut last_any: Option<std::time::Instant> = None;
|
||||
let mut ping = tokio::time::interval(PING);
|
||||
ping.tick().await;
|
||||
loop {
|
||||
@@ -280,12 +287,16 @@ async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, d
|
||||
}
|
||||
incoming = socket.recv() => match incoming {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
// Typing notices, a few seconds apart per place.
|
||||
let fresh = last_typing
|
||||
.as_ref()
|
||||
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
||||
// Typing notices, a few seconds apart per place, one a second in all.
|
||||
let fresh = text.len() <= TYPING_MAX_BYTES
|
||||
&& last_any.is_none_or(|at| at.elapsed() >= TYPING_ANY_EVERY)
|
||||
&& last_typing
|
||||
.as_ref()
|
||||
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
||||
if fresh {
|
||||
last_typing = Some((text.to_string(), std::time::Instant::now()));
|
||||
let now = std::time::Instant::now();
|
||||
last_any = Some(now);
|
||||
last_typing = Some((text.to_string(), now));
|
||||
if let Some(event) = typing(&db, &me, &text).await {
|
||||
emit(&db, event).await;
|
||||
}
|
||||
|
||||
@@ -302,6 +302,10 @@ pub async fn serve(
|
||||
let thread = super::threads::readable_thread(&state.db, &viewer, thread)
|
||||
.await
|
||||
.map_err(|_| ApiError::NotFound("photo"))?;
|
||||
// A removed thread takes its photos down too (moderators still see them).
|
||||
if thread.deleted_at.is_some() && !viewer.is_moderator() {
|
||||
return Err(ApiError::NotFound("photo"));
|
||||
}
|
||||
thread.deleted_at.is_none() && thread.visibility == "public" && !deleted
|
||||
}
|
||||
};
|
||||
@@ -312,18 +316,22 @@ pub async fn serve(
|
||||
.map_err(|e| ApiError::Internal(format!("reading a photo: {e}")))?
|
||||
.ok_or(ApiError::NotFound("photo"))?;
|
||||
let content_type = if file.ends_with(".webp") { "image/webp" } else { "image/jpeg" };
|
||||
let cache = if public { "public, max-age=31536000, immutable" } else { "private, max-age=3600" };
|
||||
// Not for long even when public: a moderator may remove the post, and the
|
||||
// CDN and the browsers must let go of the photo within the hour.
|
||||
let cache = if public { "public, max-age=3600" } else { "private, max-age=3600" };
|
||||
Ok(([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, cache)], object.bytes).into_response())
|
||||
}
|
||||
|
||||
/// Every hour: unattached photos older than a day, and the photos of posts
|
||||
/// removed more than a year ago, leave the storage and the table.
|
||||
/// (or whole threads) removed more than a year ago, leave the storage and the table.
|
||||
pub async fn cleanup(state: &AppState) -> anyhow::Result<u64> {
|
||||
let Some(storage) = &state.storage else { return Ok(0) };
|
||||
let gone: Vec<(Uuid, String, String)> = sqlx::query_as(
|
||||
"SELECT ph.id, ph.file, ph.thumb FROM forum.photos ph LEFT JOIN forum.posts p ON p.id = ph.post_id \
|
||||
LEFT JOIN forum.threads t ON t.id = p.thread_id \
|
||||
WHERE (ph.post_id IS NULL AND ph.created_at < now() - interval '1 day') \
|
||||
OR (p.deleted_at IS NOT NULL AND p.deleted_at < now() - interval '1 year') \
|
||||
OR (t.deleted_at IS NOT NULL AND t.deleted_at < now() - interval '1 year') \
|
||||
LIMIT 500",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
|
||||
@@ -316,13 +316,19 @@ async fn set_helped(
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The sharer's link goes (as when revoked on the main site).
|
||||
/// The sharer's link goes (as when revoked on the main site), unless another
|
||||
/// live question of theirs still shows it: asking twice about the same chart
|
||||
/// reuses one link (call it after this post let go of it).
|
||||
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
||||
.bind(share)
|
||||
.bind(owner)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.posts p JOIN forum.threads t ON t.id = p.thread_id \
|
||||
WHERE p.share_id = $1 AND p.deleted_at IS NULL AND t.deleted_at IS NULL)",
|
||||
)
|
||||
.bind(share)
|
||||
.bind(owner)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+49
-10
@@ -1327,18 +1327,41 @@ async fn a_question_about_ones_chart(pool: PgPool) {
|
||||
assert_eq!(shown["posts"][0]["share"]["revoked"], true);
|
||||
assert!(shown["posts"][0]["share"].get("points").is_none());
|
||||
|
||||
// The author takes it off (only she may): the card goes, the link stops working.
|
||||
// A second question about the same chart uses the same link.
|
||||
sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap();
|
||||
let (status, second) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&anna),
|
||||
json!({ "topic": "egbolt-es-kepletek", "title": "És a Vénusz?", "body": "Még egy kérdés.", "share": "annaforum000001" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{second}");
|
||||
let second = second["id"].as_i64().unwrap();
|
||||
let revoked = || async {
|
||||
sqlx::query_scalar::<_, bool>("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
// The author takes it off the first (only she may): that card goes, the
|
||||
// other question keeps it, so the link stays.
|
||||
let opening = shown["posts"][0]["id"].as_i64().unwrap();
|
||||
let uri = format!("/v1/forum/posts/{opening}/share");
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT);
|
||||
assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null());
|
||||
let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(revoked);
|
||||
assert!(!revoked().await);
|
||||
let other = app.get(&format!("/v1/forum/threads/{second}"), Some(&bea)).await;
|
||||
assert_eq!(other["posts"][0]["share"]["points"][1]["sign"], "pisces");
|
||||
|
||||
// Deleting the last question that shows it: now the link stops working.
|
||||
let last = other["posts"][0]["id"].as_i64().unwrap();
|
||||
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{last}"), Some(&anna), json!({})).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert!(revoked().await);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1604,7 +1627,8 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
assert_eq!(thread["posts"][0]["photos"].as_array().unwrap().len(), 2);
|
||||
let (status, headers, _) = app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(headers["cache-control"].to_str().unwrap().contains("immutable"));
|
||||
// Public, but only for an hour: a removed post's photo must not linger in caches.
|
||||
assert_eq!(headers["cache-control"].to_str().unwrap(), "public, max-age=3600");
|
||||
|
||||
// In a members-only topic: members only, not cached publicly; Bea cannot use Anna's photo.
|
||||
let (_, third) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
|
||||
@@ -1647,11 +1671,26 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
let (status, body) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
|
||||
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
|
||||
|
||||
// Unattached for over a day: gone from the table and the storage.
|
||||
// A removed thread takes its photos down (the posts themselves stay unmarked).
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now() WHERE id = $1")
|
||||
.bind(created["id"].as_i64().unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.raw("GET", &path(&jpeg["url"]), Some(&bea), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||
|
||||
// Unattached for over a day, and in a thread removed over a year ago: gone
|
||||
// from the table and the storage.
|
||||
sqlx::query("UPDATE forum.photos SET created_at = now() - interval '2 days' WHERE post_id IS NULL")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now() - interval '2 years' WHERE id = $1")
|
||||
.bind(created["id"].as_i64().unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = AppState {
|
||||
db: pool.clone(),
|
||||
flood_secs: 0,
|
||||
@@ -1660,7 +1699,7 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
storage: Some(object_storage::Storage::new(storage)),
|
||||
links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
|
||||
};
|
||||
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 2);
|
||||
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 4);
|
||||
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
|
||||
assert_eq!(left, 3);
|
||||
assert_eq!(left, 1);
|
||||
}
|
||||
|
||||
@@ -218,6 +218,15 @@ export default async function PrivacyPage() {
|
||||
</td>
|
||||
<td>Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Regisztrációkor: honnan érkeztél az oldalra (például Facebook vagy Google-keresés, egy másik oldal
|
||||
címe az elérési útja nélkül, vagy a link kampánycímkéje), és hogy telefonról, tabletről vagy
|
||||
számítógépről
|
||||
</td>
|
||||
<td>Statisztika: hogy lássuk, honnan jönnek a tagok, és melyik bejegyzésünk vagy hirdetésünk működik</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Melyik oldalt nyitottad meg, honnan érkeztél, a böngésződ és az eszközöd típusa, az országod és az oldal
|
||||
@@ -436,6 +445,11 @@ export default async function PrivacyPage() {
|
||||
eszközt használsz, és mennyi idő alatt töltődött be az oldal. Mi ebből csak összesített számokat látunk, az
|
||||
egyes látogatókat nem tudjuk követni.
|
||||
</p>
|
||||
<p>
|
||||
Ha regisztrálsz, a fiókodhoz elmentjük, honnan érkeztél az oldalra és milyen eszközről. Ehhez sem sütit,
|
||||
sem a böngészőben tárolt adatot nem használunk: az oldal csak az adott látogatás alatt, a saját memóriájában
|
||||
jegyzi meg, és a regisztrációval együtt küldi el. Akik nem regisztrálnak, azokról ilyet nem tárolunk.
|
||||
</p>
|
||||
<p>
|
||||
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
||||
csak a számításhoz küldjük el, a szerveren nem tároljuk őket. Hogy oldalváltáskor ne vesszenek el, a
|
||||
|
||||
@@ -0,0 +1,616 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { KIND_LABELS } from "@/lib/feedback";
|
||||
import type { AdminStats as Stats, StatsDay, StatsPeriod } from "@/lib/types";
|
||||
import { MONTHS, weekRange } from "@/lib/weekly";
|
||||
|
||||
const PERIODS: [number, string][] = [
|
||||
[7, "7 nap"],
|
||||
[30, "30 nap"],
|
||||
[90, "90 nap"],
|
||||
[0, "Mind"],
|
||||
];
|
||||
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
facebook: "Facebook",
|
||||
instagram: "Instagram",
|
||||
messenger: "Messenger",
|
||||
tiktok: "TikTok",
|
||||
google: "Google kereső",
|
||||
bing: "Bing",
|
||||
search: "Más kereső",
|
||||
email: "E-mail",
|
||||
app: "Más alkalmazás",
|
||||
other: "Más oldal",
|
||||
direct: "Közvetlenül",
|
||||
shared: "Megosztott link",
|
||||
invite: "Meghívó",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const DEVICE_LABELS: Record<string, string> = {
|
||||
mobile: "Telefon",
|
||||
tablet: "Tablet",
|
||||
desktop: "Számítógép",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const METHOD_LABELS: Record<string, string> = {
|
||||
google: "Google",
|
||||
apple: "Apple",
|
||||
facebook: "Facebook",
|
||||
password: "E-mail és jelszó",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const CONTENT_LABELS: Record<string, string> = {
|
||||
...KIND_LABELS,
|
||||
celebrity: "Híres ember elemzése",
|
||||
preview: "Prompt-próba (admin)",
|
||||
};
|
||||
|
||||
const WEEKDAYS = ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"];
|
||||
|
||||
const num = (n: number) => n.toLocaleString("hu-HU");
|
||||
const huf = (n: number) => `${num(n)} Ft`;
|
||||
const usd = (n: number) =>
|
||||
n.toLocaleString("hu-HU", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
const pct = (part: number, whole: number) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "–");
|
||||
|
||||
/** "nov. 24." */
|
||||
function shortDay(iso: string): string {
|
||||
const [, m, d] = iso.split("-").map(Number);
|
||||
return `${MONTHS[m - 1].slice(0, 3)}. ${d}.`;
|
||||
}
|
||||
|
||||
/** "november 24., hétfő" */
|
||||
function longDay(iso: string): string {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
const weekday = WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()];
|
||||
return `${MONTHS[m - 1]} ${d}., ${weekday}`;
|
||||
}
|
||||
|
||||
function addDays(iso: string, days: number): string {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Admin → Statisztika: how the site is doing, for the chosen period. */
|
||||
export function AdminStats() {
|
||||
const [days, setDays] = useState(30);
|
||||
const [data, setData] = useState<Stats | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
api<Stats>(`/admin/stats?days=${days}`)
|
||||
.then((d) => live && setData(d))
|
||||
.catch((e) => live && setError(errorText(e)))
|
||||
.finally(() => live && setLoading(false));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [days]);
|
||||
|
||||
return (
|
||||
<div className="field stats" style={{ gap: 18 }}>
|
||||
<div className="stats-filter" role="group" aria-label="Időszak">
|
||||
{PERIODS.map(([d, label]) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
className={d === days ? "btn btn-sm btn-primary" : "btn btn-sm"}
|
||||
aria-pressed={d === days}
|
||||
onClick={() => setDays(d)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
{data && (
|
||||
<span className="hint">
|
||||
{longDay(data.from).replace(/, .*/, "")} – {longDay(data.to).replace(/, .*/, "")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!data && !error && <p className="muted">Betöltés…</p>}
|
||||
{data && (
|
||||
<div className="field" style={{ gap: 18, opacity: loading ? 0.55 : 1 }} aria-busy={loading}>
|
||||
<Totals data={data} />
|
||||
<Tiles
|
||||
period={data.period}
|
||||
previous={data.previous}
|
||||
days={data.days}
|
||||
subscribers={data.totals.weekly_subscribers}
|
||||
/>
|
||||
<Daily daily={data.daily} />
|
||||
<div className="stats-grid">
|
||||
<Funnel data={data} />
|
||||
<Sources data={data} />
|
||||
</div>
|
||||
<div className="stats-grid">
|
||||
<Packages data={data} />
|
||||
<Weekly data={data} />
|
||||
</div>
|
||||
<Content data={data} />
|
||||
<p className="hint">
|
||||
A tagok számában az adminok nem szerepelnek. A bevétel az éles Stripe-fizetések összege, a tesztfizetések
|
||||
nélkül. A napokat magyar idő szerint számoljuk. Azokról, akik nem regisztrálnak, nem tárolunk semmit; őket a
|
||||
Cloudflare Web Analytics mutatja.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Totals({ data }: { data: Stats }) {
|
||||
const t = data.totals;
|
||||
return (
|
||||
<p className="muted stats-totals">
|
||||
Eddig összesen: <strong>{num(t.members)}</strong> tag · <strong>{num(t.own_charts)}</strong> saját képlet ·{" "}
|
||||
<strong>{num(t.buyers)}</strong> fizető vásárló · <strong>{huf(t.revenue_huf)}</strong> bevétel ·{" "}
|
||||
<strong>{num(t.weekly_subscribers)}</strong> kéri a heti levelet · <strong>{num(t.forum_members)}</strong>{" "}
|
||||
fórumtag
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/** "+2 az előző 30 naphoz képest" */
|
||||
function Delta({ now, before, days }: { now: number; before: number | undefined; days: number }) {
|
||||
if (before === undefined) return null;
|
||||
const diff = now - before;
|
||||
const text =
|
||||
diff === 0
|
||||
? `ugyanannyi, mint az előző ${days} napban`
|
||||
: `${diff > 0 ? "+" : "−"}${num(Math.abs(diff))} az előző ${days} naphoz képest`;
|
||||
return <span className="stats-tile-sub">{text}</span>;
|
||||
}
|
||||
|
||||
function Tiles({
|
||||
period: p,
|
||||
previous: b,
|
||||
days,
|
||||
subscribers,
|
||||
}: {
|
||||
period: StatsPeriod;
|
||||
previous: StatsPeriod | null;
|
||||
days: number;
|
||||
subscribers: number;
|
||||
}) {
|
||||
const net = p.revenue_huf - p.refunded_huf;
|
||||
return (
|
||||
<dl className="stats-tiles">
|
||||
<div>
|
||||
<dt>Új tag</dt>
|
||||
<dd className="stats-tile-value">{num(p.signups)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.signups} before={b?.signups} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Saját képletet készített</dt>
|
||||
<dd className="stats-tile-value">{num(p.own_charts)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.own_charts} before={b?.own_charts} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Vásárlás</dt>
|
||||
<dd className="stats-tile-value">{huf(net)}</dd>
|
||||
<dd className="stats-tile-sub">
|
||||
{num(p.orders)} fizetés, {num(p.buyers)} vásárló
|
||||
{p.refunded_huf > 0 && `, ${huf(p.refunded_huf)} visszatérítve`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Elemzés és kérdés</dt>
|
||||
<dd className="stats-tile-value">{num(p.analyses + p.questions)}</dd>
|
||||
<dd className="stats-tile-sub">
|
||||
{num(p.analyses)} elemzés, {num(p.questions)} kérdés
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Heti horoszkópot olvasott</dt>
|
||||
<dd className="stats-tile-value">{num(p.weekly_readers)}</dd>
|
||||
<dd className="stats-tile-sub">{num(subscribers)} tag kéri a hétfői levelet</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Fórum-hozzászólás</dt>
|
||||
<dd className="stats-tile-value">{num(p.forum_posts)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.forum_posts} before={b?.forum_posts} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>AI-költség</dt>
|
||||
<dd className="stats-tile-value">{usd(p.ai_cost_usd)}</dd>
|
||||
<dd className="stats-tile-sub">minden elemzés, válasz és próba</dd>
|
||||
</div>
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
const SERIES: { key: keyof StatsDay; label: string; value: (d: StatsDay) => number; unit: string }[] = [
|
||||
{ key: "signups", label: "Új tag", value: (d) => d.signups, unit: "új tag" },
|
||||
{ key: "own_charts", label: "Saját képlet", value: (d) => d.own_charts, unit: "saját képlet" },
|
||||
{ key: "analyses", label: "Elemzés és kérdés", value: (d) => d.analyses + d.questions, unit: "elemzés és kérdés" },
|
||||
{ key: "orders", label: "Fizetés", value: (d) => d.orders, unit: "fizetés" },
|
||||
{ key: "weekly_readers", label: "Heti horoszkóp", value: (d) => d.weekly_readers, unit: "heti olvasó" },
|
||||
{ key: "forum_posts", label: "Fórum", value: (d) => d.forum_posts, unit: "hozzászólás" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Day by day, one small chart per measure on the same days. Pointing at (or
|
||||
* tapping) a day shows that day's numbers in the line above; the table
|
||||
* below has them all.
|
||||
*/
|
||||
function Daily({ daily }: { daily: StatsDay[] }) {
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const day = hover !== null ? daily[hover] : null;
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Napról napra</h2>
|
||||
<p className="stats-readout" aria-hidden="true">
|
||||
{day ? (
|
||||
<>
|
||||
<strong>{longDay(day.date)}</strong>
|
||||
{SERIES.map((s) => ` · ${num(s.value(day))} ${s.unit}`).join("")}
|
||||
{day.revenue_huf > 0 && ` · ${huf(day.revenue_huf)}`}
|
||||
</>
|
||||
) : (
|
||||
<span className="muted">Mutass egy napra a számaiért.</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="stats-daily" onPointerLeave={() => setHover(null)}>
|
||||
{SERIES.map((s) => {
|
||||
const values = daily.map(s.value);
|
||||
const max = Math.max(...values, 0);
|
||||
const total = values.reduce((a, v) => a + v, 0);
|
||||
return (
|
||||
<div key={s.key} className="spark">
|
||||
<div className="spark-head">
|
||||
<span>{s.label}</span>
|
||||
<strong>{num(total)}</strong>
|
||||
</div>
|
||||
<div
|
||||
className="spark-plot"
|
||||
role="img"
|
||||
aria-label={`${s.label}: összesen ${total}, egy napon legfeljebb ${max}`}
|
||||
>
|
||||
{max > 0 && <span className="spark-max">{num(max)}</span>}
|
||||
<div className="spark-bars">
|
||||
{values.map((v, i) => (
|
||||
<span
|
||||
key={daily[i].date}
|
||||
className={i === hover ? "spark-col is-on" : "spark-col"}
|
||||
onPointerEnter={() => setHover(i)}
|
||||
onPointerDown={() => setHover(i)}
|
||||
>
|
||||
{v > 0 && <span className="spark-bar" style={{ height: `${Math.max((v / max) * 100, 6)}%` }} />}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="spark-axis" aria-hidden="true">
|
||||
<span>{daily.length > 0 && shortDay(daily[0].date)}</span>
|
||||
<span>{daily.length > 0 && shortDay(daily[daily.length - 1].date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<details className="details">
|
||||
<summary>Napi táblázat</summary>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nap</th>
|
||||
<th>Új tag</th>
|
||||
<th>Saját képlet</th>
|
||||
<th>Elemzés</th>
|
||||
<th>Kérdés</th>
|
||||
<th>Fizetés</th>
|
||||
<th>Bevétel</th>
|
||||
<th>Heti olvasó</th>
|
||||
<th>Fórum</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...daily].reverse().map((d) => (
|
||||
<tr key={d.date}>
|
||||
<td>{longDay(d.date)}</td>
|
||||
<td className="num">{d.signups}</td>
|
||||
<td className="num">{d.own_charts}</td>
|
||||
<td className="num">{d.analyses}</td>
|
||||
<td className="num">{d.questions}</td>
|
||||
<td className="num">{d.orders}</td>
|
||||
<td className="num">{d.revenue_huf ? huf(d.revenue_huf) : "–"}</td>
|
||||
<td className="num">{d.weekly_readers}</td>
|
||||
<td className="num">{d.forum_posts}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** A horizontal bar with its value at the end. */
|
||||
function Bar({ value, max, label }: { value: number; max: number; label: string }) {
|
||||
return (
|
||||
<span className="hbar">
|
||||
<span className="hbar-track">
|
||||
{value > 0 && <span className="hbar-fill" style={{ width: `${(value / max) * 100}%` }} />}
|
||||
</span>
|
||||
<span className="hbar-value">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Funnel({ data }: { data: Stats }) {
|
||||
const f = data.cohort.funnel;
|
||||
const steps: [string, number][] = [
|
||||
["Regisztrált", f.signups],
|
||||
["Megerősítette az e-mail-címét", f.verified],
|
||||
["Elkészítette a saját képletét", f.own_chart],
|
||||
["Elkezdte a fizetést", f.checkout],
|
||||
["Fizetett", f.bought],
|
||||
];
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Regisztrációtól a fizetésig</h2>
|
||||
<p className="hint">Az időszakban regisztráltak: ki meddig jutott el azóta.</p>
|
||||
</div>
|
||||
{f.signups === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem regisztrált senki.</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="funnel">
|
||||
{steps.map(([label, n], i) => (
|
||||
<li key={label}>
|
||||
<span>{label}</span>
|
||||
<Bar value={n} max={f.signups} label={i === 0 ? num(n) : `${num(n)} · ${pct(n, f.signups)}`} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="hint">
|
||||
Elemzést vagy kérdést kért (vásárolt vagy kapott egységgel): {num(f.ordered)} ({pct(f.ordered, f.signups)})
|
||||
· Heti horoszkópot olvasott: {num(f.weekly)} ({pct(f.weekly, f.signups)})
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Sources({ data }: { data: Stats }) {
|
||||
const c = data.cohort;
|
||||
const total = c.funnel.signups;
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Honnan jöttek</h2>
|
||||
<p className="hint">Az időszakban regisztráltak, az első látogatásuk szerint.</p>
|
||||
</div>
|
||||
{total === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem regisztrált senki.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table stats-sources">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Forrás</th>
|
||||
<th>Tag</th>
|
||||
<th>Saját képlet</th>
|
||||
<th>Fizetett</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{c.sources.map((s) => (
|
||||
<tr key={s.source}>
|
||||
<td>{SOURCE_LABELS[s.source] ?? s.source}</td>
|
||||
<td>
|
||||
<Bar value={s.signups} max={total} label={`${num(s.signups)} · ${pct(s.signups, total)}`} />
|
||||
</td>
|
||||
<td className="num">{num(s.own_chart)}</td>
|
||||
<td className="num">{num(s.bought)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="stats-split">
|
||||
<Shares
|
||||
title="Eszköz"
|
||||
rows={c.devices.map((d) => [DEVICE_LABELS[d.device] ?? d.device, d.signups])}
|
||||
total={total}
|
||||
/>
|
||||
<Shares
|
||||
title="Regisztráció módja"
|
||||
rows={c.methods.map((m) => [METHOD_LABELS[m.method] ?? m.method, m.signups])}
|
||||
total={total}
|
||||
/>
|
||||
</div>
|
||||
{c.details.length > 0 && (
|
||||
<div>
|
||||
<h3 className="stats-h3">Hivatkozó oldalak és kampányok</h3>
|
||||
<ul className="stats-list">
|
||||
{c.details.map((d) => (
|
||||
<li key={d.detail}>
|
||||
<code>{d.detail}</code>
|
||||
<span className="num">{num(d.signups)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<p className="hint">
|
||||
„Közvetlenül”: beírta a címet, könyvjelzőből vagy olyan alkalmazásból jött, amely nem mondja meg, honnan.
|
||||
„Nem ismert”: a mérés előtt regisztrált. A saját Facebook-bejegyzéseid linkjéhez tehetsz kampánycímkét
|
||||
(például <code>?utm_source=facebook&utm_campaign=heti</code>), az itt külön sorban látszik.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Shares({ title, rows, total }: { title: string; rows: [string, number][]; total: number }) {
|
||||
return (
|
||||
<div>
|
||||
<h3 className="stats-h3">{title}</h3>
|
||||
<ul className="stats-list">
|
||||
{rows.map(([label, n]) => (
|
||||
<li key={label}>
|
||||
<span>{label}</span>
|
||||
<span className="num">
|
||||
{num(n)} · {pct(n, total)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Packages({ data }: { data: Stats }) {
|
||||
const rows = data.packages;
|
||||
const total = rows.reduce((a, r) => a + r.revenue_huf, 0);
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Vásárlások csomagonként</h2>
|
||||
{rows.length === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem volt fizetés.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Csomag</th>
|
||||
<th>Darab</th>
|
||||
<th>Bevétel</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={`${r.package}-${r.gift}`}>
|
||||
<td>
|
||||
{r.name ?? r.package}
|
||||
{r.gift && <span className="hint"> (ajándékba)</span>}
|
||||
</td>
|
||||
<td className="num">{num(r.orders)}</td>
|
||||
<td className="num">{huf(r.revenue_huf)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th>Összesen</th>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.orders, 0))}</td>
|
||||
<td className="num">{huf(total)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Weekly({ data }: { data: Stats }) {
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Heti horoszkóp hetente</h2>
|
||||
<p className="hint">Hányan olvasták el (a szöveg az első megnyitáskor készül), és hány hétfői levél ment ki.</p>
|
||||
</div>
|
||||
{data.weekly.length === 0 ? (
|
||||
<p className="muted">Még senki nem olvasta.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Hét</th>
|
||||
<th>Olvasó</th>
|
||||
<th>Levél</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.weekly.map((w) => (
|
||||
<tr key={w.week_start}>
|
||||
<td>{weekRange(w.week_start, addDays(w.week_start, 6))}</td>
|
||||
<td className="num">{num(w.readers)}</td>
|
||||
<td className="num">{num(w.emails)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Content({ data }: { data: Stats }) {
|
||||
const rows = data.content;
|
||||
const cost = rows.reduce((a, r) => a + r.cost_usd, 0);
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Amit az AI írt</h2>
|
||||
<p className="hint">Mindenkié az időszakban, az adminoké is. A költséget az OpenRouter adja meg.</p>
|
||||
</div>
|
||||
{rows.length === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem készült szöveg.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fajta</th>
|
||||
<th>Elkészült</th>
|
||||
<th>Sikertelen</th>
|
||||
<th>Költség</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.kind}>
|
||||
<td>{CONTENT_LABELS[r.kind] ?? r.kind}</td>
|
||||
<td className="num">{num(r.done)}</td>
|
||||
<td className="num">{r.failed ? num(r.failed) : "–"}</td>
|
||||
<td className="num">{usd(r.cost_usd)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th>Összesen</th>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.done, 0))}</td>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.failed, 0))}</td>
|
||||
<td className="num">{usd(cost)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { AdminStats } from "./AdminStats";
|
||||
|
||||
export const metadata: Metadata = { title: "Statisztika" };
|
||||
|
||||
export default async function AdminStatsPage() {
|
||||
const me = await requireMe("/admin/statisztika");
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<AdminNav current="/admin/statisztika" />
|
||||
<div className="page-head">
|
||||
<h1>Statisztika</h1>
|
||||
<p className="muted">
|
||||
Regisztrációk, képletek, vásárlások és a heti horoszkóp olvasói, és hogy honnan jönnek a tagok.
|
||||
</p>
|
||||
</div>
|
||||
<AdminStats />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
/** The part of Sign in with Apple JS (appleid.auth.js) we use. */
|
||||
interface AppleSignInResponse {
|
||||
@@ -98,7 +99,13 @@ export function AppleLogin({
|
||||
const name = [response.user?.name?.lastName, response.user?.name?.firstName].filter(Boolean).join(" ") || null;
|
||||
try {
|
||||
await api("/auth/apple", {
|
||||
body: { id_token: response.authorization.id_token, name, invite_token: inviteToken, referral },
|
||||
body: {
|
||||
id_token: response.authorization.id_token,
|
||||
name,
|
||||
invite_token: inviteToken,
|
||||
referral,
|
||||
came_from: cameFrom(),
|
||||
},
|
||||
});
|
||||
router.replace(target);
|
||||
router.refresh();
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
|
||||
function GoogleMark() {
|
||||
@@ -74,7 +75,9 @@ export function GoogleLogin({
|
||||
setError(null);
|
||||
setUninvited(null);
|
||||
try {
|
||||
await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken, referral } });
|
||||
await api("/auth/google", {
|
||||
body: { id_token: response.credential, invite_token: inviteToken, referral, came_from: cameFrom() },
|
||||
});
|
||||
router.replace(target);
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useState } from "react";
|
||||
import { PasswordInput } from "@/components/PasswordInput";
|
||||
import { Turnstile } from "@/components/Turnstile";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
type Mode = "login" | "register" | "forgot";
|
||||
|
||||
@@ -79,6 +80,7 @@ export function PasswordLogin({
|
||||
invite_token: inviteToken,
|
||||
referral,
|
||||
turnstile_token: token,
|
||||
came_from: cameFrom(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -135,6 +135,8 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
for (const v of Array.isArray(value) ? value : [value]) query.append(key, v);
|
||||
}
|
||||
// The phone's browser learns from this which app the visitor came out of (lib/arrival.ts).
|
||||
if (inApp) query.set("forras", (inApp.app ?? "app").toLowerCase());
|
||||
const here = `${await siteUrl()}/belepes${query.size ? `?${query}` : ""}`;
|
||||
|
||||
const google =
|
||||
|
||||
@@ -6,14 +6,30 @@ import { notFound } from "next/navigation";
|
||||
import { ForumNav } from "@/components/forum/ForumNav";
|
||||
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||
import { FORUM_PREVIEW, FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
||||
|
||||
import "./forum.css";
|
||||
|
||||
const DESCRIPTION = "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
||||
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
|
||||
description: DESCRIPTION,
|
||||
openGraph: {
|
||||
type: "website",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
title: "Sorsfonalak fórum",
|
||||
description: DESCRIPTION,
|
||||
images: [FORUM_PREVIEW],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: "Sorsfonalak fórum",
|
||||
description: DESCRIPTION,
|
||||
images: [FORUM_PREVIEW.url],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
||||
|
||||
import { ThreadView } from "@/components/forum/ThreadView";
|
||||
import type { ThreadPage } from "@/lib/forum";
|
||||
import { FORUM_PREVIEW, type ThreadPage } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
type Props = { params: Promise<{ id: string }> };
|
||||
@@ -19,18 +19,42 @@ async function load(param: string) {
|
||||
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
||||
}
|
||||
|
||||
/** The start of a post for a description: one line, cut at a word, at most `max` characters. */
|
||||
function excerpt(text: string, max: number): string {
|
||||
const line = text.replace(/\s+/g, " ").trim();
|
||||
if (line.length <= max) return line;
|
||||
const cut = line.slice(0, max - 1);
|
||||
const words = cut.slice(0, Math.max(cut.lastIndexOf(" "), max / 2)).trimEnd();
|
||||
return `${words.replace(/[.,;:!?–-]+$/, "")}…`;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const res = await load((await params).id);
|
||||
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
||||
const { thread, posts } = res.data;
|
||||
const open = thread.topic.visibility === "public" && !thread.deleted;
|
||||
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
||||
const url = `/forum/szal/${thread.id}-${thread.slug}`;
|
||||
// The link preview: a public thread's title and opening words; of a
|
||||
// members-only or removed one nothing (link previews are public).
|
||||
const preview = open
|
||||
? { title: thread.title, description: excerpt(opening, 200) }
|
||||
: { title: "Sorsfonalak fórum", description: "Beszélgetés a Sorsfonalak fórumán." };
|
||||
return {
|
||||
title: thread.title,
|
||||
description: open ? opening.slice(0, 160) : undefined,
|
||||
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
|
||||
description: open ? excerpt(opening, 160) : undefined,
|
||||
alternates: { canonical: url },
|
||||
// Members-only topics and removed threads stay out of search engines.
|
||||
robots: open ? undefined : { index: false, follow: false },
|
||||
openGraph: {
|
||||
type: "article",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
url,
|
||||
...preview,
|
||||
images: [FORUM_PREVIEW],
|
||||
},
|
||||
twitter: { card: "summary_large_image", ...preview, images: [FORUM_PREVIEW.url] },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1879,3 +1879,55 @@ span.tarot-fan-card { cursor: default; }
|
||||
.mail-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||
.mail-set legend { font-family: var(--font-display); font-size: 20px; font-weight: 600; margin-bottom: 4px; }
|
||||
.mail-set label:not(.check) { font-size: 14px; color: var(--ink-2); margin-top: 6px; }
|
||||
.weekly-landing-lead { font-size: 17px; line-height: 1.6; max-width: 640px; }
|
||||
.weekly-landing-actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 6px; }
|
||||
.weekly-steps { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 10px; color: var(--ink-2); line-height: 1.55; }
|
||||
.weekly-steps strong { color: var(--ink); font-weight: 600; }
|
||||
|
||||
/* Admin → Statisztika: stat tiles, day-by-day small charts (one gold series
|
||||
each, the same days), horizontal bars with the value at the end. */
|
||||
.stats-filter { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
.stats-filter .hint { margin-left: 4px; }
|
||||
.stats-totals strong { color: var(--ink); font-weight: 600; }
|
||||
.stats-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; margin: 0; }
|
||||
.stats-tiles > div {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px;
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
}
|
||||
.stats-tiles dt { font-size: 13px; color: var(--muted); }
|
||||
.stats-tiles dd { margin: 0; }
|
||||
.stats-tile-value { font-size: 26px; font-weight: 600; line-height: 1.2; color: var(--ink); }
|
||||
.stats-tile-sub { font-size: 12px; color: var(--muted); }
|
||||
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr)); gap: 18px; align-items: start; }
|
||||
.stats-readout { font-size: 14px; color: var(--ink-2); min-height: 44px; }
|
||||
.stats-readout strong { color: var(--ink); font-weight: 600; }
|
||||
.stats-daily { display: flex; flex-direction: column; gap: 10px; touch-action: pan-y; }
|
||||
.spark { display: grid; grid-template-columns: 150px minmax(0, 1fr); gap: 12px; align-items: end; }
|
||||
.spark-head { display: flex; flex-direction: column; font-size: 13px; color: var(--muted); padding-bottom: 2px; }
|
||||
.spark-head strong { font-size: 18px; color: var(--ink); font-weight: 600; }
|
||||
.spark-plot { position: relative; height: 52px; border-bottom: 1px solid var(--line-2); }
|
||||
.spark-max { position: absolute; top: -2px; right: 0; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.spark-bars { display: flex; height: 100%; align-items: stretch; padding-top: 14px; }
|
||||
.spark-col { flex: 1 1 0; min-width: 0; display: flex; align-items: flex-end; justify-content: center; padding: 0 1px; cursor: default; }
|
||||
.spark-col.is-on { background: rgba(217, 180, 106, 0.1); }
|
||||
.spark-bar { display: block; width: 100%; max-width: 24px; background: var(--gold); border-radius: 4px 4px 0 0; }
|
||||
.spark-col.is-on .spark-bar { background: var(--gold-hover); }
|
||||
.spark-axis { display: flex; justify-content: space-between; margin-left: 162px; font-size: 12px; color: var(--muted); }
|
||||
.hbar { display: flex; align-items: center; gap: 8px; min-width: 120px; }
|
||||
.hbar-track { flex: 1 1 auto; height: 12px; display: flex; }
|
||||
.hbar-fill { display: block; height: 100%; background: var(--gold); border-radius: 0 4px 4px 0; }
|
||||
.hbar-value { font-size: 13px; color: var(--ink-2); white-space: nowrap; font-variant-numeric: tabular-nums; min-width: 64px; }
|
||||
.funnel { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.funnel li { display: grid; grid-template-columns: minmax(0, 210px) minmax(0, 1fr); gap: 12px; align-items: center; font-size: 14px; }
|
||||
.stats-sources td { vertical-align: middle; }
|
||||
.stats-split { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; }
|
||||
.stats-h3 { font-family: var(--font-body); font-size: 14px; font-weight: 600; color: var(--ink-2); margin-bottom: 6px; }
|
||||
.stats-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 14px; }
|
||||
.stats-list li { display: flex; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--line); padding: 4px 0; }
|
||||
.stats-list code { overflow-wrap: anywhere; }
|
||||
@media (max-width: 620px) {
|
||||
.spark { grid-template-columns: minmax(0, 1fr); gap: 4px; }
|
||||
.spark-head { flex-direction: row; justify-content: space-between; align-items: baseline; }
|
||||
.spark-axis { margin-left: 0; }
|
||||
.funnel li { grid-template-columns: minmax(0, 1fr); gap: 4px; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { Paragraphs } from "@/components/Rich";
|
||||
import example from "@/content/pelda-heti.json";
|
||||
import { weekRange } from "@/lib/weekly";
|
||||
|
||||
const LOGIN = "/belepes?vissza=/heti-horoszkop";
|
||||
|
||||
/**
|
||||
* The weekly horoscope for visitors: what it is, a real example written for
|
||||
* the example chart (the one of the Példaelemzés page), and the way in.
|
||||
*/
|
||||
export function WeeklyLanding() {
|
||||
return (
|
||||
<main className="page weekly-landing" style={{ maxWidth: 820 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Ingyenes · hétfőnként új</span>
|
||||
<h1>Heti horoszkóp, ami rólad szól</h1>
|
||||
<p className="muted weekly-landing-lead">
|
||||
Nem a csillagjegyedre írt általános szöveg: a hét égboltját a saját születési képletedre vetítjük. Melyik
|
||||
bolygó milyen fényszöget alkot a te pontjaiddal, melyik napon, és mit kérhet tőled a héten.
|
||||
</p>
|
||||
<div className="weekly-landing-actions">
|
||||
<Link href={LOGIN} className="btn btn-primary lp-btn">
|
||||
Belépés
|
||||
</Link>
|
||||
<Link href={`/belepes?mod=regisztracio&vissza=/heti-horoszkop`} className="btn lp-btn">
|
||||
Regisztráció
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<article className="card summary-card weekly-card" aria-labelledby="weekly-example-title">
|
||||
<span className="eyebrow">Példa · {weekRange(example.week_start, example.week_end)}</span>
|
||||
<h2 id="weekly-example-title" className="summary-title">
|
||||
{example.title}
|
||||
</h2>
|
||||
<div className="summary-text weekly-text" lang="hu">
|
||||
<Paragraphs text={example.text} />
|
||||
</div>
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Ezt a heti horoszkópot a <Link href="/pelda">példaelemzés</Link> kitalált képletéhez írtuk (1990. március 15.,
|
||||
14:30, Szeged), ugyanúgy, ahogy a tiédet is megírjuk.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<section className="card field weekly-how" aria-labelledby="weekly-how-title" style={{ gap: 12 }}>
|
||||
<h2 id="weekly-how-title">Hogyan működik?</h2>
|
||||
<ol className="weekly-steps">
|
||||
<li>
|
||||
<strong>Megadod, mikor és hol születtél.</strong> Ebből percre pontosan kiszámoljuk a születési képletedet.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Hétfőnként új heti horoszkópot kapsz,</strong> a te képletedből és a hét égboltjából: a hét fő
|
||||
témája, a kulcsnapok és egy javaslat.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Hétfő reggel e-mailben szólunk,</strong> hogy itt az új. Ha nem kéred, egy kattintással
|
||||
kikapcsolhatod.
|
||||
</li>
|
||||
</ol>
|
||||
<div>
|
||||
<Link href={LOGIN} className="btn btn-primary">
|
||||
Belépés, és kérem a heti horoszkópomat
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { MONTHS, WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||
import { WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
import { MONTHS } from "@/lib/weekly";
|
||||
|
||||
const POLL_MS = 3000;
|
||||
const MAX_POLLS = 60;
|
||||
@@ -34,8 +35,9 @@ function monthName(key: string): string {
|
||||
|
||||
/**
|
||||
* One month of weekly horoscopes, the newest week first. In this month the
|
||||
* week's horoscope is asked for first (queued if new), and polled until the
|
||||
* worker has written it; meanwhile its card shows the waiting animation.
|
||||
* week's horoscope is asked for first (queued if new), then read until the
|
||||
* worker has written it (or given up); meanwhile its card shows the waiting
|
||||
* animation.
|
||||
*/
|
||||
export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: boolean }) {
|
||||
const [data, setData] = useState<Month | null>(null);
|
||||
@@ -52,25 +54,45 @@ export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin:
|
||||
useEffect(() => {
|
||||
let stopped = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let polls = 0;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const week = await api<Week & { email: boolean }>("/weekly", { method: "POST" });
|
||||
if (stopped) return;
|
||||
putWeek({ week_start: week.week_start, week_end: week.week_end, analysis: week.analysis });
|
||||
if (week.analysis.status === "done") return;
|
||||
} catch {
|
||||
// try again on the next tick
|
||||
const wait = () => new Promise((resolve) => (timer = setTimeout(resolve, POLL_MS)));
|
||||
/**
|
||||
* This week's text: asked for once (queued if new, or written again if
|
||||
* the last attempt failed), then only read until the worker is done.
|
||||
*/
|
||||
const follow = async () => {
|
||||
let week: Week | null = null;
|
||||
for (let tries = 0; !week && tries < 5 && !stopped; tries++) {
|
||||
try {
|
||||
const got = await api<Week & { email: boolean }>("/weekly", { method: "POST" });
|
||||
week = { week_start: got.week_start, week_end: got.week_end, analysis: got.analysis };
|
||||
} catch {
|
||||
await wait();
|
||||
}
|
||||
}
|
||||
if (!week || stopped) return setGaveUp(!stopped);
|
||||
putWeek(week);
|
||||
for (let polls = 0; !stopped; polls++) {
|
||||
const { status } = week.analysis;
|
||||
if (status === "done" || status === "failed") return;
|
||||
if (polls >= MAX_POLLS) return setGaveUp(true);
|
||||
await wait();
|
||||
try {
|
||||
const id: string = week.analysis.id;
|
||||
const analysis: Analysis = await api<Analysis>(`/analyses/${id}`);
|
||||
if (stopped) return;
|
||||
week = { ...week, analysis };
|
||||
putWeek(week);
|
||||
} catch {
|
||||
// try again on the next tick
|
||||
}
|
||||
}
|
||||
if (++polls >= MAX_POLLS) return setGaveUp(true);
|
||||
timer = setTimeout(poll, POLL_MS);
|
||||
};
|
||||
(async () => {
|
||||
try {
|
||||
const page = await api<Month>(`/weekly/history${query}`);
|
||||
if (stopped) return;
|
||||
setData(page);
|
||||
if (page.month === page.current_month) await poll();
|
||||
if (page.month === page.current_month) await follow();
|
||||
} catch (e) {
|
||||
if (!stopped) setError(errorText(e));
|
||||
}
|
||||
|
||||
@@ -1,22 +1,58 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { requireMe } from "@/lib/server";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { getMe } from "@/lib/server";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
|
||||
import { WeeklyLanding } from "./Landing";
|
||||
import { WeeklyPage } from "./WeeklyPage";
|
||||
|
||||
export const metadata: Metadata = { title: "Heti horoszkóp" };
|
||||
/** Bumped when the preview image changes, so Facebook and co. fetch it again. */
|
||||
const PREVIEW_VERSION = 1;
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const base = await siteUrl();
|
||||
const title = "Heti horoszkóp, ami rólad szól";
|
||||
const description =
|
||||
"Ingyenes, hétfőnként új személyes heti horoszkóp a saját születési képletedből és a hét égboltjából: a hét fő témája, a kulcsnapok és egy javaslat.";
|
||||
const image = { url: `${base}/kep/heti-horoszkop.png?v=${PREVIEW_VERSION}`, width: 1200, height: 630, alt: title };
|
||||
return {
|
||||
title: "Heti horoszkóp",
|
||||
description,
|
||||
alternates: { canonical: `${base}/heti-horoszkop` },
|
||||
openGraph: {
|
||||
type: "website",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
url: `${base}/heti-horoszkop`,
|
||||
title,
|
||||
description,
|
||||
images: [image],
|
||||
},
|
||||
twitter: { card: "summary_large_image", title, description, images: [image.url] },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The member's weekly horoscopes, one month at a time, the newest first
|
||||
* (`?honap=2026-11` pages back). This week's is written when the page opens.
|
||||
* The weekly horoscope. Members: their own, one month at a time, the newest
|
||||
* first (`?honap=2026-11` pages back); this week's is written when the page
|
||||
* opens. Visitors: what it is, with an example, and the way in.
|
||||
*/
|
||||
export default async function WeeklyHoroscopePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[]>>;
|
||||
}) {
|
||||
const me = await requireMe("/heti-horoszkop");
|
||||
const me = await getMe();
|
||||
if (!me) {
|
||||
return (
|
||||
<>
|
||||
<PublicHeader />
|
||||
<WeeklyLanding />
|
||||
</>
|
||||
);
|
||||
}
|
||||
const raw = (await searchParams).honap;
|
||||
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// The link preview image of the forum's pages (og:image), drawn from the
|
||||
// example chart. The pages link it with a version (?v=…).
|
||||
import example from "@/content/pelda.json";
|
||||
import { chartCard } from "@/lib/ogCard";
|
||||
import type { ChartResult } from "@/lib/types";
|
||||
|
||||
export async function GET() {
|
||||
return chartCard({
|
||||
chart: example.chart as unknown as ChartResult,
|
||||
timeKnown: true,
|
||||
eyebrow: "SORSFONALAK FÓRUM",
|
||||
title: "Ahol meghallgatnak.",
|
||||
text: "Beszélgetés, meghallgatás, asztrológia és álmok: egy nyugodt, figyelmes közösség.",
|
||||
lines: [
|
||||
{ glyph: "☽", label: "Meghallgatás" },
|
||||
{ glyph: "☿", label: "Beszélgetés" },
|
||||
{ glyph: "♀", label: "Asztrológia" },
|
||||
],
|
||||
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// The link preview image of the weekly horoscope page (og:image), drawn from
|
||||
// the example chart. The page links it with a version (?v=…).
|
||||
import example from "@/content/pelda.json";
|
||||
import { chartCard } from "@/lib/ogCard";
|
||||
import type { ChartResult } from "@/lib/types";
|
||||
|
||||
export async function GET() {
|
||||
return chartCard({
|
||||
chart: example.chart as unknown as ChartResult,
|
||||
timeKnown: true,
|
||||
eyebrow: "HETI HOROSZKÓP",
|
||||
title: "A te heted, nem a csillagjegyedé.",
|
||||
text: "Hétfőnként új, személyes horoszkóp a saját születési képletedből és a hét égboltjából. Ingyenes.",
|
||||
lines: [
|
||||
{ glyph: "☉", label: "A saját képletedből" },
|
||||
{ glyph: "☽", label: "A hét égboltjából" },
|
||||
{ glyph: "☿", label: "Hétfőnként új" },
|
||||
],
|
||||
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
|
||||
import { Cormorant_Garamond, Inter } from "next/font/google";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { Arrival } from "@/components/Arrival";
|
||||
import { DialogHost } from "@/components/Dialogs";
|
||||
import { KeyboardSafe } from "@/components/KeyboardSafe";
|
||||
import { NightSky } from "@/components/NightSky";
|
||||
@@ -45,6 +46,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
|
||||
<body>
|
||||
<NightSky />
|
||||
<Arrival />
|
||||
<KeyboardSafe />
|
||||
<VersionWatcher />
|
||||
<DialogHost />
|
||||
|
||||
@@ -129,6 +129,11 @@ const DATA: [string, string, string][] = [
|
||||
"The free weekly horoscope; a short e-mail on Mondays that the new one is there (sent by default; turn it off at any time in the e-mail's footer, on the Weekly horoscope page or on your Profile page)",
|
||||
"Performance of the contract; for the e-mail, legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"At sign-up: where you came to the site from (for example Facebook or a Google search, another site's address without its path, or the link's campaign tag), and whether from a phone, a tablet or a computer",
|
||||
"Statistics: seeing where members come from, and which of our posts or ads work",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"Which page you opened, where you came from, your browser and device type, your country and how long the page took to load (visitor statistics)",
|
||||
"Seeing how many people view each page and whether the site is fast enough",
|
||||
@@ -390,6 +395,12 @@ export default async function PrivacyPolicyPage() {
|
||||
When a page loads, a small script sends which page you opened, where you came from, your browser and device
|
||||
type, and how long the page took to load. We only see totals and cannot follow individual visitors.
|
||||
</p>
|
||||
<p>
|
||||
If you sign up, we save with your account where you came to the site from and from what kind of device. No
|
||||
cookie and nothing stored in the browser is used for this: the page only remembers it in its own memory
|
||||
during that visit and sends it with the sign-up. Nothing like this is stored about visitors who do not sign
|
||||
up.
|
||||
</p>
|
||||
<p>
|
||||
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
||||
calculation and are not stored on our server. So that they are not lost when you move between pages, they
|
||||
|
||||
@@ -16,6 +16,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
return [
|
||||
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
|
||||
{ url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 },
|
||||
{ url: `${base}/heti-horoszkop`, changeFrequency: "weekly", priority: 0.8 },
|
||||
{ url: `${base}/kartyajoslas/pelda`, changeFrequency: "monthly", priority: 0.7 },
|
||||
{ url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 },
|
||||
{ url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 },
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { Role } from "@/lib/types";
|
||||
import { FeedbackCount } from "./FeedbackCount";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/admin/statisztika", label: "Statisztika" },
|
||||
{ href: "/admin", label: "Felhasználók" },
|
||||
{ href: "/admin/meghivok", label: "Meghívók" },
|
||||
{ href: "/admin/promokodok", label: "Promókódok" },
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { rememberArrival } from "@/lib/arrival";
|
||||
|
||||
// Right when the site's code loads in the browser, before any navigation
|
||||
// inside the site changes the address.
|
||||
rememberArrival();
|
||||
|
||||
/** Notes where the visit began (see lib/arrival.ts); draws nothing. */
|
||||
export function Arrival() {
|
||||
return null;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
import { weekRange } from "@/lib/weekly";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { RateContent } from "./RateContent";
|
||||
@@ -11,28 +12,6 @@ import { RegenerateButton } from "./RegenerateButton";
|
||||
import { RetryNotice } from "./RetryNotice";
|
||||
import { Paragraphs } from "./Rich";
|
||||
|
||||
export const MONTHS = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
|
||||
/** "november 30. – december 6." or "december 7–13.". */
|
||||
export function weekRange(start: string, end: string): string {
|
||||
const [, m1, d1] = start.split("-").map(Number);
|
||||
const [, m2, d2] = end.split("-").map(Number);
|
||||
return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Monday's e-mail about the weekly horoscope, on or off. Turned on, the first
|
||||
* one comes next Monday.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"week_start": "2026-11-30",
|
||||
"week_end": "2026-12-06",
|
||||
"title": "Gondolatok, amelyek összeérnek",
|
||||
"text": "A héten a gondolkodásod és a szíved egymásra hangolódnak. A legtisztább üzenetet a Merkúr hozza: a trigonja a születési Merkúrod felett hétfőn pontos, ez a világos fejtartás napja. A Nap a Nyilas jegyében a születési Vénuszodra szextilt vet, a Merkúr pedig a Szaturnuszoddal is harmonizál. A háttérben a Plútó lassan dolgozik a születési Marsod közelében: mély, kitartó átalakulás, nem hirtelen fordulat.\n\nHétfőn a Mars szextilje a születési Jupiteroddal is kedvező, a Mars az 1. házban jár, így a kezdeményezőkedved most erős. Kedden csúcsnap jön: a Nap szextilje a Vénuszoddal és a Merkúr szextilje a Szaturnusszal a hét legtisztább harmóniája, miközben az utolsó negyedben álló Hold a Szűz jegyében, az 1. házban a dolgok lecsupaszítására hív. Szerdán a Merkúr trigonja a Napoddal megerősíti, hogy a szavaid mögött valódi meggyőződés áll. Pénteken a Vénusz Skorpióba lép a 3. házban, szombaton a Hold is követi, így a hét vége befelé forduló, mélyebb hangulatú. Vasárnap a Vénusz trigonja a Jupiterrel bőséges, nagylelkű zárást ad.\n\nJavaslat: kedden írd le azt a kérést vagy elhatározást, amit eddig halogattál, mert a Merkúr és a Szaturnusz összhangja most kitartást ad a szavaidnak. A hét végén engedj teret a csendnek a Hold skorpiós hullámzásában, és vasárnap, a Vénusz–Jupiter trigon jegyében, merj örülni annak, ami már a tiéd."
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Where this visit began, for the admin statistics of a new member: the
|
||||
* referring site's address (without its path), the link's campaign tags and
|
||||
* click id, and the app the visitor came out of (the login page's way out of
|
||||
* Facebook's browser adds `?forras=`). Read once, when the site first loads
|
||||
* in the tab, and kept in the page's memory only: nothing is stored in the
|
||||
* browser, and it is only sent with a sign-up on the same visit.
|
||||
*/
|
||||
export interface CameFrom {
|
||||
referrer: string | null;
|
||||
utm_source: string | null;
|
||||
utm_medium: string | null;
|
||||
utm_campaign: string | null;
|
||||
click: string | null;
|
||||
app: string | null;
|
||||
}
|
||||
|
||||
let arrival: CameFrom | null = null;
|
||||
|
||||
/** Called as the site first loads (components/Arrival.tsx). */
|
||||
export function rememberArrival(): void {
|
||||
if (arrival || typeof window === "undefined") return;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const tag = (name: string) => params.get(name)?.trim().slice(0, 60) || null;
|
||||
let referrer: string | null = null;
|
||||
try {
|
||||
referrer = document.referrer ? new URL(document.referrer).hostname || null : null;
|
||||
} catch {
|
||||
referrer = null;
|
||||
}
|
||||
arrival = {
|
||||
referrer,
|
||||
utm_source: tag("utm_source"),
|
||||
utm_medium: tag("utm_medium"),
|
||||
utm_campaign: tag("utm_campaign"),
|
||||
click: ["fbclid", "gclid", "ttclid"].find((id) => params.has(id)) ?? null,
|
||||
app: tag("forras"),
|
||||
};
|
||||
}
|
||||
|
||||
/** What to send with a sign-up (null when the site did not record it). */
|
||||
export function cameFrom(): CameFrom | null {
|
||||
return arrival;
|
||||
}
|
||||
@@ -280,6 +280,9 @@ export const INTENTS = {
|
||||
} as const;
|
||||
|
||||
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||
/** The forum's link preview image (Facebook and co.); a thread adds its own title and text. */
|
||||
export const FORUM_PREVIEW = { url: "/kep/forum.png?v=1", width: 1200, height: 630, alt: "A Sorsfonalak fóruma" };
|
||||
|
||||
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||
return postId ? `${path}#h${postId}` : path;
|
||||
|
||||
@@ -887,3 +887,68 @@ export interface FeedbackSummary {
|
||||
comments: { score: number; comment: string; created_at: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
/** The headline numbers of a period on Admin → Statisztika. */
|
||||
export interface StatsPeriod {
|
||||
signups: number;
|
||||
own_charts: number;
|
||||
analyses: number;
|
||||
questions: number;
|
||||
orders: number;
|
||||
buyers: number;
|
||||
revenue_huf: number;
|
||||
refunded_huf: number;
|
||||
weekly_readers: number;
|
||||
forum_posts: number;
|
||||
ai_cost_usd: number;
|
||||
}
|
||||
|
||||
export interface StatsDay {
|
||||
date: string;
|
||||
signups: number;
|
||||
own_charts: number;
|
||||
analyses: number;
|
||||
questions: number;
|
||||
orders: number;
|
||||
revenue_huf: number;
|
||||
weekly_readers: number;
|
||||
forum_posts: number;
|
||||
}
|
||||
|
||||
/** Admin → Statisztika (`GET /v1/admin/stats?days=`). */
|
||||
export interface AdminStats {
|
||||
days: number;
|
||||
from: string;
|
||||
to: string;
|
||||
totals: {
|
||||
members: number;
|
||||
own_charts: number;
|
||||
buyers: number;
|
||||
revenue_huf: number;
|
||||
weekly_subscribers: number;
|
||||
forum_members: number;
|
||||
};
|
||||
period: StatsPeriod;
|
||||
/** The same length of time before the period (null for "since the start"). */
|
||||
previous: StatsPeriod | null;
|
||||
daily: StatsDay[];
|
||||
/** The members who signed up in the period. */
|
||||
cohort: {
|
||||
funnel: {
|
||||
signups: number;
|
||||
verified: number;
|
||||
own_chart: number;
|
||||
ordered: number;
|
||||
checkout: number;
|
||||
bought: number;
|
||||
weekly: number;
|
||||
};
|
||||
sources: { source: string; signups: number; own_chart: number; bought: number }[];
|
||||
details: { detail: string; signups: number }[];
|
||||
devices: { device: string; signups: number }[];
|
||||
methods: { method: string; signups: number }[];
|
||||
};
|
||||
packages: { package: string; name: string | null; gift: boolean; orders: number; revenue_huf: number }[];
|
||||
content: { kind: string; done: number; failed: number; cost_usd: number }[];
|
||||
weekly: { week_start: string; readers: number; emails: number }[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/** Dates of the weekly horoscope (shared by the server and the browser). */
|
||||
|
||||
export const MONTHS = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
|
||||
/** "november 30. – december 6." or "december 7–13.". */
|
||||
export function weekRange(start: string, end: string): string {
|
||||
const [, m1, d1] = start.split("-").map(Number);
|
||||
const [, m2, d2] = end.split("-").map(Number);
|
||||
return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`;
|
||||
}
|
||||
@@ -341,6 +341,11 @@ async fn one_week_of_a_chart() {
|
||||
assert_eq!(status, StatusCode::OK, "{u}");
|
||||
assert!(u["week"]["positions"][0]["house"].is_null());
|
||||
|
||||
// The week the clocks go back (Sunday 25 October): still Monday to Sunday.
|
||||
let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-10-19"}))).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
assert_eq!((d["week"]["start"].as_str(), d["week"]["end"].as_str()), (Some("2026-10-19"), Some("2026-10-25")));
|
||||
|
||||
// Not a Monday.
|
||||
let (status, _) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-12-01"}))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
|
||||
@@ -57,7 +57,10 @@ pub fn calculate(state: &AppState, req: WeekRequest) -> Result<WeekResponse, Api
|
||||
let (start_jd, offset) = jd_at(start)?;
|
||||
let next = start.checked_add(jiff::Span::new().days(7)).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
let (end_jd, _) = jd_at(next)?;
|
||||
let week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
|
||||
let mut week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
|
||||
.map_err(|e| ApiError::Calculation(e.to_string()))?;
|
||||
// The last day from the calendar: the offset at the start would be an hour
|
||||
// off in the week the clocks go back.
|
||||
week.end = start.checked_add(jiff::Span::new().days(6)).map_err(|e| ApiError::Internal(e.to_string()))?.to_string();
|
||||
Ok(WeekResponse { timezone: zone_name, week })
|
||||
}
|
||||
|
||||
@@ -65,7 +65,12 @@ pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result<usi
|
||||
for m in due {
|
||||
let threads: Vec<(String, i64)> = sqlx::query_as(
|
||||
"SELECT th.title, count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \
|
||||
JOIN forum.topics tp ON tp.id = th.topic_id \
|
||||
WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \
|
||||
AND (tp.visibility <> 'restricted' \
|
||||
OR EXISTS (SELECT 1 FROM forum.topic_members tm \
|
||||
WHERE tm.topic_id = tp.id AND tm.user_id = $1 AND tm.status = 'approved') \
|
||||
OR EXISTS (SELECT 1 FROM users mu WHERE mu.id = $1 AND mu.roles && ARRAY['moderator', 'admin'])) \
|
||||
AND p.created_at > $2 \
|
||||
AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \
|
||||
WHERE r.user_id = $1 AND r.thread_id = th.id), 0) \
|
||||
@@ -382,6 +387,50 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_closed_topic_only_for_its_members(pool: PgPool) {
|
||||
let anna = member(&pool, "anna@example.com", "Anna", "off", "daily").await;
|
||||
let bea = member(&pool, "bea@example.com", "Bea", "off", "daily").await;
|
||||
let cili = member(&pool, "cili@example.com", "Cili", "off", "off").await;
|
||||
let topic: i16 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.topics (id, slug, name, description, visibility, position) \
|
||||
VALUES (90, 'zart-kor', 'Zárt kör', 'Próba', 'restricted', 90) RETURNING id",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// Anna is still in; Bea followed the thread while she was, and has left since.
|
||||
sqlx::query("INSERT INTO forum.topic_members (topic_id, user_id, status) VALUES ($1, $2, 'approved')")
|
||||
.bind(topic)
|
||||
.bind(anna)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let thread: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES ($1, $2, 'Titkos cím') RETURNING id",
|
||||
)
|
||||
.bind(topic)
|
||||
.bind(cili)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2), ($3, $2)")
|
||||
.bind(anna)
|
||||
.bind(thread)
|
||||
.bind(bea)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
post(&pool, thread, cili, None).await;
|
||||
|
||||
assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 1);
|
||||
let to: Vec<String> = sqlx::query_scalar("SELECT to_email FROM email_outbox WHERE template = 'forum_digest'")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(to, ["anna@example.com"], "the title stays inside the closed topic");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user