Share rewards: a question for a visit, an analysis for a new user
CI / test (push) Successful in 1m33s
CI / build (push) Successful in 6m18s
CI / deploy (push) Skipped

A click proves little, so the first visit of a shared link now earns a
question (once per user) instead of a natal analysis. A natal analysis is
earned by bringing a new user: the share page remembers the link, the
Google sign-up sends it, and when that user makes their own chart the
sharer gets one, at most three (referrals table, referral_reward). This is
off until sign-up opens (REFERRAL_REWARDS, default false). The share button
and its small print follow; /v1/me tells what was earned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-19 11:24:49 +00:00
co-authored by Claude Opus 5.5
parent 8e1205359d
commit 0e3eaee735
16 changed files with 265 additions and 29 deletions
+4 -1
View File
@@ -34,6 +34,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
let package = crate::packages::current(&mut conn, auth.id()).await?;
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
let referrals = super::shares::referral_rewards(&mut conn, auth.id()).await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
@@ -42,8 +43,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
"birth_change": birth_change,
"persons": persons.view(),
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
// The free analysis for a shared link is used up (once per user).
// The free question for a shared link is used up (once per user).
"share_reward_granted": share_reward,
// Natal analyses earned by bringing new users, and how many can be.
"referral_rewards": { "earned": referrals, "limit": super::shares::REFERRAL_LIMIT },
})))
}
+7
View File
@@ -170,6 +170,8 @@ pub struct RegisterRequest {
locale: Option<String>,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
/// The slug of the shared link the visitor came from.
referral: Option<String>,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
@@ -224,6 +226,7 @@ pub async fn register(
state.config.free_person_slots,
)
.await?;
super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref()).await?;
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
queue_verification(&state, &mut tx, &user).await?;
@@ -291,6 +294,8 @@ pub struct GoogleRequest {
id_token: String,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
/// The slug of the shared link the visitor came from.
referral: Option<String>,
}
/// Logs in with Google. An unknown Google account is linked to the existing
@@ -362,6 +367,8 @@ pub async fn google(
state.config.free_person_slots,
)
.await?;
super::shares::record_referral(&mut tx, state.config.referral_rewards, id, req.referral.as_deref())
.await?;
(id, true)
}
};
+4
View File
@@ -184,6 +184,7 @@ pub async fn create(
birth_changes::record(&mut tx, &auth, row.id).await?;
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
super::shares::reward_referral(&state, auth.id()).await?;
return Ok((StatusCode::OK, Json(row.owner_view())));
}
queue_summary(&state, &auth, &chart).await;
@@ -231,6 +232,9 @@ pub async fn create(
}
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
if row.is_primary {
super::shares::reward_referral(&state, auth.id()).await?;
}
Ok((StatusCode::CREATED, Json(row.owner_view())))
}
+1
View File
@@ -163,6 +163,7 @@ async fn public_config(State(state): St) -> Json<Value> {
"password_login": c.password_login,
"mock_payments": c.mock_payments,
"user_invites": c.user_invites,
"referral_rewards": c.referral_rewards,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
+71 -3
View File
@@ -9,8 +9,10 @@
//! share page reports a visit from the visitor's browser
//! (`POST /v1/public/shares/{slug}/visit`): it is counted unless it comes
//! from a robot or from the sharer (logged in, or from the address the link
//! was made at). The sharer's first such visit earns one free natal analysis,
//! once per user.
//! was made at). The sharer's first such visit earns one free question, once
//! per user: a click proves little. A natal analysis is earned by bringing a
//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
use axum::Json;
use axum::extract::{Path, State};
@@ -332,7 +334,7 @@ pub async fn visit(
sqlx::query("UPDATE shares SET view_count = view_count + 1 WHERE id = $1").bind(share.id).execute(&mut *tx).await?;
let rewarded = sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
VALUES ($1, $2, 'natal', 1, 'share_reward', $3) ON CONFLICT DO NOTHING",
VALUES ($1, $2, 'question', 1, 'share_reward', $3) ON CONFLICT DO NOTHING",
)
.bind(Uuid::now_v7())
.bind(share.owner_id)
@@ -348,6 +350,72 @@ pub async fn visit(
Ok(Json(json!({ "counted": true })))
}
/// Natal analyses a user can earn by bringing new users through shared links.
pub const REFERRAL_LIMIT: i64 = 3;
/// A new user came from a shared link (`slug`): remembered for the reward,
/// unless rewards are off, the link is unknown or revoked, or it is their own.
pub(super) async fn record_referral(
conn: &mut sqlx::PgConnection,
enabled: bool,
user_id: Uuid,
slug: Option<&str>,
) -> Result<(), sqlx::Error> {
let Some(slug) = slug.map(str::trim).filter(|s| enabled && !s.is_empty()) else {
return Ok(());
};
sqlx::query(
"INSERT INTO referrals (user_id, referrer_id, share_id) \
SELECT $1, owner_id, id FROM shares WHERE slug = $2 AND revoked_at IS NULL AND owner_id <> $1 \
ON CONFLICT DO NOTHING",
)
.bind(user_id)
.bind(slug)
.execute(conn)
.await?;
Ok(())
}
/// The new user made their own chart: the sharer who brought them gets a
/// natal analysis, while under the limit. Runs once per new user.
pub(super) async fn reward_referral(state: &crate::AppState, user_id: Uuid) -> Result<(), ApiError> {
if !state.config.referral_rewards {
return Ok(());
}
let mut tx = state.db.begin().await?;
let referrer: Option<Uuid> =
sqlx::query_scalar("SELECT referrer_id FROM referrals WHERE user_id = $1 AND rewarded_at IS NULL FOR UPDATE")
.bind(user_id)
.fetch_optional(&mut *tx)
.await?;
let Some(referrer) = referrer else { return Ok(()) };
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(referrer).execute(&mut *tx).await?;
let earned = referral_rewards(&mut tx, referrer).await?;
if earned < REFERRAL_LIMIT {
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \
VALUES ($1, $2, 'natal', 1, 'referral_reward', $3)",
)
.bind(Uuid::now_v7())
.bind(referrer)
.bind(format!("new user {user_id} from a shared link"))
.execute(&mut *tx)
.await?;
tracing::info!(referrer = %referrer, user = %user_id, "referral reward granted");
}
sqlx::query("UPDATE referrals SET rewarded_at = now() WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
tx.commit().await?;
Ok(())
}
/// Natal analyses the user has earned by bringing new users.
pub async fn referral_rewards(conn: &mut sqlx::PgConnection, user_id: Uuid) -> Result<i64, sqlx::Error> {
sqlx::query_scalar("SELECT count(*) FROM credit_ledger WHERE user_id = $1 AND reason = 'referral_reward'")
.bind(user_id)
.fetch_one(conn)
.await
}
/// Whether the user has already received the reward for sharing.
pub async fn reward_granted(db: &PgPool, user_id: Uuid) -> Result<bool, sqlx::Error> {
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM credit_ledger WHERE user_id = $1 AND reason = 'share_reward')")