Merge pull request 'Main' (#1) from main into prod
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
+41
-7
@@ -1,12 +1,14 @@
|
||||
# Tests, image build and deployment on every push to main.
|
||||
# main: tests and image build (tags: commit hash, `main`).
|
||||
# prod: the same, then deployment to the server (tags: commit hash, `prod`, `latest`).
|
||||
#
|
||||
# Runs on the self-hosted runner in ci/runner (label `linux`). Jobs use the
|
||||
# host's Docker daemon, so image builds share its BuildKit cache.
|
||||
# host's Docker daemon, so image builds share its BuildKit cache; a commit
|
||||
# already built on main is rebuilt from cache in seconds.
|
||||
#
|
||||
# Repository settings (Settings → Actions):
|
||||
# secrets.REGISTRY_TOKEN Gitea access token with package write access
|
||||
# secrets.DEPLOY_SSH_KEY private key of the deploy user on the server
|
||||
# vars.DEPLOY_HOST user@host of the server; deployment is skipped when unset
|
||||
# vars.DEPLOY_HOST user@host of the server
|
||||
# vars.DEPLOY_KNOWN_HOSTS `ssh-keyscan <host>` output
|
||||
# vars.DEPLOY_PATH directory on the server (default /opt/sorsfonalak)
|
||||
|
||||
@@ -14,7 +16,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, prod]
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
@@ -77,11 +79,16 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
tag=$(echo "${{ github.sha }}" | cut -c1-12)
|
||||
extra="${{ github.ref_name }}"
|
||||
[ "$extra" = prod ] && extra="prod latest"
|
||||
build() {
|
||||
image="$IMAGE_PREFIX-$1"; shift
|
||||
docker build --label sorsfonalak.ci=1 -t "$image:$tag" -t "$image:latest" "$@"
|
||||
docker build --label sorsfonalak.ci=1 -t "$image:$tag" "$@"
|
||||
docker push -q "$image:$tag"
|
||||
docker push -q "$image:latest"
|
||||
for t in $extra; do
|
||||
docker tag "$image:$tag" "$image:$t"
|
||||
docker push -q "$image:$t"
|
||||
done
|
||||
}
|
||||
build horoscope-api -f services/horoscope-api/Dockerfile .
|
||||
build backend -f services/backend/Dockerfile .
|
||||
@@ -95,9 +102,12 @@ jobs:
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
if: vars.DEPLOY_HOST != ''
|
||||
if: github.ref == 'refs/heads/prod'
|
||||
runs-on: linux
|
||||
steps:
|
||||
- name: Check settings
|
||||
run: |
|
||||
[ -n "${{ vars.DEPLOY_HOST }}" ] || { echo "vars.DEPLOY_HOST is not set (Settings → Actions → Variables)" >&2; exit 1; }
|
||||
- name: Checkout
|
||||
run: |
|
||||
apk add --no-cache -q git openssh-client
|
||||
@@ -125,3 +135,27 @@ jobs:
|
||||
(grep -q '^TAG=' .env && sed -i 's/^TAG=.*/TAG=$tag/' .env || echo 'TAG=$tag' >> .env) && \
|
||||
docker compose pull -q && docker compose up -d --remove-orphans --wait && \
|
||||
docker image prune -f >/dev/null"
|
||||
# A release (and its tag, e.g. v2026.11.17-163612e) for every deployment,
|
||||
# listing the commits since the previous one.
|
||||
- name: Release
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
run: |
|
||||
set -eu
|
||||
apk add --no-cache -q curl jq
|
||||
git fetch -q --unshallow --tags origin
|
||||
short=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
name="v$(date -u +%Y.%m.%d)-$short"
|
||||
if curl -fsS -o /dev/null -H "Authorization: token $TOKEN" "$API/releases/tags/$name" 2>/dev/null; then
|
||||
echo "release $name already exists (redeploy)"; exit 0
|
||||
fi
|
||||
prev=$(git describe --tags --abbrev=0 --match 'v*' HEAD 2>/dev/null || true)
|
||||
if [ -n "$prev" ]; then range="$prev..HEAD"; since="since $prev"; else range="-20 HEAD"; since="(last 20 commits)"; fi
|
||||
changes=$(git log --no-merges --pretty='- %s (%h)' $range)
|
||||
body=$(printf 'Deployed to production on %s UTC.\nImages: `registry.sagifer.com/sagifer/sorsfonalak-*:%s`\n\nChanges %s:\n%s\n' \
|
||||
"$(date -u '+%Y-%m-%d %H:%M')" "$(echo "${{ github.sha }}" | cut -c1-12)" "$since" "$changes")
|
||||
jq -n --arg tag "$name" --arg sha "${{ github.sha }}" --arg body "$body" \
|
||||
'{tag_name: $tag, target_commitish: $sha, name: $tag, body: $body}' \
|
||||
| curl -fsS -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' -d @- "$API/releases" \
|
||||
| jq -r '"created release " + .name + ": " + .html_url'
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Every time a user's own (primary) birth data is set or changed. The
|
||||
-- backend limits changes with it: after the first save, three corrections
|
||||
-- within an hour, then one per 24 hours (admins are not limited).
|
||||
|
||||
CREATE TABLE birth_data_changes (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX birth_data_changes_user_idx ON birth_data_changes (user_id, created_at);
|
||||
|
||||
-- The current primary charts count as the first save.
|
||||
INSERT INTO birth_data_changes (id, user_id, chart_id, created_at)
|
||||
SELECT gen_random_uuid(), owner_id, id, created_at FROM charts WHERE is_primary;
|
||||
+9
-3
@@ -1,10 +1,16 @@
|
||||
# Build és telepítés
|
||||
|
||||
Minden `main`-re pusholt commit után lefut a `.gitea/workflows/ci.yml` (Gitea Actions):
|
||||
A `.gitea/workflows/ci.yml` (Gitea Actions) két ágra fut:
|
||||
|
||||
- **main**: tesztek, majd image-build. Címkék: a commit hash első 12 karaktere és `main`.
|
||||
- **prod**: ugyanez, majd telepítés a szerverre. Címkék: hash, `prod` és `latest`. Élesíteni tehát úgy kell, hogy a main-t a prod-ba mergeled (vagy pusholod).
|
||||
|
||||
A lépések:
|
||||
|
||||
1. **test**: `cargo test` a backendre, a workerre, a db-re, a horoscope-clientre és a service-kitre, egy Postgres szolgáltatás-konténerrel.
|
||||
2. **build**: megépíti a négy image-et, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A címke a commit hash első 12 karaktere, plusz `latest`. A frontend buildje a TypeScript-típusokat is ellenőrzi.
|
||||
3. **deploy** (csak ha a `DEPLOY_HOST` be van állítva): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, beírja az új `TAG`-et a szerveren lévő `.env`-be, majd `docker compose pull && up -d`. Az adatbázis-migrációk a backend indulásakor futnak le.
|
||||
2. **build**: megépíti a négy image-et, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi. Egy main-en már megépült commit a cache-ből pár mp alatt újraépül.
|
||||
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, beírja az új `TAG`-et a szerveren lévő `.env`-be, majd `docker compose pull && up -d`. Az adatbázis-migrációk a backend indulásakor futnak le.
|
||||
4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-<hash>` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases).
|
||||
|
||||
Kézzel is indítható a repó Actions oldaláról (workflow_dispatch).
|
||||
|
||||
|
||||
@@ -85,6 +85,8 @@ services:
|
||||
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
|
||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
||||
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
||||
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
||||
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -53,6 +53,8 @@ services:
|
||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
||||
# E-mail + password login; off by default (Google, Apple and Facebook only).
|
||||
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
||||
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
||||
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -14,6 +14,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
||||
| `COOKIE_DOMAIN` | – | pl. `.sorsfonalak.hu`, ha a frontend és az API más aldomainen fut |
|
||||
| `SESSION_TTL_DAYS` | `30` | a munkamenet élettartama |
|
||||
| `PASSWORD_LOGIN` | `false` | e-mail + jelszó regisztráció és belépés; élesben ki van kapcsolva (csak Google, Apple, Facebook), a jelszavas végpontok ilyenkor 403-at adnak |
|
||||
| `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` azonnal jóváír egy elemzési egységet (a compose-fájlokban egyelőre `true`) |
|
||||
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
||||
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||
@@ -111,3 +112,8 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
|
||||
## Háttérmunkák
|
||||
|
||||
A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket (OpenRouter, strukturált JSON; hibánál visszaadja az egységet), és óránként takarít. Még hátravan az elemzés streamelése a frontend felé.
|
||||
|
||||
## Korlátok
|
||||
|
||||
- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
|
||||
- **Admin:** nincs módosítási korlát, és a részletes elemzés ingyenes (nem fogy egység).
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Limits on changing a user's own birth data.
|
||||
//!
|
||||
//! The first save is free. Within an hour of it the user may correct the data
|
||||
//! three more times; after that, once per 24 hours. Admins are not limited.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgConnection;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::ApiError;
|
||||
use crate::views::rfc3339;
|
||||
use db::Role;
|
||||
|
||||
const GRACE_PERIOD: Duration = Duration::hours(1);
|
||||
const GRACE_CHANGES: usize = 3;
|
||||
const DAILY: Duration = Duration::hours(24);
|
||||
|
||||
pub const DAILY_NOTICE: &str = "A rendszer csak napi egy módosítást engedélyez.";
|
||||
|
||||
/// Where a user stands with changing their birth data.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Status {
|
||||
/// The grace period is over (or used up): one change per day.
|
||||
pub daily: bool,
|
||||
/// When the next change is possible; `None`: now.
|
||||
pub next_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// The rule itself, over the times of the earlier saves (oldest first).
|
||||
pub fn evaluate(saves: &[OffsetDateTime], now: OffsetDateTime) -> Status {
|
||||
let (Some(&first), Some(&last)) = (saves.first(), saves.last()) else {
|
||||
return Status { daily: false, next_at: None };
|
||||
};
|
||||
let corrections = saves.len() - 1;
|
||||
if now - first < GRACE_PERIOD && corrections < GRACE_CHANGES {
|
||||
return Status { daily: false, next_at: None };
|
||||
}
|
||||
let next = last + DAILY;
|
||||
Status { daily: true, next_at: (next > now).then_some(next) }
|
||||
}
|
||||
|
||||
async fn saves(conn: &mut PgConnection, user_id: Uuid) -> Result<Vec<OffsetDateTime>, ApiError> {
|
||||
let rows: Vec<(OffsetDateTime,)> =
|
||||
sqlx::query_as("SELECT created_at FROM birth_data_changes WHERE user_id = $1 ORDER BY created_at")
|
||||
.bind(user_id)
|
||||
.fetch_all(conn)
|
||||
.await?;
|
||||
Ok(rows.into_iter().map(|(t,)| t).collect())
|
||||
}
|
||||
|
||||
/// "23 óra 5 perc" / "40 perc" (rounded up to a minute).
|
||||
fn wait_text(wait: Duration) -> String {
|
||||
let minutes = (wait.whole_seconds() + 59) / 60;
|
||||
let (h, m) = (minutes / 60, minutes % 60);
|
||||
match (h, m) {
|
||||
(0, m) => format!("{m} perc"),
|
||||
(h, 0) => format!("{h} óra"),
|
||||
(h, m) => format!("{h} óra {m} perc"),
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_error(next_at: OffsetDateTime, now: OffsetDateTime) -> ApiError {
|
||||
ApiError::Limited {
|
||||
code: "birth_data_change_limit",
|
||||
message: format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next_at - now)),
|
||||
}
|
||||
}
|
||||
|
||||
/// For `/v1/me`: whether the daily limit applies and, if so, the notice to show.
|
||||
pub async fn view(conn: &mut PgConnection, auth: &AuthUser) -> Result<Value, ApiError> {
|
||||
if auth.user.has_role(Role::Admin) {
|
||||
return Ok(json!({ "limited": false, "next_change_at": null, "notice": null }));
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let status = evaluate(&saves(conn, auth.id()).await?, now);
|
||||
let notice = match status.next_at {
|
||||
Some(next) => Some(format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next - now))),
|
||||
None if status.daily => Some(DAILY_NOTICE.to_string()),
|
||||
None => None,
|
||||
};
|
||||
Ok(json!({
|
||||
"limited": status.daily,
|
||||
"next_change_at": status.next_at.map(rfc3339),
|
||||
"notice": notice,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Checks the limit and records the change, inside the transaction that
|
||||
/// makes `chart_id` the user's own chart. Locks the user row, so parallel
|
||||
/// saves are counted one after the other.
|
||||
pub async fn record(tx: &mut PgConnection, auth: &AuthUser, chart_id: Uuid) -> Result<(), ApiError> {
|
||||
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
|
||||
if !auth.user.has_role(Role::Admin) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if let Some(next) = evaluate(&saves(tx, auth.id()).await?, now).next_at {
|
||||
return Err(limit_error(next, now));
|
||||
}
|
||||
}
|
||||
sqlx::query("INSERT INTO birth_data_changes (id, user_id, chart_id) VALUES ($1, $2, $3)")
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(chart_id)
|
||||
.execute(tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(minutes: i64) -> OffsetDateTime {
|
||||
OffsetDateTime::UNIX_EPOCH + Duration::minutes(minutes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_save_is_free() {
|
||||
assert_eq!(evaluate(&[], at(0)), Status { daily: false, next_at: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_corrections_within_the_first_hour() {
|
||||
let now = at(30);
|
||||
assert_eq!(evaluate(&[at(0)], now).next_at, None);
|
||||
assert_eq!(evaluate(&[at(0), at(5), at(10)], now).next_at, None);
|
||||
// the third correction used up the grace period
|
||||
let s = evaluate(&[at(0), at(5), at(10), at(20)], now);
|
||||
assert!(s.daily);
|
||||
assert_eq!(s.next_at, Some(at(20) + DAILY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_first_hour_once_a_day() {
|
||||
assert_eq!(evaluate(&[at(0)], at(61)), Status { daily: true, next_at: Some(at(24 * 60)) });
|
||||
assert_eq!(evaluate(&[at(0)], at(24 * 60)), Status { daily: true, next_at: None });
|
||||
assert_eq!(evaluate(&[at(0), at(24 * 60 + 5)], at(30 * 60)).next_at, Some(at(48 * 60 + 5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_is_written_in_hours_and_minutes() {
|
||||
assert_eq!(wait_text(Duration::minutes(40)), "40 perc");
|
||||
assert_eq!(wait_text(Duration::hours(3)), "3 óra");
|
||||
assert_eq!(wait_text(Duration::seconds(23 * 3600 + 4 * 60 + 1)), "23 óra 5 perc");
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ pub struct Config {
|
||||
/// `PASSWORD_LOGIN` (default `false`): e-mail and password registration and
|
||||
/// login. Off in production, where only Google, Apple and Facebook are offered.
|
||||
pub password_login: bool,
|
||||
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
|
||||
/// analysis unit at once, until Stripe is connected.
|
||||
pub mock_payments: bool,
|
||||
/// `GOOGLE_CLIENT_IDS`: comma-separated OAuth client ids accepted as the
|
||||
/// ID token audience; empty disables Google login.
|
||||
pub google_client_ids: Vec<String>,
|
||||
@@ -87,6 +90,7 @@ impl Config {
|
||||
cookie_domain: var("COOKIE_DOMAIN"),
|
||||
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
|
||||
password_login: parsed("PASSWORD_LOGIN", false)?,
|
||||
mock_payments: parsed("MOCK_PAYMENTS", false)?,
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
google_jwks_url: var("GOOGLE_JWKS_URL")
|
||||
.unwrap_or_else(|| "https://www.googleapis.com/oauth2/v3/certs".into()),
|
||||
@@ -115,6 +119,7 @@ impl Config {
|
||||
cookie_domain: None,
|
||||
session_ttl_days: 30,
|
||||
password_login: true,
|
||||
mock_payments: true,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
google_jwks_url,
|
||||
bootstrap_admin_emails: vec!["admin@example.com".into()],
|
||||
|
||||
@@ -28,6 +28,9 @@ pub enum ApiError {
|
||||
InsufficientCredits { unit: &'static str, balance: i64 },
|
||||
#[error("too many attempts; try again later")]
|
||||
TooManyRequests,
|
||||
/// A usage limit; the message is shown to the user as is.
|
||||
#[error("{message}")]
|
||||
Limited { code: &'static str, message: String },
|
||||
/// Birth data rejected by the horoscope service; its error object is passed through.
|
||||
#[error("invalid birth data")]
|
||||
BirthData { status: StatusCode, body: Value },
|
||||
@@ -54,6 +57,7 @@ impl ApiError {
|
||||
ApiError::InvalidToken => (StatusCode::BAD_REQUEST, "invalid_token"),
|
||||
ApiError::InsufficientCredits { .. } => (StatusCode::PAYMENT_REQUIRED, "insufficient_credits"),
|
||||
ApiError::TooManyRequests => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"),
|
||||
ApiError::Limited { code, .. } => (StatusCode::TOO_MANY_REQUESTS, code),
|
||||
ApiError::BirthData { status, .. } => (*status, "invalid_birth_data"),
|
||||
ApiError::HoroscopeUnavailable(_) => (StatusCode::BAD_GATEWAY, "horoscope_unavailable"),
|
||||
ApiError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! `backend healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod auth;
|
||||
mod birth_changes;
|
||||
mod config;
|
||||
mod credits;
|
||||
mod error;
|
||||
|
||||
@@ -28,12 +28,15 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let balance = credits::balance(&mut *state.db.acquire().await?, auth.id()).await?;
|
||||
let mut conn = state.db.acquire().await?;
|
||||
let balance = credits::balance(&mut conn, auth.id()).await?;
|
||||
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
"primary_chart_id": primary.map(|(id,)| id),
|
||||
"analyses_left": balance.view(),
|
||||
"birth_change": birth_change,
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Text analyses (LLM) of charts and synastries.
|
||||
//!
|
||||
//! A request creates a `pending` analysis and spends one unit of its kind
|
||||
//! (`natal` or `synastry`, see [`credits`]); the worker
|
||||
//! (`natal` or `synastry`, see [`credits`]; admins pay nothing); the worker
|
||||
//! writes the text later. A finished analysis with the same cache key (same
|
||||
//! chart or synastry hash, prompt version, model and language) is copied
|
||||
//! instead, free of charge, so the same chart is never paid for twice.
|
||||
@@ -29,6 +29,7 @@ use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||
use db::Role;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct AnalysisRow {
|
||||
@@ -117,12 +118,14 @@ async fn request(
|
||||
req: AnalysisRequest,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
||||
// Admins get detailed analyses free of charge.
|
||||
let unit = match target {
|
||||
Target::Synastry { .. } => Unit::Synastry,
|
||||
_ => Unit::Natal,
|
||||
_ if auth.user.has_role(Role::Admin) => None,
|
||||
Target::Synastry { .. } => Some(Unit::Synastry),
|
||||
_ => Some(Unit::Natal),
|
||||
};
|
||||
let model = state.config.analysis_model.clone();
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, Some(unit)).await?;
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, unit).await?;
|
||||
Ok((status, Json(row.view())))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use uuid::Uuid;
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::birth_changes;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{chart_hash, chart_highlights, rfc3339};
|
||||
|
||||
@@ -130,7 +131,8 @@ fn clean_birth(birth: Value) -> Result<Value, ApiError> {
|
||||
|
||||
/// Saves a new chart. If the user already has a chart with exactly the same
|
||||
/// birth data, that one is returned (and made primary if asked) instead of
|
||||
/// calculating it again.
|
||||
/// calculating it again. Replacing the user's own chart counts against the
|
||||
/// birth data change limit ([`birth_changes`]).
|
||||
pub async fn create(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
@@ -157,6 +159,7 @@ pub async fn create(
|
||||
.bind(chart.id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
birth_changes::record(&mut tx, &auth, row.id).await?;
|
||||
tx.commit().await?;
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
return Ok((StatusCode::OK, Json(row.owner_view())));
|
||||
@@ -194,6 +197,9 @@ pub async fn create(
|
||||
.bind(hash)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if req.is_primary {
|
||||
birth_changes::record(&mut tx, &auth, row.id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
queue_summary(&state, &auth, &row).await;
|
||||
Ok((StatusCode::CREATED, Json(row.owner_view())))
|
||||
@@ -243,6 +249,9 @@ pub async fn update(
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if is_primary && !chart.is_primary {
|
||||
birth_changes::record(&mut tx, &auth, id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(row.owner_view()))
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ mod admin;
|
||||
mod analyses;
|
||||
mod auth;
|
||||
mod charts;
|
||||
mod payments;
|
||||
mod shares;
|
||||
mod synastries;
|
||||
|
||||
@@ -63,6 +64,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/me/password", post(account::change_password))
|
||||
.route("/v1/me/export", get(account::export))
|
||||
.route("/v1/credits", get(account::credits))
|
||||
.route("/v1/payments/mock", post(payments::mock))
|
||||
// charts
|
||||
.route("/v1/charts", get(charts::list).post(charts::create))
|
||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
||||
@@ -119,6 +121,7 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"analysis_model": c.analysis_model,
|
||||
"summary_model": c.summary_model,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": c.mock_payments,
|
||||
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Payments. Until Stripe is connected, `MOCK_PAYMENTS=true` turns on a
|
||||
//! stand-in: "paying" adds one analysis unit right away, so the paid flow can
|
||||
//! be used end to end.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St};
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MockPayment {
|
||||
unit: Unit,
|
||||
}
|
||||
|
||||
/// Adds one unit of the given kind as a (pretend) purchase.
|
||||
pub async fn mock(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<MockPayment>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !state.config.mock_payments {
|
||||
return Err(ApiError::NotFound("payment method"));
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) VALUES ($1, $2, $3, 1, 'purchase', 'mock payment')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
.bind(req.unit.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let balance = credits::balance(&mut tx, auth.id()).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(json!({ "analyses_left": balance.view() })))
|
||||
}
|
||||
@@ -400,6 +400,8 @@ async fn charts_are_private(pool: PgPool) {
|
||||
.await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::NOT_FOUND, Some("place_not_found")));
|
||||
|
||||
// (the fourth change of the own chart; the limit is tested in birth_data_changes_are_limited)
|
||||
sqlx::query("DELETE FROM birth_data_changes").execute(&app.pool).await.unwrap();
|
||||
let r = app
|
||||
.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Én", "is_primary": true})))
|
||||
.await;
|
||||
@@ -652,3 +654,101 @@ async fn synastry_analyses_use_synastry_units(pool: PgPool) {
|
||||
assert_eq!((r.status, r.body["kind"].as_str()), (StatusCode::ACCEPTED, Some("synastry")));
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 1, "synastry": 0}));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn birth_data_changes_are_limited(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["birth_change"]["limited"], json!(false));
|
||||
|
||||
// the first save and three corrections within the hour are free
|
||||
let first = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
for date in ["1990-03-16", "1990-03-17", "1990-03-18"] {
|
||||
app.chart(&anna, "Saját", true, date).await;
|
||||
}
|
||||
// saving the current data again is not a change
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(&anna),
|
||||
json!({"label": "Saját", "is_primary": true,
|
||||
"birth": {"date": "1990-03-18", "time": "14:30", "country": "HU", "place": "Szeged"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
|
||||
// the fourth correction: once a day from now on
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/charts",
|
||||
Some(&anna),
|
||||
json!({"label": "Saját", "is_primary": true,
|
||||
"birth": {"date": "1990-03-19", "time": "14:30", "country": "HU", "place": "Szeged"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS, "{}", r.body);
|
||||
assert_eq!(r.body["error"]["code"], json!("birth_data_change_limit"));
|
||||
let message = r.body["error"]["message"].as_str().unwrap();
|
||||
assert!(message.starts_with("A rendszer csak napi egy módosítást engedélyez."), "{message}");
|
||||
assert!(message.ends_with("óra múlva módosíthatod."), "{message}");
|
||||
// switching back to an older chart is a change too
|
||||
let r = app
|
||||
.call(
|
||||
"PATCH",
|
||||
&format!("/v1/charts/{}", first["id"].as_str().unwrap()),
|
||||
Some(&anna),
|
||||
Some(json!({"is_primary": true})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
|
||||
// other people's charts are not limited
|
||||
app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||
|
||||
let me = app.get("/v1/me", Some(&anna)).await.body;
|
||||
assert_eq!(me["birth_change"]["limited"], json!(true));
|
||||
assert!(me["birth_change"]["notice"].as_str().unwrap().contains("napi egy"));
|
||||
|
||||
// a day later it works again
|
||||
sqlx::query("UPDATE birth_data_changes SET created_at = created_at - interval '25 hours'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.chart(&anna, "Saját", true, "1990-03-19").await;
|
||||
|
||||
// admins are not limited
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
for day in 10..16 {
|
||||
app.chart(&admin, "Saját", true, &format!("1980-01-{day}")).await;
|
||||
}
|
||||
assert_eq!(app.get("/v1/me", Some(&admin)).await.body["birth_change"]["notice"], Value::Null);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||
let r =
|
||||
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&admin), None).await;
|
||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
|
||||
|
||||
// a user "pays", which adds a unit, then requests the analysis
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let chart = app.chart(&anna, "Saját", true, "1991-05-01").await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["analyses_left"]),
|
||||
(StatusCode::OK, &json!({"natal": 1, "synastry": 0})),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
let r =
|
||||
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&anna), None).await;
|
||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
|
||||
assert_eq!(app.get("/v1/credits", Some(&anna)).await.body["balance"], json!({"natal": 0, "synastry": 0}));
|
||||
|
||||
// without MOCK_PAYMENTS there is no such payment
|
||||
let app = TestApp::with_config(app.pool.clone(), |c| c.mock_payments = false).await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"unit": "natal"})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,35 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
|
||||
function GoogleMark() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 48 48" aria-hidden="true">
|
||||
<path
|
||||
fill="#EA4335"
|
||||
d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"
|
||||
/>
|
||||
<path
|
||||
fill="#4285F4"
|
||||
d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"
|
||||
/>
|
||||
<path
|
||||
fill="#FBBC05"
|
||||
d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"
|
||||
/>
|
||||
<path
|
||||
fill="#34A853"
|
||||
d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Continue with Google" in the site's own button style. Google's real
|
||||
* (rendered, invisible) button lies on top of it and receives the click, so
|
||||
* the sign-in still returns an ID token.
|
||||
*/
|
||||
export function GoogleLogin({ clientId, target }: { clientId: string; target: string }) {
|
||||
const router = useRouter();
|
||||
const slot = useRef<HTMLDivElement>(null);
|
||||
@@ -34,7 +63,7 @@ export function GoogleLogin({ clientId, target }: { clientId: string; target: st
|
||||
if (!ready || !google || !slot.current) return;
|
||||
google.accounts.id.initialize({ client_id: clientId, callback: onCredential, ux_mode: "popup", itp_support: true });
|
||||
google.accounts.id.renderButton(slot.current, {
|
||||
theme: "filled_black",
|
||||
theme: "outline",
|
||||
size: "large",
|
||||
text: "continue_with",
|
||||
shape: "rectangular",
|
||||
@@ -51,8 +80,15 @@ export function GoogleLogin({ clientId, target }: { clientId: string; target: st
|
||||
onReady={() => setReady(true)}
|
||||
onError={() => setError("Nem sikerült betölteni a Google-belépést. Ellenőrizd a hálózatot vagy a reklámblokkolót.")}
|
||||
/>
|
||||
<div ref={slot} className="gsi-slot" aria-busy={busy} />
|
||||
{busy && <p className="msg muted">Belépés…</p>}
|
||||
<div className="social-login" data-ready={ready} aria-busy={busy}>
|
||||
<span className="btn-social" aria-hidden="true">
|
||||
<span className="btn-social-icon">
|
||||
<GoogleMark />
|
||||
</span>
|
||||
{busy ? "Belépés…" : "Folytatás Google-fiókkal"}
|
||||
</span>
|
||||
<div ref={slot} className="gsi-overlay" />
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
|
||||
@@ -47,7 +47,7 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
<div className="auth-box">
|
||||
<div className="page-head">
|
||||
<h1 style={{ fontSize: 44 }}>Belépés</h1>
|
||||
<p className="muted">Lépj be a Google-fiókoddal. Ha még nincs fiókod, az első belépéskor létrejön.</p>
|
||||
<p className="muted">Üdv újra! Lépj be a fiókodba.</p>
|
||||
</div>
|
||||
{config === null ? (
|
||||
<p className="msg msg-error" role="alert">
|
||||
@@ -60,6 +60,7 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
||||
</p>
|
||||
)}
|
||||
<p className="auth-foot">Még nincs fiókod? Az első belépéskor létrejön.</p>
|
||||
<p className="hint">
|
||||
A belépéssel elfogadod, hogy a születési adataidat a képleted kiszámításához tároljuk. Bármikor törölheted
|
||||
őket a profilodban.
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
--ok: #9fd8b0;
|
||||
--harmonic: #7fb0e0;
|
||||
--tense: #e38b8b;
|
||||
--square: #f0a35e;
|
||||
--radius: 10px;
|
||||
--font-display: var(--font-cormorant), "Cormorant Garamond", Georgia, serif;
|
||||
--font-body: var(--font-inter), Inter, system-ui, sans-serif;
|
||||
@@ -143,9 +144,27 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
}
|
||||
.auth-main { flex: 1 1 480px; display: flex; align-items: center; justify-content: center; padding: 48px 24px; }
|
||||
.auth-box { width: 100%; max-width: 420px; display: flex; flex-direction: column; gap: 28px; }
|
||||
.wheel { width: min(380px, 80%); aspect-ratio: 1; margin: 0 auto; }
|
||||
.tagline { font-family: var(--font-display); font-size: 36px; font-weight: 600; line-height: 1.1; }
|
||||
.gsi-slot { min-height: 44px; display: flex; justify-content: center; }
|
||||
.wheel { width: min(440px, 80%); aspect-ratio: 1; margin: 0 auto; }
|
||||
.tagline { font-family: var(--font-display); font-size: 38px; font-weight: 600; line-height: 1.1; }
|
||||
.auth-foot { font-size: 15px; color: var(--muted); text-align: center; }
|
||||
|
||||
/* Social login buttons; Google's own button lies invisibly on top (.gsi-overlay). */
|
||||
.social-login { position: relative; }
|
||||
.btn-social {
|
||||
position: relative; width: 100%; min-height: 48px; padding: 0 52px;
|
||||
display: flex; align-items: center; justify-content: center; gap: 12px;
|
||||
border: 1px solid var(--line-2); border-radius: var(--radius); background: transparent;
|
||||
color: var(--ink); font: 500 15px var(--font-body);
|
||||
}
|
||||
.btn-social-icon { position: absolute; left: 16px; top: 50%; margin-top: -10px; width: 20px; height: 20px; display: flex; }
|
||||
.social-login:hover .btn-social { border-color: #5a6790; background: rgba(255, 255, 255, 0.03); }
|
||||
.social-login:focus-within .btn-social { outline: 2px solid var(--gold); outline-offset: 2px; }
|
||||
.social-login[data-ready="false"] .btn-social { opacity: 0.6; }
|
||||
.gsi-overlay {
|
||||
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
|
||||
opacity: 0.001; overflow: hidden; cursor: pointer;
|
||||
}
|
||||
.gsi-overlay > div, .gsi-overlay iframe { transform: scale(1.06, 1.2); }
|
||||
|
||||
/* Detailed analysis */
|
||||
.analysis-card { gap: 14px; }
|
||||
@@ -173,14 +192,33 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.skeleton span:last-child { width: 60%; }
|
||||
@keyframes pulse { 50% { opacity: 0.45; } }
|
||||
@media (prefers-reduced-motion: reduce) { .skeleton span { animation: none; } }
|
||||
|
||||
/* Loading while the LLM writes */
|
||||
.loading { display: flex; align-items: center; gap: 24px; padding: 8px 0; }
|
||||
.loading-wheel { width: 120px; height: 120px; flex: none; animation: spin 24s linear infinite; }
|
||||
.loading-compact .loading-wheel { width: 64px; height: 64px; }
|
||||
.loading-text { display: flex; flex-direction: column; gap: 6px; }
|
||||
.loading-text strong { font-family: var(--font-display); font-size: 24px; font-weight: 600; }
|
||||
.loading-text .muted { animation: pulse 2.4s ease-in-out infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .loading-wheel, .loading-text .muted { animation: none; } }
|
||||
@media (max-width: 640px) { .loading { flex-direction: column; text-align: center; } }
|
||||
|
||||
/* Payment step */
|
||||
.pay-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
|
||||
.pay-line { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.chart-layout { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, 1fr); gap: 24px; align-items: start; }
|
||||
.chart-wheel-card { padding: 16px; gap: 10px; }
|
||||
.chart-wheel { width: 100%; height: auto; display: block; max-width: 680px; margin: 0 auto; }
|
||||
.chart-layout .big3 { grid-template-columns: 1fr; }
|
||||
.wheel-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; justify-content: center; }
|
||||
.legend-line { display: inline-block; width: 22px; height: 2px; border-radius: 1px; margin-left: 6px; }
|
||||
.legend-harmonic { background: var(--harmonic); }
|
||||
.legend-tense { background: var(--tense); }
|
||||
.wheel-legend { display: flex; flex-direction: column; align-items: center; gap: 4px; text-align: center; }
|
||||
.wheel-legend-items { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 16px; }
|
||||
.legend-item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.legend-line { display: inline-block; width: 24px; height: 2px; border-radius: 1px; }
|
||||
.legend-trine { background: var(--harmonic); }
|
||||
.legend-sextile { background: repeating-linear-gradient(90deg, var(--harmonic) 0 5px, transparent 5px 9px); }
|
||||
.legend-square { background: var(--square); }
|
||||
.legend-opposition { background: var(--tense); }
|
||||
.aspect-tag { white-space: nowrap; }
|
||||
.aspect-harmonic { color: var(--harmonic); }
|
||||
.aspect-tense { color: var(--tense); }
|
||||
@@ -201,9 +239,10 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.w-axis-label { fill: var(--gold); font: 600 14px var(--font-body); letter-spacing: 0.5px; }
|
||||
.w-house-num { fill: var(--muted); font: 500 12px var(--font-body); }
|
||||
.w-aspect { stroke-linecap: round; }
|
||||
.w-harmonic { stroke: var(--harmonic); }
|
||||
.w-tense { stroke: var(--tense); }
|
||||
.w-neutral { stroke: var(--gold); }
|
||||
.w-asp-trine { stroke: var(--harmonic); }
|
||||
.w-asp-sextile { stroke: var(--harmonic); stroke-dasharray: 5 4; }
|
||||
.w-asp-square { stroke: var(--square); }
|
||||
.w-asp-opposition { stroke: var(--tense); }
|
||||
.w-point-tick { stroke: var(--ink); stroke-width: 1.6; }
|
||||
.w-leader { stroke: var(--muted); stroke-width: 0.7; stroke-opacity: 0.6; }
|
||||
.w-point-glyph { fill: var(--ink); font-family: var(--font-symbols); font-size: 22px; }
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { BigThree, ChartTables } from "@/components/ChartTables";
|
||||
import { ChartSummary } from "@/components/ChartSummary";
|
||||
import { DetailedAnalysis } from "@/components/DetailedAnalysis";
|
||||
import { ChartWheel } from "@/components/ChartWheel";
|
||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||
import { ELEMENTS, MODALITIES, MOON_PHASES, countryName, formatBirthDate, pointName } from "@/lib/astro";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import type { Analysis, Chart } from "@/lib/types";
|
||||
import type { Analysis, Chart, PublicConfig } from "@/lib/types";
|
||||
|
||||
export const metadata: Metadata = { title: "Képlet" };
|
||||
|
||||
@@ -19,9 +18,10 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
const { id } = await params;
|
||||
const me = await requireMe(`/kepletek/${id}`);
|
||||
if (!UUID.test(id)) notFound();
|
||||
const [chart, analyses] = await Promise.all([
|
||||
const [chart, analyses, config] = await Promise.all([
|
||||
backendGet<Chart>(`/v1/charts/${id}`),
|
||||
backendGet<{ analyses: Analysis[] }>(`/v1/charts/${id}/analyses`),
|
||||
backendGet<PublicConfig>("/v1/config"),
|
||||
]);
|
||||
if (!chart) notFound();
|
||||
const list = analyses?.analyses ?? [];
|
||||
@@ -47,22 +47,13 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
{" · "}
|
||||
{place?.name ?? chart.birth_data.place ?? "–"}
|
||||
{country ? `, ${countryName(country)}` : ""}
|
||||
{chart.is_primary && (
|
||||
<>
|
||||
{" · "}
|
||||
<Link href="/profil#birth">adatok javítása</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section className="chart-layout" aria-label="Képletrajz">
|
||||
<div className="card chart-wheel-card">
|
||||
<ChartWheel chart={result} timeKnown={timeKnown} />
|
||||
<p className="hint wheel-legend">
|
||||
<span className="legend-line legend-harmonic" aria-hidden="true" /> harmonikus (trigon, szextil)
|
||||
<span className="legend-line legend-tense" aria-hidden="true" /> feszült (kvadrát, szembenállás)
|
||||
</p>
|
||||
<WheelLegend />
|
||||
</div>
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<ChartSummary chartId={chart.id} initial={summary} />
|
||||
@@ -114,7 +105,13 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<DetailedAnalysis chartId={chart.id} initial={detailed} left={me.analyses_left.natal} />
|
||||
<DetailedAnalysis
|
||||
chartId={chart.id}
|
||||
initial={detailed}
|
||||
left={me.analyses_left.natal}
|
||||
isAdmin={me.user.roles.includes("admin")}
|
||||
canPay={config?.mock_payments ?? false}
|
||||
/>
|
||||
|
||||
<section className="card" aria-labelledby="positions">
|
||||
<h2 id="positions">Pozíciók</h2>
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { AnalysisView } from "@/components/AnalysisView";
|
||||
import { ChartWheel } from "@/components/ChartWheel";
|
||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||
import { Rich } from "@/components/Rich";
|
||||
import { Logo } from "@/components/SiteHeader";
|
||||
import example from "@/content/pelda.json";
|
||||
@@ -38,6 +38,7 @@ export default async function ExamplePage() {
|
||||
<section className="chart-layout" aria-label="A példa képlete">
|
||||
<div className="card chart-wheel-card">
|
||||
<ChartWheel chart={chart} timeKnown />
|
||||
<WheelLegend />
|
||||
</div>
|
||||
<div className="field" style={{ gap: 16 }}>
|
||||
<section className="card summary-card" aria-labelledby="example-summary">
|
||||
|
||||
@@ -19,8 +19,19 @@ export interface SavedBirth {
|
||||
dst: boolean;
|
||||
}
|
||||
|
||||
/** Shows the saved birth data, or the form to enter or correct it. Saving opens the chart page. */
|
||||
export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; chartId: string | null }) {
|
||||
/**
|
||||
* Shows the saved birth data, or the form to enter or correct it. Saving opens
|
||||
* the chart page. `notice`: the backend's text about the change limit, if any.
|
||||
*/
|
||||
export function BirthEditor({
|
||||
chart,
|
||||
chartId,
|
||||
notice,
|
||||
}: {
|
||||
chart: SavedBirth | null;
|
||||
chartId: string | null;
|
||||
notice: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [editing, setEditing] = useState(chart === null);
|
||||
|
||||
@@ -38,6 +49,7 @@ export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; char
|
||||
időszámítást) a születési hely alapján magunk határozzuk meg.
|
||||
</p>
|
||||
)}
|
||||
{chart && notice && <p className="msg">{notice}</p>}
|
||||
<BirthForm
|
||||
initial={chart ? { ...chart.birth, placeName: chart.placeName, region: chart.region } : null}
|
||||
onCancel={chart ? () => setEditing(false) : undefined}
|
||||
@@ -87,6 +99,7 @@ export function BirthEditor({ chart, chartId }: { chart: SavedBirth | null; char
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{notice && <p className="hint">{notice}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ export default async function ProfilePage() {
|
||||
: null
|
||||
}
|
||||
chartId={chart?.id ?? null}
|
||||
notice={me.birth_change.notice}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { ZodiacWheel } from "./ZodiacWheel";
|
||||
|
||||
/** Slowly turning wheel with the elapsed time, while the LLM writes. */
|
||||
export function AnalysisLoading({ title, text, compact = false }: { title?: string; text: string; compact?: boolean }) {
|
||||
const [seconds, setSeconds] = useState(0);
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setSeconds((s) => s + 1), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
const elapsed = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
|
||||
|
||||
return (
|
||||
<div className={compact ? "loading loading-compact" : "loading"}>
|
||||
<ZodiacWheel className="loading-wheel" />
|
||||
<div className="loading-text">
|
||||
{title && <strong>{title}</strong>}
|
||||
<p className="muted" role="status">
|
||||
{text}
|
||||
</p>
|
||||
<p className="hint" aria-hidden="true">
|
||||
{elapsed}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { Rich } from "./Rich";
|
||||
|
||||
const POLL_MS = 3000;
|
||||
@@ -62,17 +63,12 @@ export function ChartSummary({ chartId, initial }: { chartId: string; initial: A
|
||||
<h2 id="summary-title" className="sr-only">
|
||||
Rövid összefoglaló
|
||||
</h2>
|
||||
{gaveUp || summary?.status === "failed" ? (
|
||||
<p className="muted" role="status">
|
||||
{gaveUp || summary?.status === "failed"
|
||||
? "Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később."
|
||||
: "Az összefoglalód készül, ez néhány másodperc…"}
|
||||
Az összefoglaló most nem készült el. Töltsd újra az oldalt egy kicsit később.
|
||||
</p>
|
||||
{!gaveUp && summary?.status !== "failed" && (
|
||||
<div className="skeleton" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</div>
|
||||
) : (
|
||||
<AnalysisLoading compact text="Az összefoglalód készül, ez néhány másodperc…" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -28,6 +28,10 @@ const WHEEL_POINTS = [
|
||||
"lilith",
|
||||
"chiron",
|
||||
];
|
||||
// Aspects drawn on the wheel, between these points; the rest (minor aspects,
|
||||
// nodes, Lilith, Chiron) are only in the aspect table.
|
||||
const WHEEL_ASPECTS = ["opposition", "square", "trine", "sextile"];
|
||||
const ASPECT_POINTS = ["sun", "moon", "mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
|
||||
const SIGN_ORDER = Object.keys(SIGNS);
|
||||
const SIGN_ELEMENT = ["fire", "earth", "air", "water"];
|
||||
const ANGLE_LABELS: [string, string][] = [
|
||||
@@ -94,17 +98,24 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
9,
|
||||
);
|
||||
|
||||
// Longitudes for the aspect line ends (planets and, with a known time, the angles).
|
||||
const ends = new Map<string, number>(points.map((p) => [p.id, p.longitude]));
|
||||
// Aspect line ends: the planets at their spread-out glyph angle (so lines of
|
||||
// neighbouring planets do not run into one point) and, with a known time,
|
||||
// the ascendant and the midheaven.
|
||||
const ends = new Map<string, number>();
|
||||
points.forEach((p, i) => {
|
||||
if (ASPECT_POINTS.includes(p.id)) ends.set(p.id, placed[i]);
|
||||
});
|
||||
if (timeKnown) {
|
||||
for (const [key] of ANGLE_LABELS) {
|
||||
for (const key of ["ascendant", "midheaven"]) {
|
||||
const a = angle(key);
|
||||
if (a) ends.set(key, a.longitude);
|
||||
}
|
||||
}
|
||||
const aspects = (chart.aspects ?? []).filter(
|
||||
(a) => a.aspect !== "conjunction" && ends.has(a.point1) && ends.has(a.point2),
|
||||
);
|
||||
// Only the major aspects; tight ones are drawn last (on top).
|
||||
const aspects = (chart.aspects ?? [])
|
||||
.filter((a) => WHEEL_ASPECTS.includes(a.aspect) && ends.has(a.point1) && ends.has(a.point2))
|
||||
.map((a) => ({ ...a, strength: a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5 }))
|
||||
.sort((x, y) => x.strength - y.strength);
|
||||
|
||||
const description = points
|
||||
.map((p) => `${pointName(p.id)} ${signName(p.sign)} ${dms(p.degree_in_sign_dms)}`)
|
||||
@@ -170,7 +181,14 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
if (!a) return null;
|
||||
const [x, y] = xy(a.longitude, R_LABEL, start);
|
||||
return (
|
||||
<text key={key} x={f(x)} y={f(y)} className="w-axis-label" dominantBaseline="central" textAnchor="middle">
|
||||
<text
|
||||
key={key}
|
||||
x={f(x)}
|
||||
y={f(y)}
|
||||
className="w-axis-label"
|
||||
dominantBaseline="central"
|
||||
textAnchor="middle"
|
||||
>
|
||||
<title>
|
||||
{pointName(key)}: {dms(a.degree_in_sign_dms)} {signName(a.sign)}
|
||||
</title>
|
||||
@@ -186,8 +204,7 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
{aspects.map((a) => {
|
||||
const [x1, y1] = xy(ends.get(a.point1)!, R_INNER, start);
|
||||
const [x2, y2] = xy(ends.get(a.point2)!, R_INNER, start);
|
||||
const kind = ASPECTS[a.aspect]?.kind ?? "neutral";
|
||||
const strength = a.max_orb > 0 ? 1 - Math.min(a.orb / a.max_orb, 1) : 0.5;
|
||||
const s = a.strength;
|
||||
return (
|
||||
<line
|
||||
key={`${a.point1}-${a.point2}-${a.aspect}`}
|
||||
@@ -195,9 +212,9 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
y1={f(y1)}
|
||||
x2={f(x2)}
|
||||
y2={f(y2)}
|
||||
className={`w-aspect w-${kind}`}
|
||||
strokeOpacity={(0.3 + 0.7 * strength).toFixed(2)}
|
||||
strokeWidth={(0.8 + 1.4 * strength).toFixed(2)}
|
||||
className={`w-aspect w-asp-${a.aspect}`}
|
||||
strokeOpacity={(0.2 + 0.8 * s * s).toFixed(2)}
|
||||
strokeWidth={(0.6 + 1.9 * s).toFixed(2)}
|
||||
>
|
||||
<title>
|
||||
{pointName(a.point1)} {ASPECTS[a.aspect]?.hu ?? a.aspect} {pointName(a.point2)} (orbis{" "}
|
||||
@@ -214,7 +231,7 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
const [lx, ly] = xy(placed[i], R_GLYPH + 14, start);
|
||||
const [gx, gy] = xy(placed[i], R_GLYPH, start);
|
||||
const [dx, dy] = xy(placed[i], R_DEG, start);
|
||||
const [ex, ey] = xy(p.longitude, R_INNER, start);
|
||||
const [ex, ey] = xy(placed[i], R_INNER, start);
|
||||
const deg = Number.parseInt(p.degree_in_sign_dms, 10);
|
||||
return (
|
||||
<g key={p.id} className="w-point">
|
||||
@@ -231,10 +248,34 @@ export function ChartWheel({ chart, timeKnown }: { chart: ChartResult; timeKnown
|
||||
<text x={f(dx)} y={f(dy)} className="w-point-deg" dominantBaseline="central" textAnchor="middle">
|
||||
{deg}°{p.retrograde ? "℞" : ""}
|
||||
</text>
|
||||
<circle cx={f(ex)} cy={f(ey)} r={2.2} className="w-end" />
|
||||
{ends.has(p.id) && <circle cx={f(ex)} cy={f(ey)} r={2.2} className="w-end" />}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const LEGEND: [string, string][] = [
|
||||
["trine", "trigon"],
|
||||
["sextile", "szextil"],
|
||||
["square", "kvadrát"],
|
||||
["opposition", "szembenállás"],
|
||||
];
|
||||
|
||||
/** Key to the aspect lines of the wheel. */
|
||||
export function WheelLegend() {
|
||||
return (
|
||||
<div className="hint wheel-legend">
|
||||
<p className="wheel-legend-items">
|
||||
{LEGEND.map(([aspect, label]) => (
|
||||
<span key={aspect} className="legend-item">
|
||||
<span className={`legend-line legend-${aspect}`} aria-hidden="true" /> {label}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
<p>Vastagabb vonal: szorosabb fényszög.</p>
|
||||
<p>A körön a bolygók, az ASC és az MC főfényszögei vannak; az összes fényszög a táblázatban.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,27 +6,35 @@ import { useEffect, useState } from "react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { AnalysisView } from "./AnalysisView";
|
||||
|
||||
const POLL_MS = 5000;
|
||||
const MAX_POLLS = 120; // 10 minutes
|
||||
|
||||
type Step = "offer" | "confirm" | "pay";
|
||||
|
||||
/**
|
||||
* The paid detailed analysis of a chart: offer (with the units left),
|
||||
* confirmation, progress while the worker writes it, and the finished text.
|
||||
* The detailed analysis of a chart. A saved one is shown at once; otherwise
|
||||
* the offer: admins start it free, users with units confirm, others pay
|
||||
* (a stand-in payment for now). While the worker writes it, a loading wheel.
|
||||
*/
|
||||
export function DetailedAnalysis({
|
||||
chartId,
|
||||
initial,
|
||||
left,
|
||||
isAdmin,
|
||||
canPay,
|
||||
}: {
|
||||
chartId: string;
|
||||
initial: Analysis | null;
|
||||
left: number;
|
||||
isAdmin: boolean;
|
||||
/** The stand-in payment is on (MOCK_PAYMENTS). */
|
||||
canPay: boolean;
|
||||
}) {
|
||||
const [analysis, setAnalysis] = useState<Analysis | null>(initial);
|
||||
const [remaining, setRemaining] = useState(left);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [step, setStep] = useState<Step>("offer");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const waiting = analysis?.status === "pending" || analysis?.status === "running";
|
||||
@@ -54,14 +62,13 @@ export function DetailedAnalysis({
|
||||
};
|
||||
}, [waiting, analysis]);
|
||||
|
||||
async function request() {
|
||||
async function start(pay: boolean) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const next = await api<Analysis>(`/charts/${chartId}/analyses`, { method: "POST" });
|
||||
setAnalysis(next);
|
||||
if (next.credits_charged > 0) setRemaining((n) => n - 1);
|
||||
setConfirming(false);
|
||||
if (pay) await api("/payments/mock", { body: { unit: "natal" } });
|
||||
setAnalysis(await api<Analysis>(`/charts/${chartId}/analyses`, { method: "POST" }));
|
||||
setStep("offer");
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
@@ -78,32 +85,29 @@ export function DetailedAnalysis({
|
||||
);
|
||||
}
|
||||
|
||||
if (waiting) {
|
||||
return (
|
||||
<section className="card analysis-card" aria-labelledby="detailed-title" aria-busy={waiting}>
|
||||
<section className="card analysis-card" aria-label="Részletes elemzés" aria-busy="true">
|
||||
<span className="eyebrow">Részletes elemzés</span>
|
||||
<AnalysisLoading
|
||||
title="Készül az elemzésed"
|
||||
text="Most íródik a hat fejezet a képleted alapján. Ez általában 1–3 perc; nyugodtan elhagyhatod az oldalt, az elemzés elkészül és itt vár."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card analysis-card" aria-labelledby="detailed-title">
|
||||
<span className="eyebrow">Részletes elemzés</span>
|
||||
{waiting ? (
|
||||
<>
|
||||
<h2 id="detailed-title">Készül az elemzésed</h2>
|
||||
<p className="muted" role="status">
|
||||
A mesterséges intelligencia most írja meg a hat fejezetet a képleted alapján. Ez általában 1–2 perc; nyugodtan
|
||||
elhagyhatod az oldalt, az elemzés elkészül és itt vár.
|
||||
</p>
|
||||
<div className="skeleton" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2 id="detailed-title">Az egész képleted, fejezetekre bontva</h2>
|
||||
<p className="muted">
|
||||
Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési
|
||||
út. A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
|
||||
Kb. 1500 szó hat fejezetben: személyiség, érzelmek, gondolkodás, szerelem és kapcsolatok, hivatás, fejlődési út.
|
||||
A végén erősségek, kihívások és útravaló. Csak a képleted pozíciói alapján készül.
|
||||
</p>
|
||||
{analysis?.status === "failed" && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
Az előző kérés nem sikerült, az elemzést visszaadtuk a keretedbe. Próbáld újra.
|
||||
Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
@@ -111,23 +115,58 @@ export function DetailedAnalysis({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{remaining > 0 ? (
|
||||
confirming ? (
|
||||
|
||||
{isAdmin ? (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={request} disabled={busy}>
|
||||
<button type="button" className="btn btn-primary" onClick={() => start(false)} disabled={busy}>
|
||||
{busy ? "Indítás…" : "Részletes elemzés készítése"}
|
||||
</button>
|
||||
<span className="hint">Adminként ingyenes.</span>
|
||||
</div>
|
||||
) : left > 0 ? (
|
||||
step === "confirm" ? (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => start(false)} disabled={busy}>
|
||||
{busy ? "Indítás…" : "Igen, kérem az elemzést"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setConfirming(false)} disabled={busy}>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setStep("offer")} disabled={busy}>
|
||||
Mégse
|
||||
</button>
|
||||
<span className="hint">Ez felhasznál 1-et a {remaining} képletelemzésedből.</span>
|
||||
<span className="hint">Ez felhasznál 1-et a {left} képletelemzésedből.</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => setConfirming(true)}>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setStep("confirm")}>
|
||||
Részletes elemzés kérése
|
||||
</button>
|
||||
<span className="hint">Még {remaining} képletelemzésed van.</span>
|
||||
<span className="hint">Még {left} képletelemzésed van.</span>
|
||||
</div>
|
||||
)
|
||||
) : canPay ? (
|
||||
step === "pay" ? (
|
||||
<div className="pay-box">
|
||||
<div className="pay-line">
|
||||
<span>Részletes képletelemzés</span>
|
||||
<strong>1 db</strong>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => start(true)} disabled={busy}>
|
||||
{busy ? "Fizetés…" : "Fizetés"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setStep("offer")} disabled={busy}>
|
||||
Mégse
|
||||
</button>
|
||||
</div>
|
||||
<p className="hint">Tesztüzem: a fizetés még nincs bekötve, a gomb nem terhel semmit.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="form-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => setStep("pay")}>
|
||||
Részletes elemzés kérése
|
||||
</button>
|
||||
<Link href="/pelda" className="btn btn-ghost">
|
||||
Példa megtekintése
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
@@ -138,8 +177,6 @@ export function DetailedAnalysis({
|
||||
<span className="hint">A részletes elemzés fizetős; a csomagok hamarosan elérhetők.</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,36 +1,74 @@
|
||||
// Decorative zodiac wheel for the login page (pure SVG, no data needed).
|
||||
// Decorative chart wheel for the login page (pure SVG, sample sky from the design canvas).
|
||||
|
||||
const GLYPHS = ["♈", "♉", "♊", "♋", "♌", "♍", "♎", "♏", "♐", "♑", "♒", "♓"];
|
||||
// A few planets of a sample sky, for the aspect lines in the middle.
|
||||
const SAMPLE = [12, 75, 131, 200, 247, 302, 338];
|
||||
const SIGNS = ["♈", "♉", "♊", "♋", "♌", "♍", "♎", "♏", "♐", "♑", "♒", "♓"];
|
||||
const ASC = 182.73;
|
||||
const PLANETS: [string, number][] = [
|
||||
["☉", 53.61],
|
||||
["☽", 204.02],
|
||||
["☿", 46.72],
|
||||
["♀", 62.71],
|
||||
["♂", 334.49],
|
||||
["♃", 311.71],
|
||||
["♄", 80.06],
|
||||
["♅", 199.7],
|
||||
["♆", 246.42],
|
||||
["♇", 181.88],
|
||||
];
|
||||
// angle, orb, colour, dash (conjunctions are not drawn)
|
||||
const ASPECTS: [number, number, string, string | undefined][] = [
|
||||
[0, 7, "", undefined],
|
||||
[60, 5, "#7fb0ff", "1.2 1"],
|
||||
[90, 6, "#f08a4b", undefined],
|
||||
[120, 6, "#7fb0ff", undefined],
|
||||
[180, 7, "#f08a4b", "1.8 1"],
|
||||
];
|
||||
const VS = "︎"; // text presentation, not emoji
|
||||
|
||||
function point(deg: number, r: number) {
|
||||
const t = ((180 - deg) * Math.PI) / 180;
|
||||
const norm = (a: number) => ((a % 360) + 360) % 360;
|
||||
|
||||
function point(lon: number, r: number) {
|
||||
const t = ((180 + lon - ASC) * Math.PI) / 180;
|
||||
return { x: 50 + r * Math.cos(t), y: 50 - r * Math.sin(t) };
|
||||
}
|
||||
|
||||
export function ZodiacWheel({ className }: { className?: string }) {
|
||||
const lines: { a: number; b: number; hard: boolean }[] = [];
|
||||
SAMPLE.forEach((a, i) =>
|
||||
SAMPLE.slice(i + 1).forEach((b) => {
|
||||
let d = Math.abs(a - b) % 360;
|
||||
/** Glyph positions pushed at least 12° apart. */
|
||||
function spread(): { g: string; lon: number; at: number }[] {
|
||||
const out = PLANETS.map(([g, lon]) => ({ g, lon, at: lon })).sort((a, b) => a.at - b.at);
|
||||
for (let it = 0; it < 14; it++) {
|
||||
for (let k = 0; k < out.length; k++) {
|
||||
const a = out[k];
|
||||
const b = out[(k + 1) % out.length];
|
||||
const gap = norm(b.at - a.at);
|
||||
if (gap < 12) {
|
||||
a.at -= (12 - gap) / 2;
|
||||
b.at += (12 - gap) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function aspectLines() {
|
||||
const lines: { a: number; b: number; color: string; dash?: string }[] = [];
|
||||
PLANETS.forEach(([, a], i) =>
|
||||
PLANETS.slice(i + 1).forEach(([, b]) => {
|
||||
let d = Math.abs(norm(a) - norm(b));
|
||||
if (d > 180) d = 360 - d;
|
||||
if (Math.abs(d - 120) < 8 || Math.abs(d - 60) < 6) lines.push({ a, b, hard: false });
|
||||
else if (Math.abs(d - 90) < 7 || Math.abs(d - 180) < 8) lines.push({ a, b, hard: true });
|
||||
const hit = ASPECTS.find(([angle, orb]) => Math.abs(d - angle) <= orb);
|
||||
if (hit && hit[0] > 0) lines.push({ a, b, color: hit[2], dash: hit[3] });
|
||||
}),
|
||||
);
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function ZodiacWheel({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 100 100" aria-hidden="true">
|
||||
<circle cx="50" cy="50" r="49" fill="none" stroke="#2c3654" strokeWidth="0.5" />
|
||||
<circle cx="50" cy="50" r="38" fill="none" stroke="#2c3654" strokeWidth="0.35" />
|
||||
<circle cx="50" cy="50" r="24" fill="#0f1426" stroke="#263049" strokeWidth="0.35" />
|
||||
{GLYPHS.map((_, i) => {
|
||||
const a = point(i * 30, 38);
|
||||
const b = point(i * 30, 49);
|
||||
return <line key={`d${i}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke="#263049" strokeWidth="0.35" />;
|
||||
})}
|
||||
{GLYPHS.map((g, i) => {
|
||||
const p = point(i * 30 + 15, 43.5);
|
||||
<circle cx="50" cy="50" r="49.6" fill="none" stroke="#2c3654" strokeWidth="0.35" />
|
||||
<circle cx="50" cy="50" r="36" fill="none" stroke="#2c3654" strokeWidth="0.25" />
|
||||
<circle cx="50" cy="50" r="16" fill="#0f1426" stroke="#263049" strokeWidth="0.25" />
|
||||
{SIGNS.map((g, i) => {
|
||||
const p = point(i * 30 + 15, 43);
|
||||
return (
|
||||
<text
|
||||
key={g}
|
||||
@@ -38,18 +76,17 @@ export function ZodiacWheel({ className }: { className?: string }) {
|
||||
y={p.y}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
fontSize="5"
|
||||
fontSize="6.5"
|
||||
fill={i % 3 === 0 ? "#d9b46a" : "#5a6790"}
|
||||
style={{ fontFamily: "var(--font-symbols)" }}
|
||||
>
|
||||
{g}
|
||||
{"︎"}
|
||||
{g + VS}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{lines.map(({ a, b, hard }) => {
|
||||
const p = point(a, 24);
|
||||
const q = point(b, 24);
|
||||
{aspectLines().map(({ a, b, color, dash }) => {
|
||||
const p = point(a, 16);
|
||||
const q = point(b, 16);
|
||||
return (
|
||||
<line
|
||||
key={`${a}-${b}`}
|
||||
@@ -57,16 +94,33 @@ export function ZodiacWheel({ className }: { className?: string }) {
|
||||
y1={p.y}
|
||||
x2={q.x}
|
||||
y2={q.y}
|
||||
stroke={hard ? "#f08a4b" : "#7fb0ff"}
|
||||
strokeWidth="0.4"
|
||||
strokeDasharray={hard ? undefined : "1.4 0.8"}
|
||||
opacity="0.8"
|
||||
stroke={color}
|
||||
strokeWidth="0.32"
|
||||
strokeDasharray={dash}
|
||||
opacity="0.85"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{SAMPLE.map((d) => {
|
||||
const p = point(d, 24);
|
||||
return <circle key={d} cx={p.x} cy={p.y} r="0.9" fill="#ece6d8" />;
|
||||
{spread().map(({ g, lon, at }) => {
|
||||
const t1 = point(lon, 16);
|
||||
const t2 = point(lon, 19.5);
|
||||
const p = point(at, 26.5);
|
||||
return (
|
||||
<g key={g}>
|
||||
<line x1={t1.x} y1={t1.y} x2={t2.x} y2={t2.y} stroke="#ece6d8" strokeWidth="0.35" opacity="0.9" />
|
||||
<text
|
||||
x={p.x}
|
||||
y={p.y}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
fontSize="5"
|
||||
fill="#ece6d8"
|
||||
style={{ fontFamily: "var(--font-symbols)" }}
|
||||
>
|
||||
{g + VS}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,14 @@ export interface Me {
|
||||
providers: string[];
|
||||
primary_chart_id: string | null;
|
||||
analyses_left: UnitBalance;
|
||||
birth_change: BirthChange;
|
||||
}
|
||||
|
||||
/** Limit on changing the own birth data (the notice text comes from the backend). */
|
||||
export interface BirthChange {
|
||||
limited: boolean;
|
||||
next_change_at: string | null;
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
/** Detailed analyses left, per kind. */
|
||||
@@ -32,6 +40,7 @@ export interface PublicConfig {
|
||||
summary_model: string;
|
||||
password_login: boolean;
|
||||
password_min_length: number;
|
||||
mock_payments: boolean;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
|
||||
Reference in New Issue
Block a user