Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
321d43f369 | ||
|
|
6a147aa253 | ||
|
|
a986cf4edd | ||
|
|
169fb9c85d | ||
|
|
8d9c50cb02 | ||
|
|
018ccf76a0 | ||
|
|
26c5bb2746 | ||
|
|
2997a06474 |
@@ -85,6 +85,28 @@ impl FromRequestParts<Arc<AppState>> for AdminUser {
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard: may manage the famous people (the admin or the creator role).
|
||||
pub struct CelebrityEditor(pub AuthUser);
|
||||
|
||||
impl CelebrityEditor {
|
||||
pub fn is_admin(&self) -> bool {
|
||||
self.0.user.has_role(Role::Admin)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for CelebrityEditor {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
if user.user.has_role(Role::Creator) {
|
||||
return Ok(CelebrityEditor(user));
|
||||
}
|
||||
user.require(Role::Admin)?;
|
||||
Ok(CelebrityEditor(user))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_agent(parts_headers: &axum::http::HeaderMap) -> Option<String> {
|
||||
parts_headers.get(USER_AGENT).and_then(|v| v.to_str().ok()).map(|s| s.chars().take(300).collect())
|
||||
}
|
||||
|
||||
@@ -60,11 +60,17 @@ pub async fn list_users(
|
||||
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
|
||||
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pattern)
|
||||
.bind(&pattern)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let total: i64 = sqlx::query_scalar(
|
||||
"SELECT count(*) FROM users u WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1",
|
||||
)
|
||||
.bind(&pattern)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let users: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question, tarot)| {
|
||||
@@ -78,7 +84,7 @@ pub async fn list_users(
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "users": users, "limit": limit, "offset": offset })))
|
||||
Ok(Json(json!({ "users": users, "total": total, "limit": limit, "offset": offset })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -410,6 +410,11 @@ pub async fn regenerate(
|
||||
_admin: crate::auth::AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(regenerate_in_place(&state, id).await?))
|
||||
}
|
||||
|
||||
/// See [`regenerate`]; also used for the famous people's analyses.
|
||||
pub(super) async fn regenerate_in_place(state: &AppState, id: Uuid) -> Result<Value, ApiError> {
|
||||
let row = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
if row.status == "pending" || row.status == "running" {
|
||||
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
|
||||
@@ -446,5 +451,5 @@ pub async fn regenerate(
|
||||
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(%id, kind, "analysis regenerated");
|
||||
Ok(Json(row.view()))
|
||||
Ok(row.view())
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
|
||||
use super::charts::{CHART_COLUMNS, ChartRow, calculate, find_chart};
|
||||
use super::{Body, IdPath, St, double_option};
|
||||
use crate::AppState;
|
||||
use crate::auth::{AdminUser, AuthUser};
|
||||
use crate::auth::{AuthUser, CelebrityEditor};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{chart_highlights, public_chart, rfc3339, rfc3339_opt};
|
||||
|
||||
@@ -43,12 +43,13 @@ struct CelebrityRow {
|
||||
focus_x: f32,
|
||||
focus_y: f32,
|
||||
published_at: Option<OffsetDateTime>,
|
||||
created_by: Option<Uuid>,
|
||||
created_at: OffsetDateTime,
|
||||
updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id, chart_id, name, subtitle, slug, photo_key, photo_width, photo_height, focus_x, focus_y, \
|
||||
published_at, created_at, updated_at";
|
||||
published_at, created_by, created_at, updated_at";
|
||||
|
||||
impl CelebrityRow {
|
||||
fn photo(&self) -> Value {
|
||||
@@ -161,6 +162,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result<Value, ApiError>
|
||||
let chart = find_chart(db, row.chart_id).await?.ok_or(ApiError::NotFound("celebrity"))?;
|
||||
let analysis = latest_analysis(db, row.chart_id).await?;
|
||||
let mut view = row.base();
|
||||
view["created_by"] = json!(row.created_by);
|
||||
view["birth_data"] = chart.birth_data.clone();
|
||||
view["birth"] = public_chart(&chart.result, true)["birth"].clone();
|
||||
view["highlights"] = chart_highlights(&chart.result);
|
||||
@@ -174,7 +176,7 @@ async fn admin_view(db: &PgPool, row: &CelebrityRow) -> Result<Value, ApiError>
|
||||
type ListRow =
|
||||
(Uuid, Uuid, String, Option<String>, String, Option<OffsetDateTime>, Option<String>, Value, Option<String>);
|
||||
|
||||
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
|
||||
pub async fn list(State(state): St, _editor: CelebrityEditor) -> ApiResult<Json<Value>> {
|
||||
let rows: Vec<ListRow> = sqlx::query_as(
|
||||
"SELECT c.id, c.chart_id, c.name, c.subtitle, c.slug, c.published_at, c.photo_key, ch.result, \
|
||||
(SELECT a.status FROM analyses a WHERE a.chart_id = c.chart_id AND a.kind = 'celebrity' \
|
||||
@@ -210,7 +212,7 @@ pub struct CreateCelebrity {
|
||||
/// Adds a famous person: calculates the chart and queues the analysis.
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Json(req), _): Body<CreateCelebrity>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let name = clean_name(&req.name)?;
|
||||
@@ -249,7 +251,7 @@ pub async fn create(
|
||||
|
||||
pub async fn get_one(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -273,7 +275,7 @@ pub struct UpdateCelebrity {
|
||||
|
||||
pub async fn update(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<UpdateCelebrity>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
@@ -353,10 +355,10 @@ pub async fn update(
|
||||
}
|
||||
|
||||
/// Queues the analysis again when there is none or the last one failed
|
||||
/// (rewriting a finished one: `POST /v1/admin/analyses/{id}/regenerate`).
|
||||
/// (rewriting a finished one: [`regenerate_analysis`]).
|
||||
pub async fn request_analysis(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -365,6 +367,17 @@ pub async fn request_analysis(
|
||||
Ok(Json(admin_view(&state.db, &row).await?))
|
||||
}
|
||||
|
||||
/// Writes the finished (or failed) analysis again with the current prompt.
|
||||
pub async fn regenerate_analysis(
|
||||
State(state): St,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
let analysis = latest_analysis(&state.db, row.chart_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
Ok(Json(super::analyses::regenerate_in_place(&state, analysis.id).await?))
|
||||
}
|
||||
|
||||
fn storage(state: &AppState) -> Result<&crate::storage::Storage, ApiError> {
|
||||
state
|
||||
.storage
|
||||
@@ -385,7 +398,7 @@ async fn delete_photo(state: &AppState, key: &str) {
|
||||
/// WebP); it replaces the previous one. The face point is reset.
|
||||
pub async fn upload_photo(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
CelebrityEditor(admin): CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
body: Bytes,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
@@ -422,7 +435,7 @@ pub async fn upload_photo(
|
||||
|
||||
pub async fn remove_photo(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
_editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find(&state.db, id).await?;
|
||||
@@ -442,10 +455,14 @@ pub async fn remove_photo(
|
||||
/// Deletes the famous person with their chart, analysis and photo.
|
||||
pub async fn remove(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
editor: CelebrityEditor,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let row = find(&state.db, id).await?;
|
||||
if !editor.is_admin() && row.created_by != Some(editor.0.id()) {
|
||||
return Err(ApiError::Forbidden("only an admin may delete someone else's famous person".into()));
|
||||
}
|
||||
let admin = editor.0;
|
||||
sqlx::query("DELETE FROM charts WHERE id = $1").bind(row.chart_id).execute(&state.db).await?;
|
||||
if let Some(key) = &row.photo_key {
|
||||
delete_photo(&state, key).await;
|
||||
@@ -474,7 +491,7 @@ pub async fn public_list(State(state): St) -> ApiResult<Json<Value>> {
|
||||
Ok(Json(json!({ "celebrities": items })))
|
||||
}
|
||||
|
||||
/// Public: one famous person's page (a draft only for admins).
|
||||
/// Public: one famous person's page (a draft only for admins and creators).
|
||||
pub async fn public_view(
|
||||
State(state): St,
|
||||
auth: Result<AuthUser, ApiError>,
|
||||
@@ -485,7 +502,7 @@ pub async fn public_view(
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("celebrity"))?;
|
||||
let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin));
|
||||
let admin = auth.is_ok_and(|a| a.user.has_role(db::Role::Admin) || a.user.has_role(db::Role::Creator));
|
||||
if row.published_at.is_none() && !admin {
|
||||
return Err(ApiError::NotFound("celebrity"));
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Admin: the error log of the analyses, answers and prompt test runs (every
|
||||
//! failed attempt, written by the worker), newest first.
|
||||
//! failed attempt, written by the worker), newest first. Entries can be
|
||||
//! deleted one by one or all that match a filter.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -71,3 +73,41 @@ pub async fn list(
|
||||
.collect();
|
||||
Ok(Json(json!({ "errors": errors, "total": total, "last_day": last_day, "limit": limit, "offset": offset })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeleteQuery {
|
||||
source: Option<String>,
|
||||
outcome: Option<String>,
|
||||
}
|
||||
|
||||
/// Deletes every entry matching the filter (none given: all of them).
|
||||
pub async fn delete_matching(
|
||||
State(state): St,
|
||||
AdminUser(admin): AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<DeleteQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let deleted = sqlx::query(
|
||||
"DELETE FROM generation_errors WHERE ($1::text IS NULL OR source = $1) AND ($2::text IS NULL OR outcome = $2)",
|
||||
)
|
||||
.bind(&query.source)
|
||||
.bind(&query.outcome)
|
||||
.execute(&state.db)
|
||||
.await?
|
||||
.rows_affected();
|
||||
tracing::info!(admin = %admin.id(), deleted, "error log entries deleted");
|
||||
Ok(Json(json!({ "deleted": deleted })))
|
||||
}
|
||||
|
||||
/// Deletes one entry.
|
||||
pub async fn delete_one(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Path(id), _): WithRejection<Path<i64>, ApiError>,
|
||||
) -> ApiResult<StatusCode> {
|
||||
let result = sqlx::query("DELETE FROM generation_errors WHERE id = $1").bind(id).execute(&state.db).await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("error"));
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
@@ -552,6 +552,7 @@ pub async fn preview(
|
||||
pub async fn public_view(State(state): St, Path(token): Path<String>) -> ApiResult<Json<Value>> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Landing {
|
||||
id: Uuid,
|
||||
inviter: Option<String>,
|
||||
message: Option<String>,
|
||||
expires_at: OffsetDateTime,
|
||||
@@ -559,7 +560,7 @@ pub async fn public_view(State(state): St, Path(token): Path<String>) -> ApiResu
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
}
|
||||
let l: Landing = sqlx::query_as(
|
||||
"SELECT u.display_name AS inviter, i.message, i.expires_at, i.accepted_at, i.revoked_at \
|
||||
"SELECT i.id, u.display_name AS inviter, i.message, i.expires_at, i.accepted_at, i.revoked_at \
|
||||
FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id \
|
||||
LEFT JOIN users u ON u.id = i.invited_by WHERE t.token_hash = $1",
|
||||
)
|
||||
@@ -567,7 +568,16 @@ pub async fn public_view(State(state): St, Path(token): Path<String>) -> ApiResu
|
||||
.fetch_optional(&state.db)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound("invitation"))?;
|
||||
// The package that comes with it (only admins attach one); its code stays in the e-mail.
|
||||
let gift: Option<String> = sqlx::query_scalar(
|
||||
"SELECT package FROM promo_codes WHERE invitation_id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(l.id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let gift = gift.as_deref().and_then(packages::find).map_or(Value::Null, |p| p.view());
|
||||
Ok(Json(json!({
|
||||
"gift": gift,
|
||||
"inviter_name": l.inviter,
|
||||
"message": l.message,
|
||||
"status": status(l.accepted_at, l.revoked_at, l.expires_at),
|
||||
|
||||
@@ -147,7 +147,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
|
||||
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
|
||||
.route("/v1/admin/previews/{id}", get(prompts::get_preview))
|
||||
.route("/v1/admin/errors", get(errors::list))
|
||||
.route("/v1/admin/errors", get(errors::list).delete(errors::delete_matching))
|
||||
.route("/v1/admin/errors/{id}", axum::routing::delete(errors::delete_one))
|
||||
.route("/v1/admin/jobs", get(jobs::list))
|
||||
.route("/v1/admin/jobs/restart", post(jobs::restart))
|
||||
.route("/v1/admin/models", get(models::list))
|
||||
@@ -160,6 +161,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
get(celebrities::get_one).patch(celebrities::update).delete(celebrities::remove),
|
||||
)
|
||||
.route("/v1/admin/celebrities/{id}/analysis", post(celebrities::request_analysis))
|
||||
.route("/v1/admin/celebrities/{id}/analysis/regenerate", post(celebrities::regenerate_analysis))
|
||||
.route(
|
||||
"/v1/admin/celebrities/{id}/photo",
|
||||
axum::routing::put(celebrities::upload_photo)
|
||||
|
||||
@@ -1772,6 +1772,7 @@ async fn invitation_only_signup(pool: PgPool) {
|
||||
);
|
||||
let r = app.get(&format!("/v1/public/invitations/{guest_token}"), None).await;
|
||||
assert_eq!((r.body["inviter_name"].as_str(), r.body["status"].as_str()), (Some("Admin"), Some("pending")));
|
||||
assert_eq!(r.body["gift"], Value::Null);
|
||||
|
||||
// a resend: not too soon, then with a new link; the old one keeps working
|
||||
let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await;
|
||||
@@ -2214,6 +2215,19 @@ async fn admins_read_the_error_log(pool: PgPool) {
|
||||
let r = app.get("/v1/admin/errors?outcome=retry", Some(&admin)).await;
|
||||
assert_eq!(r.body["errors"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(app.get("/v1/admin/errors?source=question", Some(&admin)).await.body["total"], 0);
|
||||
// deleted one by one, or all that match the filter
|
||||
let retry_id = r.body["errors"][0]["id"].as_i64().unwrap();
|
||||
let r = app.call("DELETE", &format!("/v1/admin/errors/{retry_id}"), Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.call("DELETE", &format!("/v1/admin/errors/{retry_id}"), Some(&admin), None).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
let r = app.call("DELETE", &format!("/v1/admin/errors/{retry_id}"), Some(&admin), None).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
let r = app.call("DELETE", "/v1/admin/errors?outcome=retry", Some(&admin), None).await;
|
||||
assert_eq!(r.body["deleted"], 0);
|
||||
let r = app.call("DELETE", "/v1/admin/errors?source=analysis", Some(&admin), None).await;
|
||||
assert_eq!((r.status, &r.body["deleted"]), (StatusCode::OK, &json!(1)), "{}", r.body);
|
||||
assert_eq!(app.get("/v1/admin/errors", Some(&admin)).await.body["total"], 0);
|
||||
// users see the attempts of their analysis (the page says it is tried again)
|
||||
let r = app.get(&format!("/v1/analyses/{analysis}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["attempts"], 0);
|
||||
@@ -2327,6 +2341,10 @@ async fn an_invitation_brings_its_package_and_codes_fill_up(pool: PgPool) {
|
||||
);
|
||||
let list = app.get("/v1/admin/invitations", Some(&admin)).await.body;
|
||||
assert_eq!(list["invitations"][0]["package"]["name"], "Páros");
|
||||
// so does the invitation's page (without the code)
|
||||
let page = app.get(&format!("/v1/public/invitations/{guest_token}"), None).await.body;
|
||||
assert_eq!((&page["gift"]["name"], &page["gift"]["id"]), (&json!("Páros"), &json!("couple")), "{page}");
|
||||
assert!(!page.to_string().contains(guest["promo_code"].as_str().unwrap()));
|
||||
|
||||
// revoking an invitation withdraws its code
|
||||
let r = app.call("DELETE", &format!("/v1/admin/invitations/{other_id}"), Some(&admin), None).await;
|
||||
@@ -3099,3 +3117,65 @@ async fn admins_publish_famous_people_with_a_photo(pool: PgPool) {
|
||||
assert_eq!(left["celebrities"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(left["celebrities"][0]["id"].as_str(), Some(second.as_str()));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn creators_add_famous_people_but_nothing_else_of_the_admin(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let writer = app.register("szerzo@example.com", "Szerző").await;
|
||||
sqlx::query("UPDATE users SET roles = '{user,creator}' WHERE email = 'szerzo@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let birth = json!({"date": "1926-06-01", "time": "09:30", "country": "HU", "place": "Szeged"});
|
||||
|
||||
// the famous people: add, edit, see the draft, rewrite the analysis, delete their own
|
||||
let r = app.post("/v1/admin/celebrities", Some(&writer), json!({"name": "Teszt Elek", "birth": birth})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let id = r.body["id"].as_str().unwrap().to_string();
|
||||
let analysis_id = r.body["analysis"]["id"].as_str().unwrap().to_string();
|
||||
assert!(r.body["created_by"].is_string());
|
||||
let r = app.call("PATCH", &format!("/v1/admin/celebrities/{id}"), Some(&writer), Some(json!({"subtitle": "író"}))).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get("/v1/public/celebrities/teszt-elek", Some(&writer)).await.status, StatusCode::OK);
|
||||
let regenerate = format!("/v1/admin/celebrities/{id}/analysis/regenerate");
|
||||
let r = app.post(®enerate, Some(&writer), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT, "still pending: {}", r.body);
|
||||
sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid")
|
||||
.bind(&analysis_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app.post(®enerate, Some(&writer), json!({})).await;
|
||||
assert_eq!((r.status, r.body["status"].as_str()), (StatusCode::OK, Some("pending")), "{}", r.body);
|
||||
assert_eq!(r.body["id"].as_str(), Some(analysis_id.as_str()));
|
||||
|
||||
// someone else's famous person: edited, but only an admin deletes it
|
||||
let r = app.post("/v1/admin/celebrities", Some(&admin), json!({"name": "Admin Ádám", "birth": birth})).await;
|
||||
let others = r.body["id"].as_str().unwrap().to_string();
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{others}"), Some(&writer), None).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{id}"), Some(&writer), None).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
|
||||
// the rest of the admin stays closed
|
||||
for uri in ["/v1/admin/users", "/v1/admin/prompts", "/v1/admin/errors"] {
|
||||
assert_eq!(app.get(uri, Some(&writer)).await.status, StatusCode::FORBIDDEN, "{uri}");
|
||||
}
|
||||
let r = app.post(&format!("/v1/admin/analyses/{analysis_id}/regenerate"), Some(&writer), json!({})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn the_user_list_pages_with_a_total(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
for i in 0..4 {
|
||||
app.register(&format!("lap{i}@example.com"), "Lapozó").await;
|
||||
}
|
||||
let r = app.get("/v1/admin/users?limit=2&offset=2", Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(5), 2));
|
||||
let r = app.get("/v1/admin/users?q=lap&limit=3&offset=3", Some(&admin)).await;
|
||||
assert_eq!((r.body["total"].as_i64(), r.body["users"].as_array().unwrap().len()), (Some(4), 1));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { ChartWheel } from "@/components/ChartWheel";
|
||||
import { Rich } from "@/components/Rich";
|
||||
import { TarotCard, TarotCardBack } from "@/components/tarot/TarotCard";
|
||||
import { Logo, PublicHeader } from "@/components/SiteHeader";
|
||||
import { Waitlist } from "@/components/Waitlist";
|
||||
import example from "@/content/pelda.json";
|
||||
import { tarotCard } from "@/lib/tarot";
|
||||
import type { AnalysisContent, ChartResult } from "@/lib/types";
|
||||
@@ -41,16 +40,18 @@ const CHAPTERS = ["Személyiség", "Érzelmek", "Gondolkodás", "Szerelem", "Hiv
|
||||
const SYNASTRY_TOPICS = ["Vonzás", "Kommunikáció", "Érzelmi kötődés", "Súrlódások", "Hosszú táv"];
|
||||
|
||||
/** The home page for visitors: what the site does, shown on the example chart. */
|
||||
export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
/** `loggedIn`: the layout shows the app's header, and the buttons lead to the user's chart instead of the login. */
|
||||
export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean; loggedIn?: boolean }) {
|
||||
const chart = example.chart as unknown as ChartResult;
|
||||
const analysis = example.analysis as AnalysisContent;
|
||||
const sections = ["emotions", "love"].map((k) => analysis.sections?.[k]).filter((s) => s !== undefined);
|
||||
const lead = (analysis.summary ?? "").split(/(?<=\.)\s/)[0];
|
||||
const signIn = inviteOnly ? "Belépés meghívóval" : "Elkészítem a képletem";
|
||||
const signIn = loggedIn ? "A képletem" : inviteOnly ? "Belépés meghívóval" : "Elkészítem a képletem";
|
||||
const start = loggedIn ? "/keplet" : "/belepes";
|
||||
|
||||
return (
|
||||
<div className="lp">
|
||||
<PublicHeader onHome />
|
||||
{!loggedIn && <PublicHeader onHome />}
|
||||
|
||||
<section className="lp-hero">
|
||||
<div className="lp-wrap lp-hero-grid">
|
||||
@@ -70,27 +71,26 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
árának töredékéért.
|
||||
</p>
|
||||
<div className="lp-actions lp-rise lp-r4">
|
||||
<Link href="/belepes" className="btn btn-primary lp-btn">
|
||||
<Link href={start} className="btn btn-primary lp-btn">
|
||||
{signIn}
|
||||
</Link>
|
||||
<Link href="/pelda" className="btn lp-btn">
|
||||
Példaelemzés
|
||||
</Link>
|
||||
</div>
|
||||
<p className="lp-free-line lp-rise lp-r4">
|
||||
<span className="lp-free-label">Ingyenes</span>
|
||||
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
||||
</p>
|
||||
<p className="hint lp-rise lp-r4">
|
||||
{inviteOnly ? (
|
||||
<>
|
||||
Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be. Ha még nincs meghívód,{" "}
|
||||
<a href="#varolista">iratkozz fel a várólistára</a>.
|
||||
</>
|
||||
) : (
|
||||
"A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."
|
||||
)}
|
||||
</p>
|
||||
{!loggedIn && (
|
||||
<p className="lp-free-line lp-rise lp-r4">
|
||||
<span className="lp-free-label">Ingyenes</span>
|
||||
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
||||
</p>
|
||||
)}
|
||||
{!loggedIn && (
|
||||
<p className="hint lp-rise lp-r4">
|
||||
{inviteOnly
|
||||
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
||||
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<figure className="lp-figure">
|
||||
@@ -126,7 +126,7 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
<div className="lp-free-head">
|
||||
<span className="lp-free-label">Ingyenes</span>
|
||||
<h2 id="free-title" className="lp-free-title">
|
||||
Belépés nélkül is kipróbálhatod
|
||||
{loggedIn ? "Ingyenes eszközök" : "Belépés nélkül is kipróbálhatod"}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="lp-free-grid">
|
||||
@@ -145,6 +145,14 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
</span>
|
||||
<span className="lp-free-go">Megnézem →</span>
|
||||
</Link>
|
||||
<Link href="/hires-emberek" className="card lp-free-card">
|
||||
<strong>Híres emberek horoszkópja</strong>
|
||||
<span className="muted">
|
||||
Ismert emberek születési képlete és részletes asztrológiai portréja: mit árul el róluk a születésük
|
||||
pillanatának égboltja?
|
||||
</span>
|
||||
<span className="lp-free-go">Megnézem →</span>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -450,7 +458,7 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="varolista" className="lp-band lp-final">
|
||||
<section className="lp-band lp-final">
|
||||
<div className="lp-wrap lp-final-inner">
|
||||
<svg aria-hidden="true" viewBox="0 0 120 120" className="lp-spin lp-emblem">
|
||||
<circle cx="60" cy="60" r="54" className="lp-emblem-outer" />
|
||||
@@ -461,18 +469,15 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
</svg>
|
||||
<h2 className="lp-h2">Kíváncsi vagy, mit mutat a te képleted?</h2>
|
||||
<p className="lp-text">
|
||||
{inviteOnly
|
||||
? "Egyelőre meghívással lehet csatlakozni. Ha kaptál meghívót, lépj be a Google-fiókoddal. Ha még nem, írd fel magad, és szólunk."
|
||||
: "Két perc, és ott a képleted a rövid összefoglalóval együtt."}
|
||||
{loggedIn
|
||||
? "A képleted, az elemzéseid és az összevetéseid egy kattintásra."
|
||||
: inviteOnly
|
||||
? "Egyelőre meghívással lehet csatlakozni. Ha kaptál meghívót, lépj be a Google-fiókoddal."
|
||||
: "Két perc, és ott a képleted a rövid összefoglalóval együtt."}
|
||||
</p>
|
||||
<Link href="/belepes" className="btn btn-primary lp-btn lp-btn-big">
|
||||
<Link href={start} className="btn btn-primary lp-btn lp-btn-big">
|
||||
{signIn}
|
||||
</Link>
|
||||
{inviteOnly && (
|
||||
<div className="lp-waitlist">
|
||||
<Waitlist />
|
||||
</div>
|
||||
)}
|
||||
<p className="hint lp-disclaimer">
|
||||
Az elemzéseket mesterséges intelligencia írja a pontosan kiszámolt képlet alapján. Tájékoztató jellegűek, nem
|
||||
helyettesítenek szakmai tanácsot.
|
||||
@@ -498,7 +503,7 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
|
||||
<Link href="/kartyajoslas/pelda">Példajóslás</Link>
|
||||
<Link href="/aszf">ÁSZF</Link>
|
||||
<Link href="/adatvedelem">Adatvédelem</Link>
|
||||
<Link href="/belepes">Belépés</Link>
|
||||
{!loggedIn && <Link href="/belepes">Belépés</Link>}
|
||||
</nav>
|
||||
<span className="hint">© {new Date().getFullYear()} Sorsfonalak</span>
|
||||
</div>
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { huf, usePackages } from "@/components/PackageCards";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||
import type { AdminUser, Package, Role } from "@/lib/types";
|
||||
|
||||
const PAGE_SIZE = 25;
|
||||
const EDITABLE_ROLES: Role[] = ["user", "creator", "admin"];
|
||||
type UnitKind = "natal" | "synastry" | "forecast" | "question" | "tarot";
|
||||
|
||||
@@ -18,16 +20,22 @@ const UNITS: { value: UnitKind; label: string }[] = [
|
||||
{ value: "tarot", label: "kártyajóslás" },
|
||||
];
|
||||
|
||||
type Status = { ok: boolean; text: string } | null;
|
||||
|
||||
export function AdminUsers({ selfId }: { selfId: string }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [users, setUsers] = useState<AdminUser[] | null>(null);
|
||||
const [page, setPage] = useState(0);
|
||||
const [data, setData] = useState<{ users: AdminUser[]; total: number } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const packages = usePackages() ?? [];
|
||||
|
||||
const load = useCallback(async (q: string) => {
|
||||
const load = useCallback(async (q: string, p: number) => {
|
||||
try {
|
||||
const data = await api<{ users: AdminUser[] }>(`/admin/users?q=${encodeURIComponent(q)}`);
|
||||
setUsers(data.users);
|
||||
const res = await api<{ users: AdminUser[]; total: number }>(
|
||||
`/admin/users?q=${encodeURIComponent(q)}&limit=${PAGE_SIZE}&offset=${p * PAGE_SIZE}`,
|
||||
);
|
||||
setData(res);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
@@ -35,22 +43,39 @@ export function AdminUsers({ selfId }: { selfId: string }) {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => load(query.trim()), 250);
|
||||
const t = setTimeout(() => load(query.trim(), page), 250);
|
||||
return () => clearTimeout(t);
|
||||
}, [query, load]);
|
||||
}, [query, page, load]);
|
||||
|
||||
const users = data?.users ?? null;
|
||||
const total = data?.total ?? 0;
|
||||
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const selected = users?.find((u) => u.id === editing) ?? null;
|
||||
const update = (next: AdminUser) =>
|
||||
setData((d) => d && { ...d, users: d.users.map((x) => (x.id === next.id ? next : x)) });
|
||||
|
||||
return (
|
||||
<section className="card" aria-label="Felhasználók listája">
|
||||
<div className="field" style={{ maxWidth: 420 }}>
|
||||
<label htmlFor="user-search">Keresés név vagy e-mail alapján</label>
|
||||
<input
|
||||
id="user-search"
|
||||
className="inp"
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="pl. anna@"
|
||||
/>
|
||||
<div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end" }}>
|
||||
<div className="field" style={{ flex: "1 1 280px", maxWidth: 420 }}>
|
||||
<label htmlFor="user-search">Keresés név vagy e-mail alapján</label>
|
||||
<input
|
||||
id="user-search"
|
||||
className="inp"
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
placeholder="pl. anna@"
|
||||
/>
|
||||
</div>
|
||||
{data && (
|
||||
<span className="muted" style={{ fontSize: 14 }}>
|
||||
{total} felhasználó
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
@@ -63,53 +88,153 @@ export function AdminUsers({ selfId }: { selfId: string }) {
|
||||
<p className="muted">Nincs találat.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<table className="admin-users">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Felhasználó</th>
|
||||
<th scope="col">Szerepkörök</th>
|
||||
<th scope="col">Részletes elemzések</th>
|
||||
<th scope="col">Csomag</th>
|
||||
<th scope="col">Szerepkör</th>
|
||||
<th scope="col">Hátralévő elemzések</th>
|
||||
<th scope="col">Képletek</th>
|
||||
<th scope="col">Regisztrált</th>
|
||||
<th scope="col">Utoljára belépett</th>
|
||||
<th scope="col">
|
||||
<span className="sr-only">Műveletek</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => (
|
||||
<UserRow
|
||||
key={u.id}
|
||||
user={u}
|
||||
isSelf={u.id === selfId}
|
||||
packages={packages}
|
||||
onChange={(next) => setUsers((list) => list?.map((x) => (x.id === next.id ? next : x)) ?? null)}
|
||||
/>
|
||||
<tr key={u.id}>
|
||||
<td>
|
||||
<div>{u.display_name || <span className="muted">(nincs név)</span>}</div>
|
||||
<div className="muted" style={{ fontSize: 13 }}>
|
||||
{u.email}
|
||||
{u.id === selfId && " · te"}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<RoleBadges roles={u.roles} />
|
||||
</td>
|
||||
<td>
|
||||
<Balances user={u} />
|
||||
</td>
|
||||
<td className="num">{u.charts}</td>
|
||||
<td className="num">{formatDate(u.created_at)}</td>
|
||||
<td className="num">{formatDate(u.last_login_at, true)}</td>
|
||||
<td style={{ textAlign: "right" }}>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setEditing(u.id)}>
|
||||
Kezelés
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{data && total > PAGE_SIZE && (
|
||||
<nav className="pager" aria-label="Lapozás">
|
||||
<button type="button" className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
|
||||
‹ Előző
|
||||
</button>
|
||||
<span className="num">
|
||||
{page * PAGE_SIZE + 1}–{Math.min(total, (page + 1) * PAGE_SIZE)} / {total} · {page + 1}/{pages}. oldal
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={page + 1 >= pages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
>
|
||||
Következő ›
|
||||
</button>
|
||||
</nav>
|
||||
)}
|
||||
{selected && (
|
||||
<UserDialog
|
||||
user={selected}
|
||||
isSelf={selected.id === selfId}
|
||||
packages={packages}
|
||||
onChange={update}
|
||||
onClose={() => setEditing(null)}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function UserRow({
|
||||
function RoleBadges({ roles }: { roles: Role[] }) {
|
||||
const shown = roles.filter((r) => r !== "user");
|
||||
if (shown.length === 0) return <span className="muted">Felhasználó</span>;
|
||||
return (
|
||||
<div className="row" style={{ gap: 4 }}>
|
||||
{shown.map((r) => (
|
||||
<span key={r} className={r === "admin" ? "badge badge-gold" : "badge"}>
|
||||
{ROLE_LABELS[r] ?? r}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The remaining units in one line, only the ones the user has. */
|
||||
function Balances({ user }: { user: AdminUser }) {
|
||||
const left = UNITS.map((u) => ({ ...u, n: user.analyses_left[u.value] ?? 0 })).filter((u) => u.n !== 0);
|
||||
if (left.length === 0) return <span className="muted">–</span>;
|
||||
return (
|
||||
<span style={{ fontSize: 13 }}>
|
||||
{left.map((u, i) => (
|
||||
<span key={u.value} style={{ whiteSpace: "nowrap" }}>
|
||||
{i > 0 && " · "}
|
||||
{u.label} <span className="num">{u.n}</span>
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Roles, a package and single units for one user. */
|
||||
function UserDialog({
|
||||
user,
|
||||
isSelf,
|
||||
packages,
|
||||
onChange,
|
||||
onClose,
|
||||
}: {
|
||||
user: AdminUser;
|
||||
isSelf: boolean;
|
||||
packages: Package[];
|
||||
onChange: (u: AdminUser) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [delta, setDelta] = useState("");
|
||||
const [unit, setUnit] = useState<UnitKind>("natal");
|
||||
return (
|
||||
<Modal
|
||||
title={user.display_name || "(nincs név)"}
|
||||
subtitle={
|
||||
<>
|
||||
{user.email}
|
||||
{isSelf && " · te"} · regisztrált {formatDate(user.created_at)}
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
>
|
||||
<RolesEditor user={user} isSelf={isSelf} onChange={onChange} />
|
||||
<PackageGrant user={user} packages={packages} onChange={onChange} />
|
||||
<CreditGrant user={user} onChange={onChange} />
|
||||
<div className="row" style={{ justifyContent: "flex-end" }}>
|
||||
<button type="button" className="btn btn-primary" onClick={onClose}>
|
||||
Kész
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
async function toggleRole(role: Role, on: boolean) {
|
||||
function RolesEditor({ user, isSelf, onChange }: { user: AdminUser; isSelf: boolean; onChange: (u: AdminUser) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<Status>(null);
|
||||
|
||||
async function toggle(role: Role, on: boolean) {
|
||||
const roles = on ? [...user.roles, role] : user.roles.filter((r) => r !== role);
|
||||
if (roles.length === 0) return setStatus({ ok: false, text: "Legalább egy szerepkör kell." });
|
||||
setBusy(true);
|
||||
@@ -117,27 +242,7 @@ function UserRow({
|
||||
try {
|
||||
const res = await api<{ roles: Role[] }>(`/admin/users/${user.id}`, { method: "PATCH", body: { roles } });
|
||||
onChange({ ...user, roles: res.roles });
|
||||
} catch (e) {
|
||||
setStatus({ ok: false, text: errorText(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function grant(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const n = Number.parseInt(delta, 10);
|
||||
if (!Number.isFinite(n) || n === 0) return setStatus({ ok: false, text: "Adj meg egy nem nulla egész számot." });
|
||||
setBusy(true);
|
||||
setStatus(null);
|
||||
try {
|
||||
const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/credits`, {
|
||||
body: { unit, delta: n, note: "admin" },
|
||||
});
|
||||
onChange({ ...user, analyses_left: res.analyses_left });
|
||||
setDelta("");
|
||||
const label = UNITS.find((u) => u.value === unit)?.label;
|
||||
setStatus({ ok: true, text: `${n > 0 ? "+" : ""}${n} ${label}` });
|
||||
setStatus({ ok: true, text: "Mentve." });
|
||||
} catch (e) {
|
||||
setStatus({ ok: false, text: errorText(e) });
|
||||
} finally {
|
||||
@@ -146,26 +251,19 @@ function UserRow({
|
||||
}
|
||||
|
||||
return (
|
||||
<tr>
|
||||
<td>
|
||||
<div>{user.display_name || <span className="muted">(nincs név)</span>}</div>
|
||||
<div className="muted" style={{ fontSize: 13 }}>
|
||||
{user.email}
|
||||
{isSelf && " · te"}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div className="row" style={{ gap: 4 }}>
|
||||
<div className="modal-section">
|
||||
<fieldset>
|
||||
<legend>Szerepkörök</legend>
|
||||
<div className="row" style={{ gap: 16 }}>
|
||||
{EDITABLE_ROLES.map((role) => {
|
||||
const on = user.roles.includes(role);
|
||||
const locked = isSelf && role === "admin";
|
||||
return (
|
||||
<label key={role} className="check" style={{ minHeight: 28, fontSize: 13, marginRight: 8 }}>
|
||||
<label key={role} className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={on}
|
||||
checked={user.roles.includes(role)}
|
||||
disabled={busy || locked}
|
||||
onChange={(e) => toggleRole(role, e.target.checked)}
|
||||
onChange={(e) => toggle(role, e.target.checked)}
|
||||
title={locked ? "A saját admin szerepköröd nem veheted el." : undefined}
|
||||
/>
|
||||
{ROLE_LABELS[role]}
|
||||
@@ -173,65 +271,14 @@ function UserRow({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<form onSubmit={grant} className="row" style={{ gap: 6, flexWrap: "nowrap" }}>
|
||||
<span className="num" style={{ minWidth: 92, fontSize: 13 }}>
|
||||
képlet {user.analyses_left.natal}
|
||||
<br />
|
||||
szinasztria {user.analyses_left.synastry}
|
||||
<br />
|
||||
előrejelzés {user.analyses_left.forecast ?? 0}
|
||||
<br />
|
||||
kérdés {user.analyses_left.question ?? 0}
|
||||
<br />
|
||||
jóslás {user.analyses_left.tarot ?? 0}
|
||||
</span>
|
||||
<label className="sr-only" htmlFor={`unit-${user.id}`}>
|
||||
Elemzés fajtája
|
||||
</label>
|
||||
<select
|
||||
id={`unit-${user.id}`}
|
||||
className="inp"
|
||||
style={{ width: 118, minHeight: 36 }}
|
||||
value={unit}
|
||||
onChange={(e) => setUnit(e.target.value as UnitKind)}
|
||||
>
|
||||
{UNITS.map((u) => (
|
||||
<option key={u.value} value={u.value}>
|
||||
{u.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="sr-only" htmlFor={`delta-${user.id}`}>
|
||||
Jóváírt darabszám
|
||||
</label>
|
||||
<input
|
||||
id={`delta-${user.id}`}
|
||||
className="inp"
|
||||
style={{ width: 76, minHeight: 36 }}
|
||||
inputMode="numeric"
|
||||
placeholder="+1"
|
||||
value={delta}
|
||||
onChange={(e) => setDelta(e.target.value)}
|
||||
/>
|
||||
<button type="submit" className="btn btn-sm" disabled={busy || !delta}>
|
||||
Jóváír
|
||||
</button>
|
||||
</form>
|
||||
<p className="muted modal-hint">A szerző híres embereket vihet fel és szerkeszthet.</p>
|
||||
{status && (
|
||||
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
|
||||
{status.text}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<PackageGrant user={user} packages={packages} onChange={onChange} />
|
||||
</td>
|
||||
<td className="num">{user.charts}</td>
|
||||
<td className="num">{formatDate(user.created_at)}</td>
|
||||
<td className="num">{formatDate(user.last_login_at, true)}</td>
|
||||
</tr>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -247,7 +294,7 @@ function PackageGrant({
|
||||
}) {
|
||||
const [id, setId] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [status, setStatus] = useState<Status>(null);
|
||||
|
||||
async function give(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -256,12 +303,11 @@ function PackageGrant({
|
||||
setBusy(true);
|
||||
setStatus(null);
|
||||
try {
|
||||
const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(
|
||||
`/admin/users/${user.id}/packages`,
|
||||
{ body: { package: pkg.id, note: "admin ajándék" } },
|
||||
);
|
||||
const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/packages`, {
|
||||
body: { package: pkg.id, note: "admin ajándék" },
|
||||
});
|
||||
onChange({ ...user, analyses_left: res.analyses_left });
|
||||
setStatus({ ok: true, text: `${pkg.name} kiosztva` });
|
||||
setStatus({ ok: true, text: `${pkg.name} kiosztva.` });
|
||||
setId("");
|
||||
} catch (err) {
|
||||
setStatus({ ok: false, text: errorText(err) });
|
||||
@@ -271,35 +317,122 @@ function PackageGrant({
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={give} className="field" style={{ gap: 6 }}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: "nowrap" }}>
|
||||
<label className="sr-only" htmlFor={`pkg-${user.id}`}>
|
||||
Kiosztandó csomag
|
||||
</label>
|
||||
<select
|
||||
id={`pkg-${user.id}`}
|
||||
className="inp"
|
||||
style={{ width: 190, minHeight: 36 }}
|
||||
value={id}
|
||||
onChange={(e) => setId(e.target.value)}
|
||||
disabled={busy || packages.length === 0}
|
||||
>
|
||||
<option value="">Válassz csomagot…</option>
|
||||
{packages.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name} ({huf(p.price_huf)})
|
||||
</option>
|
||||
<form onSubmit={give} className="modal-section">
|
||||
<fieldset>
|
||||
<legend>Csomag kiosztása (ajándék)</legend>
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<label className="sr-only" htmlFor={`pkg-${user.id}`}>
|
||||
Kiosztandó csomag
|
||||
</label>
|
||||
<select
|
||||
id={`pkg-${user.id}`}
|
||||
className="inp"
|
||||
style={{ flex: "1 1 220px", minHeight: 40 }}
|
||||
value={id}
|
||||
onChange={(e) => setId(e.target.value)}
|
||||
disabled={busy || packages.length === 0}
|
||||
>
|
||||
<option value="">Válassz csomagot…</option>
|
||||
{packages.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name} ({huf(p.price_huf)})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit" className="btn btn-sm" disabled={busy || !id}>
|
||||
{busy ? "…" : "Kiosztás"}
|
||||
</button>
|
||||
</div>
|
||||
{status && (
|
||||
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
|
||||
{status.text}
|
||||
</span>
|
||||
)}
|
||||
</fieldset>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Adds (or takes away) single analyses of one kind. */
|
||||
function CreditGrant({ user, onChange }: { user: AdminUser; onChange: (u: AdminUser) => void }) {
|
||||
const [delta, setDelta] = useState("");
|
||||
const [unit, setUnit] = useState<UnitKind>("natal");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<Status>(null);
|
||||
|
||||
async function grant(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const n = Number.parseInt(delta, 10);
|
||||
if (!Number.isFinite(n) || n === 0) return setStatus({ ok: false, text: "Adj meg egy nem nulla egész számot." });
|
||||
setBusy(true);
|
||||
setStatus(null);
|
||||
try {
|
||||
const res = await api<{ analyses_left: AdminUser["analyses_left"] }>(`/admin/users/${user.id}/credits`, {
|
||||
body: { unit, delta: n, note: "admin" },
|
||||
});
|
||||
onChange({ ...user, analyses_left: res.analyses_left });
|
||||
setDelta("");
|
||||
const label = UNITS.find((u) => u.value === unit)?.label;
|
||||
setStatus({ ok: true, text: `${n > 0 ? "+" : ""}${n} ${label}.` });
|
||||
} catch (err) {
|
||||
setStatus({ ok: false, text: errorText(err) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={grant} className="modal-section">
|
||||
<fieldset>
|
||||
<legend>Részletes elemzések</legend>
|
||||
<dl className="balance-grid">
|
||||
{UNITS.map((u) => (
|
||||
<div key={u.value}>
|
||||
<dt>{u.label}</dt>
|
||||
<dd className="num">{user.analyses_left[u.value] ?? 0}</dd>
|
||||
</div>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit" className="btn btn-sm" disabled={busy || !id}>
|
||||
{busy ? "…" : "Kiosztás"}
|
||||
</button>
|
||||
</div>
|
||||
{status && (
|
||||
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
|
||||
{status.text}
|
||||
</span>
|
||||
)}
|
||||
</dl>
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<label className="sr-only" htmlFor={`unit-${user.id}`}>
|
||||
Elemzés fajtája
|
||||
</label>
|
||||
<select
|
||||
id={`unit-${user.id}`}
|
||||
className="inp"
|
||||
style={{ flex: "1 1 150px", minHeight: 40 }}
|
||||
value={unit}
|
||||
onChange={(e) => setUnit(e.target.value as UnitKind)}
|
||||
>
|
||||
{UNITS.map((u) => (
|
||||
<option key={u.value} value={u.value}>
|
||||
{u.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="sr-only" htmlFor={`delta-${user.id}`}>
|
||||
Darabszám (negatív: elvétel)
|
||||
</label>
|
||||
<input
|
||||
id={`delta-${user.id}`}
|
||||
className="inp"
|
||||
style={{ width: 90, minHeight: 40 }}
|
||||
inputMode="numeric"
|
||||
placeholder="+1"
|
||||
value={delta}
|
||||
onChange={(e) => setDelta(e.target.value)}
|
||||
/>
|
||||
<button type="submit" className="btn btn-sm" disabled={busy || !delta}>
|
||||
Jóváír
|
||||
</button>
|
||||
</div>
|
||||
<p className="muted modal-hint">Negatív számmal el is vehetsz (pl. -1).</p>
|
||||
{status && (
|
||||
<span className={status.ok ? "msg msg-ok" : "msg msg-error"} role="status">
|
||||
{status.text}
|
||||
</span>
|
||||
)}
|
||||
</fieldset>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { api, errorText } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import type { GenerationError } from "@/lib/types";
|
||||
|
||||
const PAGE = 100;
|
||||
const PAGE = 50;
|
||||
|
||||
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
||||
const KINDS: Record<string, string> = {
|
||||
@@ -33,43 +33,82 @@ interface Page {
|
||||
export function ErrorLog() {
|
||||
const [source, setSource] = useState("");
|
||||
const [outcome, setOutcome] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const [errors, setErrors] = useState<GenerationError[] | null>(null);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [lastDay, setLastDay] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
async (offset: number) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const params = new URLSearchParams({ limit: String(PAGE), offset: String(offset) });
|
||||
if (source) params.set("source", source);
|
||||
if (outcome) params.set("outcome", outcome);
|
||||
try {
|
||||
const page = await api<Page>(`/admin/errors?${params}`);
|
||||
setErrors((all) => (offset === 0 ? page.errors : [...(all ?? []), ...page.errors]));
|
||||
setTotal(page.total);
|
||||
setLastDay(page.last_day);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[source, outcome],
|
||||
);
|
||||
const filter = useCallback(() => {
|
||||
const params = new URLSearchParams();
|
||||
if (source) params.set("source", source);
|
||||
if (outcome) params.set("outcome", outcome);
|
||||
return params;
|
||||
}, [source, outcome]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const params = filter();
|
||||
params.set("limit", String(PAGE));
|
||||
params.set("offset", String(page * PAGE));
|
||||
try {
|
||||
const res = await api<Page>(`/admin/errors?${params}`);
|
||||
// The last page emptied by deleting: one page back.
|
||||
if (res.errors.length === 0 && page > 0) return setPage(Math.max(0, Math.ceil(res.total / PAGE) - 1));
|
||||
setErrors(res.errors);
|
||||
setTotal(res.total);
|
||||
setLastDay(res.last_day);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [filter, page]);
|
||||
|
||||
useEffect(() => {
|
||||
load(0);
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
async function removeOne(id: number) {
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/admin/errors/${id}`, { method: "DELETE" });
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMatching() {
|
||||
const what = source || outcome ? `a szűrésnek megfelelő ${total} bejegyzést` : `mind a ${total} bejegyzést`;
|
||||
if (!window.confirm(`Biztosan törlöd ${what}? Nem vonható vissza.`)) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/admin/errors?${filter()}`, { method: "DELETE" });
|
||||
setPage(0);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const pages = Math.max(1, Math.ceil(total / PAGE));
|
||||
|
||||
return (
|
||||
<section className="card" style={{ gap: 12 }}>
|
||||
<div className="row" style={{ gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
|
||||
<div className="field">
|
||||
<label htmlFor="error-source">Mi</label>
|
||||
<select id="error-source" className="inp" value={source} onChange={(e) => setSource(e.target.value)}>
|
||||
<select id="error-source" className="inp" value={source} onChange={(e) => {
|
||||
setSource(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<option value="">mind</option>
|
||||
{Object.entries(SOURCES).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
@@ -80,7 +119,11 @@ export function ErrorLog() {
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="error-outcome">Következmény</label>
|
||||
<select id="error-outcome" className="inp" value={outcome} onChange={(e) => setOutcome(e.target.value)}>
|
||||
<select id="error-outcome" className="inp" value={outcome} onChange={(e) => {
|
||||
setOutcome(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<option value="">mind</option>
|
||||
{Object.entries(OUTCOMES).map(([v, o]) => (
|
||||
<option key={v} value={v}>
|
||||
@@ -92,9 +135,14 @@ export function ErrorLog() {
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
{total} bejegyzés, ebből {lastDay} az elmúlt 24 órában
|
||||
</p>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => load(0)} disabled={busy}>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={load} disabled={busy}>
|
||||
Frissítés
|
||||
</button>
|
||||
{total > 0 && (
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={removeMatching} disabled={busy}>
|
||||
{source || outcome ? `A szűrt ${total} törlése` : `Mind a ${total} törlése`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
@@ -116,6 +164,9 @@ export function ErrorLog() {
|
||||
<th>Kísérlet</th>
|
||||
<th>Következmény</th>
|
||||
<th>Hiba</th>
|
||||
<th>
|
||||
<span className="sr-only">Törlés</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -140,16 +191,40 @@ export function ErrorLog() {
|
||||
<span className={`outcome tone-${OUTCOMES[e.outcome].tone}`}>{OUTCOMES[e.outcome].label}</span>
|
||||
</td>
|
||||
<td className="error-text">{e.error}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => removeOne(e.id)}
|
||||
aria-label="Bejegyzés törlése"
|
||||
title="Bejegyzés törlése"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{errors && errors.length < total && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => load(errors.length)} disabled={busy}>
|
||||
{busy ? "Betöltés…" : "Régebbiek"}
|
||||
</button>
|
||||
{total > PAGE && (
|
||||
<nav className="pager" aria-label="Lapozás">
|
||||
<button type="button" className="btn btn-sm" disabled={busy || page === 0} onClick={() => setPage(page - 1)}>
|
||||
‹ Újabbak
|
||||
</button>
|
||||
<span className="num">
|
||||
{page * PAGE + 1}–{Math.min(total, (page + 1) * PAGE)} / {total} · {page + 1}/{pages}. oldal
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
disabled={busy || page + 1 >= pages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
>
|
||||
Régebbiek ›
|
||||
</button>
|
||||
</nav>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { BirthForm } from "@/app/profil/BirthForm";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
@@ -24,11 +24,19 @@ export function AdminCelebrities() {
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [subtitle, setSubtitle] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const load = useCallback(() => {
|
||||
api<{ celebrities: AdminCelebrityRow[] }>("/admin/celebrities")
|
||||
.then((r) => setRows(r.celebrities))
|
||||
.catch((e) => setError(errorText(e)));
|
||||
}, []);
|
||||
useEffect(load, [load]);
|
||||
// A portrait being written: look again now and then.
|
||||
const writing = rows?.some((c) => c.analysis_status === "pending" || c.analysis_status === "running");
|
||||
useEffect(() => {
|
||||
if (!writing) return;
|
||||
const t = setInterval(load, 10_000);
|
||||
return () => clearInterval(t);
|
||||
}, [writing, load]);
|
||||
|
||||
return (
|
||||
<section className="field" style={{ gap: 18 }}>
|
||||
|
||||
@@ -17,7 +17,7 @@ import { ANALYSIS_STATUS, SubtitleField } from "../AdminCelebrities";
|
||||
const POLL_MS = 10_000;
|
||||
|
||||
/** Everything about one famous person: photo and face point, texts, publishing, portrait, birth data. */
|
||||
export function CelebrityEditor({ id }: { id: string }) {
|
||||
export function CelebrityEditor({ id, selfId, isAdmin }: { id: string; selfId: string; isAdmin: boolean }) {
|
||||
const router = useRouter();
|
||||
const [c, setC] = useState<AdminCelebrity | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -130,12 +130,18 @@ export function CelebrityEditor({ id }: { id: string }) {
|
||||
|
||||
<section className="card field" style={{ gap: 10 }}>
|
||||
<h2>Törlés</h2>
|
||||
<p className="hint">A képlet, a portré és a fotó is törlődik; a nyilvános oldal megszűnik.</p>
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-ghost" onClick={remove}>
|
||||
{c.name} törlése
|
||||
</button>
|
||||
</div>
|
||||
{isAdmin || c.created_by === selfId ? (
|
||||
<>
|
||||
<p className="hint">A képlet, a portré és a fotó is törlődik; a nyilvános oldal megszűnik.</p>
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-ghost" onClick={remove}>
|
||||
{c.name} törlése
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="hint">Akit más vitt fel, azt csak admin törölheti.</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
@@ -382,7 +388,7 @@ function AnalysisSection({
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)}>
|
||||
{open ? "Szöveg elrejtése" : "Szöveg megnézése"}
|
||||
</button>
|
||||
<RegenerateButton<Analysis> url={`/admin/analyses/${a.id}/regenerate`} onStarted={onAnalysis} />
|
||||
<RegenerateButton<Analysis> url={`${url}/analysis/regenerate`} onStarted={onAnalysis} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { AdminNav, canEditCelebrities } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { CelebrityEditor } from "./CelebrityEditor";
|
||||
@@ -13,11 +13,11 @@ type Props = { params: Promise<{ id: string }> };
|
||||
export default async function AdminCelebrityPage({ params }: Props) {
|
||||
const { id } = await params;
|
||||
const me = await requireMe(`/admin/hires-emberek/${id}`);
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
if (!canEditCelebrities(me.user.roles)) notFound();
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<AdminNav current="/admin/hires-emberek" />
|
||||
<CelebrityEditor id={id} />
|
||||
<AdminNav current="/admin/hires-emberek" roles={me.user.roles} />
|
||||
<CelebrityEditor id={id} selfId={me.user.id} isAdmin={me.user.roles.includes("admin")} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { AdminNav, canEditCelebrities } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { AdminCelebrities } from "./AdminCelebrities";
|
||||
@@ -10,10 +10,10 @@ export const metadata: Metadata = { title: "Híres emberek" };
|
||||
|
||||
export default async function AdminCelebritiesPage() {
|
||||
const me = await requireMe("/admin/hires-emberek");
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
if (!canEditCelebrities(me.user.roles)) notFound();
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<AdminNav current="/admin/hires-emberek" />
|
||||
<AdminNav current="/admin/hires-emberek" roles={me.user.roles} />
|
||||
<div className="page-head">
|
||||
<h1>Híres emberek</h1>
|
||||
<p className="muted">
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { usePackages } from "@/components/PackageCards";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types";
|
||||
import type { AdminInvitation, InvitationResult } from "@/lib/types";
|
||||
|
||||
const MAX_MESSAGE = 300;
|
||||
|
||||
@@ -33,7 +33,6 @@ const RESULT: Record<InvitationResult["status"], string> = {
|
||||
|
||||
interface ListData {
|
||||
invitations: AdminInvitation[];
|
||||
waitlist: WaitlistEntry[];
|
||||
signup_mode: "invite" | "open";
|
||||
}
|
||||
|
||||
@@ -96,7 +95,6 @@ export function AdminInvitations() {
|
||||
</p>
|
||||
)}
|
||||
{data && <InvitationList invitations={data.invitations} onChange={load} />}
|
||||
{data && <WaitlistTable waitlist={data.waitlist} onChange={load} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -399,117 +397,3 @@ function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitatio
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onChange: () => Promise<void> }) {
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [pkg, setPkg] = useState("");
|
||||
const packages = usePackages();
|
||||
|
||||
async function invite(w: WaitlistEntry) {
|
||||
setBusy(w.email);
|
||||
setNote(null);
|
||||
try {
|
||||
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
|
||||
body: { emails: [w.email], locale: w.locale, package: pkg || null },
|
||||
});
|
||||
const r = res.results[0];
|
||||
if (r && r.status !== "invited") setNote(`${r.email}: ${RESULT[r.status]}`);
|
||||
await onChange();
|
||||
} catch (e) {
|
||||
setNote(errorText(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(w: WaitlistEntry) {
|
||||
setBusy(w.email);
|
||||
setNote(null);
|
||||
try {
|
||||
await api(`/admin/waitlist/${encodeURIComponent(w.email)}`, { method: "DELETE" });
|
||||
await onChange();
|
||||
} catch (e) {
|
||||
setNote(errorText(e));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card" aria-labelledby="waitlist-title">
|
||||
<h2 id="waitlist-title" style={{ marginTop: 0 }}>
|
||||
Várólista
|
||||
</h2>
|
||||
<p className="hint">Akik meghívó nélkül próbáltak belépni, és kérték, hogy szóljunk nekik.</p>
|
||||
{waitlist.some((w) => w.invitation === null) && (
|
||||
<div className="field" style={{ maxWidth: 320 }}>
|
||||
<label htmlFor="waitlist-package">Ajándék csomag a meghívottaknak</label>
|
||||
<select id="waitlist-package" className="inp" value={pkg} onChange={(e) => setPkg(e.target.value)}>
|
||||
<option value="">nincs</option>
|
||||
{(packages ?? []).map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="hint">A „Meghívás” gomb ezzel a csomaggal küldi a meghívót; a regisztrációkor magától jóváíródik.</span>
|
||||
</div>
|
||||
)}
|
||||
{note && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{note}
|
||||
</p>
|
||||
)}
|
||||
{waitlist.length === 0 ? (
|
||||
<p className="muted">Üres.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Cím</th>
|
||||
<th scope="col">Feliratkozott</th>
|
||||
<th scope="col">Meghívó</th>
|
||||
<th scope="col">
|
||||
<span className="sr-only">Műveletek</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{waitlist.map((w) => (
|
||||
<tr key={w.email}>
|
||||
<td>{w.email}</td>
|
||||
<td className="num">{formatDate(w.created_at)}</td>
|
||||
<td>{w.invitation === "pending" ? "elküldve" : w.invitation === "accepted" ? "elfogadva" : "–"}</td>
|
||||
<td>
|
||||
<div className="row" style={{ gap: 4, flexWrap: "nowrap", justifyContent: "flex-end" }}>
|
||||
{w.invitation === null && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm"
|
||||
onClick={() => invite(w)}
|
||||
disabled={busy !== null}
|
||||
>
|
||||
Meghívás
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={() => remove(w)}
|
||||
disabled={busy !== null}
|
||||
>
|
||||
Törlés
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import Script from "next/script";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Waitlist } from "@/components/Waitlist";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
|
||||
/** The part of Sign in with Apple JS (appleid.auth.js) we use. */
|
||||
@@ -136,7 +135,6 @@ export function AppleLogin({
|
||||
? "Ez a meghívó már nem érvényes, és ehhez az Apple-fiókhoz sem tartozik másik."
|
||||
: "A Sorsfonalak jelenleg meghívásos, és ehhez az Apple-fiókhoz nem tartozik meghívó. Ha kaptál meghívót, nyisd meg a levélben kapott linket, vagy lépj be azzal a fiókkal, amelynek a címére a meghívó szólt."}
|
||||
</p>
|
||||
<Waitlist email={uninvited.endsWith("@privaterelay.appleid.com") ? "" : uninvited} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,6 @@ import Script from "next/script";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Waitlist } from "@/components/Waitlist";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
|
||||
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
|
||||
@@ -130,7 +129,6 @@ export function GoogleLogin({
|
||||
? "Ez a meghívó már nem érvényes, és ehhez a Google-fiókhoz sem tartozik másik."
|
||||
: `A Sorsfonalak jelenleg meghívásos, és ${uninvited ? `a(z) ${uninvited} címhez` : "ehhez a fiókhoz"} nem tartozik meghívó. Ha kaptál meghívót egy másik címre, lépj be azzal a Google-fiókkal, vagy nyisd meg a levélben kapott linket.`}
|
||||
</p>
|
||||
<Waitlist email={uninvited} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Waitlist } from "@/components/Waitlist";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
|
||||
type Mode = "login" | "register" | "forgot";
|
||||
@@ -178,7 +177,6 @@ export function PasswordLogin({
|
||||
? "Ez a meghívó már nem érvényes, és ehhez a címhez sem tartozik másik."
|
||||
: "A Sorsfonalak jelenleg meghívásos, és ehhez az e-mail-címhez nem tartozik meghívó. Ha kaptál meghívót, nyisd meg a levélben kapott linket."}
|
||||
</p>
|
||||
<Waitlist email={email} />
|
||||
</>
|
||||
)}
|
||||
<p className="hint pw-switch" style={{ margin: 0 }}>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Logo } from "@/components/SiteHeader";
|
||||
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
||||
import { BACKEND_URL, getMe } from "@/lib/server";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import { contents } from "@/lib/packageContents";
|
||||
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
||||
|
||||
import { AppleLogin } from "./AppleLogin";
|
||||
@@ -21,7 +22,8 @@ export const metadata: Metadata = { title: "Belépés" };
|
||||
*/
|
||||
function safeTarget(value: string | string[] | undefined): string {
|
||||
const v = Array.isArray(value) ? value[0] : value;
|
||||
return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/";
|
||||
// By default to the user's chart (or to the profile for their birth data).
|
||||
return v && /^\/(?![/\\])[^\\\u0000-\u001f]*$/.test(v) ? v : "/keplet";
|
||||
}
|
||||
|
||||
async function loadConfig(): Promise<PublicConfig | null> {
|
||||
@@ -79,6 +81,19 @@ function InvitationCard({
|
||||
{invitation.inviter_name ? <strong>{invitation.inviter_name}</strong> : "Valaki"} meghívott a Sorsfonalakra.
|
||||
</p>
|
||||
{invitation.message && <blockquote className="invite-quote">{invitation.message}</blockquote>}
|
||||
{invitation.gift && (
|
||||
<div className="invite-gift">
|
||||
<p style={{ margin: 0 }}>
|
||||
Ajándékba kapod a <strong>„{invitation.gift.name}”</strong> csomagot, a regisztrációval magától
|
||||
jóváíródik:
|
||||
</p>
|
||||
<ul>
|
||||
{contents(invitation.gift).map((line) => (
|
||||
<li key={line}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"}
|
||||
{password ? ", vagy e-mail-címmel regisztrálva" : ""} elfogadhatod. Érvényes:{" "}
|
||||
|
||||
@@ -118,9 +118,6 @@ export default async function SignPage({ params }: { params: Promise<{ jegy: str
|
||||
<aside className="card sign-cta">
|
||||
<p style={{ margin: 0 }}>{z.offer}</p>
|
||||
<div className="form-actions">
|
||||
<Link href="/szuletesi-horoszkop" className="btn">
|
||||
Ingyenes születési horoszkóp
|
||||
</Link>
|
||||
<Link href={me ? "/keplet" : "/belepes?mod=regisztracio&vissza=/profil"} className="btn btn-primary">
|
||||
{me ? "A saját képletem" : "A teljes képletem ingyen"}
|
||||
</Link>
|
||||
|
||||
@@ -45,17 +45,6 @@ export default async function SignsPage() {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="card sign-cta" style={{ marginTop: 32 }}>
|
||||
<p style={{ margin: 0 }}>
|
||||
Nem tudod, melyik jegyben áll a Holdad, vagy mi az aszcendensed? Az ingyenes születési horoszkóp a születési
|
||||
adataidból kiszámolja, belépés nélkül.
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link href="/szuletesi-horoszkop" className="btn btn-primary">
|
||||
Ingyenes születési horoszkóp
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
|
||||
@@ -180,7 +180,8 @@ textarea.inp { padding: 12px 14px; line-height: 1.55; min-height: 96px; resize:
|
||||
.combo-list small { color: var(--muted); }
|
||||
|
||||
/* Tables */
|
||||
.table-wrap { overflow-x: auto; }
|
||||
/* relative: absolutely placed children (e.g. .sr-only) stay clipped inside. */
|
||||
.table-wrap { overflow-x: auto; position: relative; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||
th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; }
|
||||
th { color: var(--muted); font-weight: 500; font-size: 13px; }
|
||||
@@ -482,6 +483,36 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
}
|
||||
.admin-nav a:hover { color: var(--ink); }
|
||||
.admin-nav a[aria-current="page"] { color: var(--gold); border-bottom-color: var(--gold); }
|
||||
|
||||
/* Admin: the user list's pager and the user dialog. */
|
||||
.pager { display: flex; align-items: center; justify-content: center; gap: 14px; flex-wrap: wrap; font-size: 14px; color: var(--ink-2); }
|
||||
.admin-users td { vertical-align: middle; }
|
||||
dialog.modal {
|
||||
width: min(560px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); padding: 0; margin: auto;
|
||||
background: var(--panel); color: var(--ink); border: 1px solid var(--line-2); border-radius: 14px;
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
dialog.modal::backdrop { background: rgba(5, 8, 16, 0.72); backdrop-filter: blur(2px); }
|
||||
.modal-inner { display: flex; flex-direction: column; gap: 18px; padding: 22px 24px 24px; }
|
||||
.modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.modal-head h2 { font-size: 26px; line-height: 1.15; overflow-wrap: anywhere; }
|
||||
.modal-sub { font-size: 13px; margin-top: 4px; overflow-wrap: anywhere; }
|
||||
.modal-close {
|
||||
flex: none; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 8px;
|
||||
background: none; border: 1px solid var(--line-2); color: var(--ink-2); cursor: pointer;
|
||||
}
|
||||
.modal-close:hover { color: var(--gold); border-color: var(--gold); }
|
||||
.modal-close svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
|
||||
.modal-section, .modal-section fieldset { border: 0; margin: 0; padding: 0; min-width: 0; }
|
||||
.modal-section { border-top: 1px solid var(--line); padding-top: 16px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.modal-section fieldset { display: flex; flex-direction: column; gap: 10px; }
|
||||
.modal-section legend { font-size: 14px; font-weight: 600; color: var(--ink); padding: 0; margin-bottom: 10px; }
|
||||
.modal-hint { font-size: 13px; margin: 0; }
|
||||
.balance-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 8px; margin: 0; }
|
||||
.balance-grid div { background: var(--panel-2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 10px; }
|
||||
.balance-grid dt { font-size: 12px; color: var(--muted); }
|
||||
.balance-grid dd { margin: 0; font-size: 18px; color: var(--ink); }
|
||||
@media (max-width: 480px) { .modal-inner { padding: 18px 16px 20px; } }
|
||||
.prompt-kind { display: flex; flex-direction: column; gap: 20px; }
|
||||
.prompt-kind-head { display: flex; gap: 16px 24px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; }
|
||||
.prompt-kind-head > p { flex: 1 1 360px; margin: 0; }
|
||||
@@ -627,6 +658,11 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
|
||||
/* Invitations */
|
||||
.invite-card { display: flex; flex-direction: column; gap: 8px; }
|
||||
.invite-gift {
|
||||
border: 1px solid rgba(217, 180, 106, 0.45); background: rgba(217, 180, 106, 0.07); border-radius: 10px;
|
||||
padding: 10px 14px; font-size: 14px;
|
||||
}
|
||||
.invite-gift ul { margin: 6px 0 0; padding-left: 18px; color: var(--ink-2); }
|
||||
.invite-quote {
|
||||
margin: 0; padding: 2px 0 2px 14px; border-left: 3px solid var(--gold);
|
||||
font-style: italic; white-space: pre-line; color: var(--ink);
|
||||
@@ -951,7 +987,6 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
.lp-final-inner { max-width: 820px; display: flex; flex-direction: column; align-items: center; gap: 22px; text-align: center; }
|
||||
.lp-emblem { width: 88px; height: 88px; }
|
||||
.lp-emblem-outer { fill: none; stroke: var(--gold); stroke-opacity: 0.5; stroke-width: 1; }
|
||||
.lp-waitlist { width: 100%; max-width: 520px; text-align: left; }
|
||||
.lp-disclaimer { max-width: 560px; }
|
||||
.lp-footer { border-top: 1px solid var(--line); padding: 28px 0; }
|
||||
.lp-footer-inner { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; justify-content: space-between; }
|
||||
@@ -1249,3 +1284,55 @@ span.tarot-fan-card { cursor: default; }
|
||||
.celeb-tile { padding: 10px; }
|
||||
.celeb-tile strong { font-size: 19px; }
|
||||
}
|
||||
|
||||
/* The ☰ menu: instead of the header's link rows where they no longer fit
|
||||
on one line (logged out below 1240px; logged in below 1380px, with more
|
||||
links and the package). */
|
||||
.mobile-menu { display: none; margin-left: auto; }
|
||||
.mobile-menu-button {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px;
|
||||
background: none; border: 1px solid var(--line-2); border-radius: 10px; color: var(--ink); cursor: pointer;
|
||||
}
|
||||
.mobile-menu-button:hover, .mobile-menu-button[aria-expanded="true"] { color: var(--gold); border-color: #5a6790; }
|
||||
.mobile-menu-button svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
|
||||
.mobile-menu-panel {
|
||||
position: absolute; top: 100%; left: 0; right: 0; z-index: 20;
|
||||
display: flex; flex-direction: column; gap: 6px; padding: 10px 16px 16px;
|
||||
background: rgba(13, 18, 32, 0.98); border-bottom: 1px solid var(--line); box-shadow: 0 16px 32px rgba(0, 0, 0, 0.45);
|
||||
max-height: calc(100vh - 70px); overflow-y: auto;
|
||||
}
|
||||
.mobile-menu-group { display: flex; flex-direction: column; }
|
||||
.mobile-menu-group + .mobile-menu-group { border-top: 1px solid var(--line); padding-top: 10px; }
|
||||
.mobile-menu-group .lp-free-label { align-self: flex-start; margin: 2px 0 6px 12px; }
|
||||
.mobile-menu-panel a { color: var(--ink-2); text-decoration: none; padding: 12px; border-radius: 8px; font-size: 17px; min-height: 44px; display: flex; align-items: center; }
|
||||
.mobile-menu-panel a:hover, .mobile-menu-panel a[aria-current="page"] { color: var(--gold); background: rgba(217, 180, 106, 0.08); }
|
||||
@media (max-width: 1240px) {
|
||||
.mobile-menu-public { display: block; }
|
||||
.lp-header .lp-nav, .lp-header .lp-free { display: none; }
|
||||
.lp-header > .btn { margin-left: auto; }
|
||||
.lp-header > .btn + .mobile-menu { margin-left: 0; }
|
||||
}
|
||||
@media (max-width: 1500px) {
|
||||
.site-header .pkg-pill-detail { display: none; }
|
||||
}
|
||||
@media (max-width: 1380px) {
|
||||
.mobile-menu-app { display: block; }
|
||||
.site-header .app-nav { display: none; }
|
||||
.site-header .who { margin-left: auto; }
|
||||
.site-header .who + .mobile-menu { margin-left: 0; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
/* Logo, account and ☰ on one line: the name only as an icon. */
|
||||
.site-header { flex-wrap: nowrap; }
|
||||
.site-header .who { flex-wrap: nowrap; gap: 8px; min-width: 0; }
|
||||
.site-header .who-name-text, .site-header .pkg-pill-detail { display: none; }
|
||||
.site-header .who-name { padding: 0 10px; }
|
||||
}
|
||||
@media (max-width: 460px) {
|
||||
/* No room for the package next to the account and ☰ (the menu has Csomagok). */
|
||||
.site-header .pkg-pill { display: none; }
|
||||
}
|
||||
@media (max-width: 380px) {
|
||||
.site-header { gap: 8px; padding-left: 12px; padding-right: 12px; }
|
||||
.logo { font-size: 22px; }
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export default async function CelebritiesPage() {
|
||||
const [people, me] = await Promise.all([loadCelebrities(), getMe()]);
|
||||
return (
|
||||
<>
|
||||
{!me && <PublicHeader />}
|
||||
{!me && <PublicHeader current="hires" />}
|
||||
<main className="page" style={{ maxWidth: 1080 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Híres emberek</span>
|
||||
@@ -68,17 +68,6 @@ export default async function CelebritiesPage() {
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="card sign-cta" style={{ marginTop: 32 }}>
|
||||
<p style={{ margin: 0 }}>
|
||||
Kíváncsi vagy a saját képletedre? Az ingyenes születési horoszkóp a születési adataidból kiszámolja, belépés
|
||||
nélkül.
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<Link href="/szuletesi-horoszkop" className="btn btn-primary">
|
||||
Ingyenes születési horoszkóp
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<PublicFooter />
|
||||
</>
|
||||
|
||||
@@ -29,7 +29,7 @@ export function SetPasswordForm({ token, minLength }: { token: string; minLength
|
||||
setBusy(true);
|
||||
try {
|
||||
await api("/auth/set-password", { body: { token, password } });
|
||||
router.replace("/");
|
||||
router.replace("/keplet");
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.code === "invalid_token") setExpired(true);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Metadata } from "next";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { JsonLd } from "@/components/PublicFooter";
|
||||
import { OPERATOR } from "@/lib/legal";
|
||||
@@ -42,14 +41,13 @@ async function signupMode(): Promise<PublicConfig["signup_mode"]> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Visitors get the home page; logged-in users go to their chart (or to the profile for their birth data). */
|
||||
/** The home page, for visitors and logged-in users alike (they get the app's header and a link to their chart). */
|
||||
export default async function Home() {
|
||||
const me = await getMe();
|
||||
if (me) redirect(me.primary_chart_id ? "/keplet" : "/profil");
|
||||
const base = await siteUrl();
|
||||
return (
|
||||
<>
|
||||
<Landing inviteOnly={(await signupMode()) !== "open"} />
|
||||
<Landing inviteOnly={(await signupMode()) !== "open"} loggedIn={me !== null} />
|
||||
<JsonLd
|
||||
data={{
|
||||
"@context": "https://schema.org",
|
||||
|
||||
@@ -1,20 +1,28 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import type { Role } from "@/lib/types";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/admin", label: "Felhasználók" },
|
||||
{ href: "/admin/meghivok", label: "Meghívók" },
|
||||
{ href: "/admin/promokodok", label: "Promókódok" },
|
||||
{ href: "/admin/hires-emberek", label: "Híres emberek" },
|
||||
{ href: "/admin/hires-emberek", label: "Híres emberek", creator: true },
|
||||
{ href: "/admin/promptok", label: "Promptok" },
|
||||
{ href: "/admin/modellek", label: "Modellek" },
|
||||
{ href: "/admin/hibak", label: "Hibanapló" },
|
||||
];
|
||||
|
||||
/** Switches between the admin pages. */
|
||||
export function AdminNav({ current }: { current: string }) {
|
||||
/** May manage the famous people (an admin or a creator). */
|
||||
export function canEditCelebrities(roles: Role[]): boolean {
|
||||
return roles.includes("admin") || roles.includes("creator");
|
||||
}
|
||||
|
||||
/** Switches between the admin pages (a creator who is no admin: only theirs). */
|
||||
export function AdminNav({ current, roles }: { current: string; roles?: Role[] }) {
|
||||
const admin = !roles || roles.includes("admin");
|
||||
return (
|
||||
<nav className="admin-nav" aria-label="Admin oldalak">
|
||||
{PAGES.map((p) => (
|
||||
{PAGES.filter((p) => admin || ("creator" in p && p.creator)).map((p) => (
|
||||
<Link key={p.href} href={p.href} aria-current={p.href === current ? "page" : undefined}>
|
||||
{p.label}
|
||||
</Link>
|
||||
|
||||
@@ -56,7 +56,6 @@ export function InvitePerson() {
|
||||
}
|
||||
|
||||
if (created) {
|
||||
const text = `Nézzük meg, mennyire illünk össze! ${created.url}`;
|
||||
return (
|
||||
<div className="field invite-done" style={{ gap: 12 }}>
|
||||
<p className="msg msg-ok" role="status">
|
||||
@@ -79,26 +78,6 @@ export function InvitePerson() {
|
||||
</button>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
{typeof navigator !== "undefined" && "share" in navigator && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => navigator.share({ text: "Nézzük meg, mennyire illünk össze!", url: created.url }).catch(() => {})}
|
||||
>
|
||||
Küldés…
|
||||
</button>
|
||||
)}
|
||||
<a className="btn btn-sm" href={`https://wa.me/?text=${encodeURIComponent(text)}`} target="_blank" rel="noopener noreferrer">
|
||||
WhatsApp
|
||||
</a>
|
||||
<a
|
||||
className="btn btn-sm"
|
||||
href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(created.url)}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Facebook
|
||||
</a>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setCreated(null)}>
|
||||
Újabb meghívó
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
|
||||
export interface MenuSection {
|
||||
/** A small heading above the group (e.g. "Ingyenes"). */
|
||||
title?: string;
|
||||
links: { href: string; label: string }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The menu behind the ☰ button on narrow screens (the header's link rows are
|
||||
* hidden there, see globals.css). Closes on a click outside, Escape, or
|
||||
* moving to another page. `className` sets the width from which it shows.
|
||||
*/
|
||||
export function MobileMenu({ sections, className }: { sections: MenuSection[]; className: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
const panelId = useId();
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => setOpen(false), [pathname]);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (e: PointerEvent) => {
|
||||
if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
const escape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
button.current?.focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener("pointerdown", outside);
|
||||
document.addEventListener("keydown", escape);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", outside);
|
||||
document.removeEventListener("keydown", escape);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const current = (href: string) => !href.includes("#") && pathname.startsWith(href);
|
||||
|
||||
return (
|
||||
<div className={`mobile-menu ${className}`} ref={box}>
|
||||
<button
|
||||
ref={button}
|
||||
type="button"
|
||||
className="mobile-menu-button"
|
||||
aria-expanded={open}
|
||||
aria-controls={panelId}
|
||||
aria-label={open ? "Menü bezárása" : "Menü"}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
{open ? <path d="M6 6l12 12M18 6L6 18" /> : <path d="M4 7h16M4 12h16M4 17h16" />}
|
||||
</svg>
|
||||
</button>
|
||||
{open && (
|
||||
<nav id={panelId} className="mobile-menu-panel" aria-label="Menü">
|
||||
{sections.map((s, i) => (
|
||||
<div key={i} className="mobile-menu-group">
|
||||
{s.title && <span className="lp-free-label">{s.title}</span>}
|
||||
{s.links.map((l) => (
|
||||
<Link
|
||||
key={l.href}
|
||||
href={l.href}
|
||||
aria-current={current(l.href) ? "page" : undefined}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{l.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useRef } from "react";
|
||||
|
||||
/**
|
||||
* A modal window (the browser's own <dialog>: focus stays inside, Escape
|
||||
* closes it). Shown while mounted; a click on the dimmed backdrop closes it.
|
||||
*/
|
||||
export function Modal({
|
||||
title,
|
||||
subtitle,
|
||||
onClose,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: React.ReactNode;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
const titleId = useId();
|
||||
|
||||
// No close() on unmount: that would fire onClose; a removed dialog is gone anyway.
|
||||
useEffect(() => {
|
||||
const dialog = ref.current;
|
||||
if (dialog && !dialog.open) dialog.showModal();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
className="modal"
|
||||
aria-labelledby={titleId}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
if (e.target === ref.current) onClose();
|
||||
}}
|
||||
>
|
||||
<div className="modal-inner">
|
||||
<div className="modal-head">
|
||||
<div>
|
||||
<h2 id={titleId}>{title}</h2>
|
||||
{subtitle && <div className="muted modal-sub">{subtitle}</div>}
|
||||
</div>
|
||||
<button type="button" className="modal-close" onClick={onClose} aria-label="Bezárás">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M6 6l12 12M18 6L6 18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { usePathname } from "next/navigation";
|
||||
export function NavLinks({ links }: { links: { href: string; label: string }[] }) {
|
||||
const pathname = usePathname();
|
||||
return (
|
||||
<nav className="nav" aria-label="Fő navigáció">
|
||||
<nav className="nav app-nav" aria-label="Fő navigáció">
|
||||
{links.map((l) => (
|
||||
<Link key={l.href} href={l.href} aria-current={pathname.startsWith(l.href) ? "page" : undefined}>
|
||||
{l.label}
|
||||
|
||||
@@ -5,22 +5,11 @@ import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { contents } from "@/lib/packageContents";
|
||||
import type { Package, PayMethod, PublicConfig } from "@/lib/types";
|
||||
|
||||
export const huf = (n: number) => `${n.toLocaleString("hu-HU")} Ft`;
|
||||
|
||||
/** What a package contains, as short lines. */
|
||||
export function contents(p: Package): string[] {
|
||||
const lines: string[] = [];
|
||||
if (p.natal) lines.push(`${p.natal} részletes képletelemzés`);
|
||||
if (p.synastry) lines.push(`${p.synastry} kapcsolati elemzés`);
|
||||
if (p.forecast) lines.push(`${p.forecast} éves előrejelzés`);
|
||||
if (p.persons) lines.push(`${p.persons} személy felvétele`);
|
||||
if (p.questions) lines.push(`${p.questions} kérdés az elemzéseidről`);
|
||||
if (p.tarot) lines.push(`${p.tarot} kártyajóslás`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Package cards with a buy button. Bigger packages show what they save and
|
||||
* how little more they cost than the previous one. With Stripe the button
|
||||
|
||||
@@ -2,6 +2,7 @@ import Link from "next/link";
|
||||
|
||||
import type { Me } from "@/lib/types";
|
||||
|
||||
import { MobileMenu } from "./MobileMenu";
|
||||
import { NavLinks } from "./NavLinks";
|
||||
import { UserMenu } from "./UserMenu";
|
||||
|
||||
@@ -40,7 +41,7 @@ export function PublicHeader({
|
||||
current,
|
||||
}: {
|
||||
onHome?: boolean;
|
||||
current?: "pelda" | "horoszkop" | "csillagjegyek";
|
||||
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires";
|
||||
}) {
|
||||
const home = onHome ? "" : "/";
|
||||
const here = (page: typeof current) => (current === page ? "page" : undefined);
|
||||
@@ -63,10 +64,34 @@ export function PublicHeader({
|
||||
<Link href="/csillagjegyek" aria-current={here("csillagjegyek")}>
|
||||
Csillagjegyek
|
||||
</Link>
|
||||
<Link href="/hires-emberek" aria-current={here("hires")}>
|
||||
Híres emberek
|
||||
</Link>
|
||||
</nav>
|
||||
<Link href="/belepes" className="btn btn-sm">
|
||||
Belépés
|
||||
</Link>
|
||||
<MobileMenu
|
||||
className="mobile-menu-public"
|
||||
sections={[
|
||||
{
|
||||
links: [
|
||||
{ href: `${home}#elemzes`, label: "Elemzés" },
|
||||
{ href: `${home}#elorejelzes`, label: "Előrejelzés" },
|
||||
{ href: `${home}#osszevetes`, label: "Összevetés" },
|
||||
{ href: "/pelda", label: "Példa" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Ingyenes",
|
||||
links: [
|
||||
{ href: "/szuletesi-horoszkop", label: "Születési horoszkóp" },
|
||||
{ href: "/csillagjegyek", label: "Csillagjegyek" },
|
||||
{ href: "/hires-emberek", label: "Híres emberek" },
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -108,9 +133,11 @@ export function SiteHeader({ me }: { me: Me }) {
|
||||
{ href: "/osszevetesek", label: "Összevetések" },
|
||||
{ href: "/kartyajoslas", label: "Kártyajóslás" },
|
||||
{ href: "/csillagjegyek", label: "Csillagjegyek" },
|
||||
{ href: "/hires-emberek", label: "Híres emberek" },
|
||||
{ href: "/csomagok", label: "Csomagok" },
|
||||
];
|
||||
if (me.user.roles.includes("admin")) links.push({ href: "/admin", label: "Admin" });
|
||||
else if (me.user.roles.includes("creator")) links.push({ href: "/admin/hires-emberek", label: "Szerző" });
|
||||
return (
|
||||
<header className="site-header">
|
||||
<Logo />
|
||||
@@ -119,6 +146,7 @@ export function SiteHeader({ me }: { me: Me }) {
|
||||
<PackageBadge me={me} />
|
||||
<UserMenu name={me.user.display_name || me.user.email} invoices={me.invoice_count > 0} />
|
||||
</div>
|
||||
<MobileMenu className="mobile-menu-app" sections={[{ links }]} />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** "Tell me when it opens": for visitors without an invitation. */
|
||||
export function Waitlist({ email: initial = "" }: { email?: string }) {
|
||||
const [email, setEmail] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [done, setDone] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api("/public/waitlist", { body: { email, locale: "hu" } });
|
||||
setDone(true);
|
||||
} catch (err) {
|
||||
setError(errorText(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<p className="msg msg-ok" role="status">
|
||||
Felírtunk. Ha megnyílik az oldal, vagy meghívót küldünk, ide írunk: <strong>{email}</strong>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form onSubmit={submit} className="card waitlist">
|
||||
<p style={{ margin: 0 }}>
|
||||
<strong>Szólunk, ha megnyílik.</strong>{" "}
|
||||
<span className="muted">Add meg az e-mail-címed, és felírunk a várólistára.</span>
|
||||
</p>
|
||||
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
||||
<label htmlFor="waitlist-email" className="sr-only">
|
||||
E-mail-cím
|
||||
</label>
|
||||
<input
|
||||
id="waitlist-email"
|
||||
className="inp"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="nev@pelda.hu"
|
||||
style={{ flex: "1 1 220px" }}
|
||||
/>
|
||||
<button type="submit" className="btn" disabled={busy}>
|
||||
{busy ? "Küldés…" : "Feliratkozom"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,14 @@ export const loadCelebrity = cache(async (slug: string): Promise<PublicCelebrity
|
||||
const res = await fetch(`${BACKEND_URL}/v1/public/celebrities/${slug}`, {
|
||||
next: { revalidate: 300, tags: [CELEBRITIES_TAG] },
|
||||
});
|
||||
if (res.ok) return (await res.json()) as PublicCelebrity;
|
||||
if (res.ok) {
|
||||
const c = (await res.json()) as PublicCelebrity;
|
||||
if (c.analysis) return c;
|
||||
// The portrait is still being written (the worker does not clear the
|
||||
// cache when it is done): no cached copy until it is there.
|
||||
const fresh = await fetch(`${BACKEND_URL}/v1/public/celebrities/${slug}`, { cache: "no-store" });
|
||||
return fresh.ok ? ((await fresh.json()) as PublicCelebrity) : c;
|
||||
}
|
||||
if (res.status !== 404) throw new Error(`celebrity ${slug}: HTTP ${res.status}`);
|
||||
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Package } from "./types";
|
||||
|
||||
/** What a package contains, as short lines. */
|
||||
export function contents(p: Package): string[] {
|
||||
const lines: string[] = [];
|
||||
if (p.natal) lines.push(`${p.natal} részletes képletelemzés`);
|
||||
if (p.synastry) lines.push(`${p.synastry} kapcsolati elemzés`);
|
||||
if (p.forecast) lines.push(`${p.forecast} éves előrejelzés`);
|
||||
if (p.persons) lines.push(`${p.persons} személy felvétele`);
|
||||
if (p.questions) lines.push(`${p.questions} kérdés az elemzéseidről`);
|
||||
if (p.tarot) lines.push(`${p.tarot} kártyajóslás`);
|
||||
return lines;
|
||||
}
|
||||
@@ -435,6 +435,8 @@ export interface PublicCelebrity extends CelebrityBase {
|
||||
|
||||
/** Admin: a famous person with the birth data for the edit form. */
|
||||
export interface AdminCelebrity extends CelebrityBase {
|
||||
/** Who added them (a creator may delete only their own). */
|
||||
created_by: string | null;
|
||||
birth_data: BirthData;
|
||||
birth: PublicBirth;
|
||||
highlights: ChartHighlights;
|
||||
@@ -482,6 +484,8 @@ export type InvitationStatus = "pending" | "accepted" | "expired" | "revoked";
|
||||
|
||||
/** What an invitation link shows before login. */
|
||||
export interface InvitationLanding {
|
||||
/** The package that comes with it (only admins attach one). */
|
||||
gift: Package | null;
|
||||
inviter_name: string | null;
|
||||
message: string | null;
|
||||
status: InvitationStatus;
|
||||
@@ -509,14 +513,6 @@ export interface AdminInvitation {
|
||||
package: { id: string; name: string | null; code: string | null; redeemed_at: string | null } | null;
|
||||
}
|
||||
|
||||
export interface WaitlistEntry {
|
||||
email: string;
|
||||
locale: string;
|
||||
created_at: string;
|
||||
/** The address's latest invitation, if any. */
|
||||
invitation: "pending" | "accepted" | null;
|
||||
}
|
||||
|
||||
export interface InvitationResult {
|
||||
email: string;
|
||||
status: "invited" | "invalid" | "already_user" | "already_invited" | "opted_out";
|
||||
|
||||
Reference in New Issue
Block a user