Inviting a person to compare charts
The new person page offers 'Adatok megadása' (typed-in data, uses a slot) or 'Meghívom': a 'how compatible are we?' link with an optional name, e-mail and message (no links, 300 chars), shareable by copy, the phone's share menu, WhatsApp or Facebook. With an address we e-mail it too (at most 10 a day per user, opted-out addresses skipped, unsubscribe link included). The invitee lands on /meghivas/<token>, signs in, gives their own birth data if needed and gets the comparison; the inviter is told and lists pending invitations (revocable) on the persons page. No person slot is used. Also: the accepted e-mail links to /osszevetesek/<id>, and the cross grid no longer breaks on another user's chart (no highlights there). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -127,7 +127,7 @@ async fn gift_of(conn: &mut PgConnection, invitation_id: Uuid) -> Result<Option<
|
||||
|
||||
// --- sending ---------------------------------------------------------------------------------
|
||||
|
||||
fn clean_message(message: Option<String>) -> Result<Option<String>, ApiError> {
|
||||
pub(super) fn clean_message(message: Option<String>) -> Result<Option<String>, ApiError> {
|
||||
let Some(message) = message.map(|m| m.replace("\r\n", "\n").trim().to_owned()).filter(|m| !m.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -142,7 +142,7 @@ fn clean_message(message: Option<String>) -> Result<Option<String>, ApiError> {
|
||||
Ok(Some(message))
|
||||
}
|
||||
|
||||
fn links(state: &AppState, token: &str) -> (String, String, String) {
|
||||
pub(super) fn links(state: &AppState, token: &str) -> (String, String, String) {
|
||||
let base = &state.config.public_base_url;
|
||||
(
|
||||
format!("{base}/meghivo/{token}"),
|
||||
@@ -199,7 +199,7 @@ async fn send(
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
async fn opted_out(conn: &mut PgConnection, email: &str) -> Result<bool, ApiError> {
|
||||
pub(super) async fn opted_out(conn: &mut PgConnection, email: &str) -> Result<bool, ApiError> {
|
||||
Ok(sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM email_optouts WHERE email_hash = $1)")
|
||||
.bind(db::token_hash(email))
|
||||
.fetch_one(conn)
|
||||
@@ -587,8 +587,11 @@ pub async fn unsubscribe(
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let mut tx = state.db.begin().await?;
|
||||
// The link of a site invitation, or of a "how compatible are we?" one a user had us e-mail.
|
||||
let email: Option<String> = sqlx::query_scalar(
|
||||
"SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1",
|
||||
"SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1 \
|
||||
UNION ALL SELECT invitee_email FROM synastry_invites WHERE token_hash = $1 AND invitee_email IS NOT NULL \
|
||||
LIMIT 1",
|
||||
)
|
||||
.bind(db::token_hash(q.token.trim()))
|
||||
.fetch_optional(&mut *tx)
|
||||
|
||||
@@ -24,6 +24,8 @@ use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{public_chart, rfc3339, rfc3339_opt, synastry_hash};
|
||||
|
||||
const INVITE_TTL: time::Duration = time::Duration::days(14);
|
||||
/// Invitations a user may have us e-mail in a day (the rest go by link).
|
||||
const EMAILED_PER_DAY: i64 = 10;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct SynastryRow {
|
||||
@@ -238,6 +240,10 @@ pub struct CreateInvite {
|
||||
/// Defaults to the user's primary chart.
|
||||
chart_id: Option<Uuid>,
|
||||
message: Option<String>,
|
||||
/// Who it is for, as the inviter calls them (only the inviter sees it).
|
||||
label: Option<String>,
|
||||
/// Have us e-mail the invitation to this address.
|
||||
email: Option<String>,
|
||||
}
|
||||
|
||||
async fn chart_or_primary(db: &PgPool, chart_id: Option<Uuid>, user: Uuid) -> Result<ChartRow, ApiError> {
|
||||
@@ -255,13 +261,57 @@ pub async fn create_invite(
|
||||
WithRejection(Json(req), _): Body<CreateInvite>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let chart = chart_or_primary(&state.db, req.chart_id, auth.id()).await?;
|
||||
let message = req.message.map(|m| m.trim().chars().take(500).collect::<String>()).filter(|m| !m.is_empty());
|
||||
// No links: the message may go out in an e-mail from our domain.
|
||||
let message = super::invitations::clean_message(req.message)?;
|
||||
let label = req.label.map(|l| l.trim().chars().take(80).collect::<String>()).filter(|l| !l.is_empty());
|
||||
let email = match req.email.as_deref().map(str::trim).filter(|e| !e.is_empty()) {
|
||||
Some(raw) => Some(super::auth::normalize_email(raw)?),
|
||||
None => None,
|
||||
};
|
||||
let token = db::new_token();
|
||||
let id = Uuid::now_v7();
|
||||
let expires_at = OffsetDateTime::now_utc() + INVITE_TTL;
|
||||
let url = format!("{}/meghivas/{token}", state.config.public_base_url);
|
||||
let mut tx = state.db.begin().await?;
|
||||
let mut emailed = false;
|
||||
if let Some(to) = &email {
|
||||
if *to == auth.user.email {
|
||||
return Err(ApiError::BadRequest("Saját magadat nem hívhatod meg.".into()));
|
||||
}
|
||||
let today: i64 = sqlx::query_scalar(
|
||||
"SELECT count(*) FROM synastry_invites WHERE inviter_id = $1 AND invitee_email IS NOT NULL \
|
||||
AND created_at > now() - interval '1 day'",
|
||||
)
|
||||
.bind(auth.id())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if today >= EMAILED_PER_DAY {
|
||||
return Err(ApiError::conflict(
|
||||
"invite_mail_limit",
|
||||
format!(
|
||||
"Naponta legfeljebb {EMAILED_PER_DAY} meghívót küldünk ki levélben. A linket továbbra is elküldheted."
|
||||
),
|
||||
));
|
||||
}
|
||||
// Someone who asked for no more invitations gets none; the link still works.
|
||||
if !super::invitations::opted_out(&mut tx, to).await? {
|
||||
let (_, unsubscribe_url, unsubscribe_post_url) = super::invitations::links(&state, &token);
|
||||
let payload = json!({
|
||||
"url": url,
|
||||
"inviter_name": auth.user.display_name,
|
||||
"message": message,
|
||||
"expires_on": expires_at.date().to_string(),
|
||||
"unsubscribe_url": unsubscribe_url,
|
||||
"unsubscribe_post_url": unsubscribe_post_url,
|
||||
});
|
||||
super::auth::queue_email_to(&mut tx, None, to, "synastry_invite", &auth.user.locale, payload).await?;
|
||||
emailed = true;
|
||||
}
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
"INSERT INTO synastry_invites (id, inviter_id, inviter_chart_id, token_hash, message, expires_at, label, \
|
||||
invitee_email) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
@@ -269,16 +319,22 @@ pub async fn create_invite(
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(&message)
|
||||
.bind(expires_at)
|
||||
.execute(&state.db)
|
||||
.bind(&label)
|
||||
.bind(&email)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(json!({
|
||||
"id": id,
|
||||
"token": token,
|
||||
"url": format!("{}/invite/{token}", state.config.public_base_url),
|
||||
"url": url,
|
||||
"chart_id": chart.id,
|
||||
"message": message,
|
||||
"label": label,
|
||||
"email": email,
|
||||
"emailed": emailed,
|
||||
"expires_at": rfc3339(expires_at),
|
||||
})),
|
||||
))
|
||||
@@ -304,10 +360,12 @@ pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult<Json<Va
|
||||
Option<OffsetDateTime>,
|
||||
Option<Uuid>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT i.id, i.inviter_chart_id, i.message, i.created_at, i.expires_at, i.accepted_at, i.synastry_id, \
|
||||
u.display_name \
|
||||
u.display_name, i.label, i.invitee_email \
|
||||
FROM synastry_invites i LEFT JOIN users u ON u.id = i.accepted_by \
|
||||
WHERE i.inviter_id = $1 ORDER BY i.created_at DESC",
|
||||
)
|
||||
@@ -316,9 +374,9 @@ pub async fn list_invites(State(state): St, auth: AuthUser) -> ApiResult<Json<Va
|
||||
.await?;
|
||||
let list: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by)| {
|
||||
.map(|(id, chart_id, message, created, expires, accepted, synastry_id, accepted_by, label, email)| {
|
||||
json!({
|
||||
"id": id, "chart_id": chart_id, "message": message,
|
||||
"id": id, "chart_id": chart_id, "message": message, "label": label, "email": email,
|
||||
"status": invite_status(accepted, expires),
|
||||
"created_at": rfc3339(created), "expires_at": rfc3339(expires),
|
||||
"accepted_at": rfc3339_opt(accepted), "accepted_by": accepted_by, "synastry_id": synastry_id,
|
||||
@@ -425,7 +483,7 @@ pub async fn accept_invite(
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some(inviter) = inviter {
|
||||
let url = format!("{}/synastry/{}", state.config.public_base_url, row.id);
|
||||
let url = format!("{}/osszevetesek/{}", state.config.public_base_url, row.id);
|
||||
super::auth::queue_email(
|
||||
&mut tx,
|
||||
&inviter,
|
||||
|
||||
@@ -517,6 +517,67 @@ async fn invitation_links_two_users(pool: PgPool) {
|
||||
assert!(app.outbox_url("anna@example.com", "invite_accepted").await.ends_with(&synastry_id));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn a_person_can_be_invited_by_mail(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
|
||||
// links are not allowed in the message (it may go out in our e-mail)
|
||||
let r =
|
||||
app.post("/v1/invites", Some(&anna), json!({"message": "nézd: www.x.hu", "email": "bela@example.com"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"email": "anna@example.com"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST, "not herself");
|
||||
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/invites",
|
||||
Some(&anna),
|
||||
json!({"label": "Béla", "email": " Bela@Example.com ", "message": "Nézzük meg, mennyire illünk!"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let token = r.body["token"].as_str().unwrap().to_string();
|
||||
assert!(r.body["url"].as_str().unwrap().ends_with(&format!("/meghivas/{token}")));
|
||||
assert_eq!((r.body["emailed"].as_bool(), r.body["email"].as_str()), (Some(true), Some("bela@example.com")));
|
||||
let (template, payload): (String, Value) =
|
||||
sqlx::query_as("SELECT template, payload FROM email_outbox WHERE to_email = 'bela@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((template.as_str(), &payload["inviter_name"]), ("synastry_invite", &json!("Anna")));
|
||||
let invites = app.get("/v1/invites", Some(&anna)).await.body;
|
||||
assert_eq!(
|
||||
(&invites["invites"][0]["label"], &invites["invites"][0]["status"]),
|
||||
(&json!("Béla"), &json!("pending"))
|
||||
);
|
||||
|
||||
// the address can opt out; the next invitation goes by link only
|
||||
let r = app.post(&format!("/v1/public/invitations/unsubscribe?token={token}"), None, json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"email": "bela@example.com"})).await;
|
||||
assert_eq!((r.status, r.body["emailed"].as_bool()), (StatusCode::CREATED, Some(false)));
|
||||
|
||||
// at most ten e-mailed a day
|
||||
for i in 2..10 {
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"email": format!("p{i}@example.com")})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED);
|
||||
}
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"email": "p10@example.com"})).await;
|
||||
assert_eq!(r.body["error"]["code"], "invite_mail_limit");
|
||||
let r = app.post("/v1/invites", Some(&anna), json!({"label": "link only"})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "a link is still fine");
|
||||
|
||||
// accepted: the inviter's mail leads to the comparison page
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
app.chart(&bela, "Saját", true, "1976-09-03").await;
|
||||
let r = app.post("/v1/invites/accept", Some(&bela), json!({"token": token})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let url = app.outbox_url("anna@example.com", "invite_accepted").await;
|
||||
assert!(url.ends_with(&format!("/osszevetesek/{}", r.body["id"].as_str().unwrap())), "{url}");
|
||||
}
|
||||
|
||||
/// Gives `token`'s user analysis units (the admin endpoint is tested in `roles_and_admin_guard`).
|
||||
async fn grant_units(app: &TestApp, token: &str, unit: &str, delta: i32) {
|
||||
let id = app.get("/v1/me", Some(token)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
|
||||
Reference in New Issue
Block a user