mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 09:58:08 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a5c9d497a | ||
|
|
b847dba411 | ||
|
|
f0e9a06c44 | ||
|
|
ce24df53d9 | ||
|
|
3fac565c76 | ||
|
|
43900921a5 | ||
|
|
6068ef7a93 | ||
|
|
83fdc9e786 |
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Production error monitoring service for Nomad Karaoke."""
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Configuration for the production error monitoring service.
|
||||
|
||||
All constants, service lists, and environment-driven configuration
|
||||
functions used across the error monitor modules.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GCP project settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
GCP_PROJECT: str = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Log querying settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: How far back to look for errors on each run (minutes).
|
||||
LOOKBACK_MINUTES: int = 15
|
||||
|
||||
#: Maximum number of log entries to fetch per service per run.
|
||||
MAX_LOG_ENTRIES: int = 500
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monitored services
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MONITORED_CLOUD_RUN_SERVICES: list[str] = [
|
||||
"karaoke-backend",
|
||||
"karaoke-decide",
|
||||
"audio-separator",
|
||||
]
|
||||
|
||||
MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"video-encoding-job",
|
||||
"lyrics-transcription-job",
|
||||
"audio-separation-job",
|
||||
"audio-download-job",
|
||||
]
|
||||
|
||||
MONITORED_CLOUD_FUNCTIONS: list[str] = [
|
||||
"gdrive-validator",
|
||||
"runner_manager",
|
||||
"backup_to_aws",
|
||||
"divebar_mirror",
|
||||
"kn_data_sync",
|
||||
"divebar_lookup",
|
||||
"encoding_worker_idle",
|
||||
]
|
||||
|
||||
MONITORED_GCE_INSTANCES: list[str] = [
|
||||
"encoding-worker-a",
|
||||
"encoding-worker-b",
|
||||
"flacfetch-vm",
|
||||
"divebar-sync-vm",
|
||||
]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Service dependency map
|
||||
# Human-readable description of which services depend on which workers.
|
||||
# Used as LLM context when generating root-cause analysis.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SERVICE_DEPENDENCY_MAP: str = """\
|
||||
karaoke-backend (main API)
|
||||
→ video-encoding-job (Cloud Run Job, triggered per order)
|
||||
→ lyrics-transcription-job (Cloud Run Job, triggered after audio-sep)
|
||||
→ audio-separation-job (Cloud Run Job, runs on Cloud Run GPU)
|
||||
→ audio-download-job (Cloud Run Job, uses flacfetch-vm)
|
||||
→ gdrive-validator (Cloud Function, validates output files)
|
||||
→ encoding-worker-a/b (GCE VMs, long-running encoding workers)
|
||||
|
||||
karaoke-decide (catalog / discovery API)
|
||||
→ kn_data_sync (Cloud Function, syncs KaraokeNerds catalog)
|
||||
→ divebar_mirror (Cloud Function, mirrors Divebar catalog)
|
||||
→ divebar_lookup (Cloud Function, single-song lookup)
|
||||
|
||||
audio-separator (Cloud Run service, GPU stem separation)
|
||||
→ audio-separation-job (Cloud Run Job, launched by audio-separator)
|
||||
|
||||
flacfetch-vm (GCE VM)
|
||||
→ audio-download-job (initiated by karaoke-backend)
|
||||
|
||||
divebar-sync-vm (GCE VM)
|
||||
→ divebar_mirror (Cloud Function, reads from this VM)
|
||||
|
||||
Shared infrastructure:
|
||||
→ runner_manager (Cloud Function, manages encoding worker lifecycle)
|
||||
→ encoding_worker_idle (Cloud Function, shuts down idle encoding workers)
|
||||
→ backup_to_aws (Cloud Function, daily GCS → S3 backup)
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM analysis settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-2.0-flash-001")
|
||||
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "us-central1")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Spike detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: An error count is a spike if it exceeds SPIKE_MULTIPLIER × baseline average.
|
||||
SPIKE_MULTIPLIER: float = 5.0
|
||||
|
||||
#: Minimum absolute error count before spike detection fires (avoids noise).
|
||||
SPIKE_MIN_COUNT: int = 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auto-resolution settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Multiply LOOKBACK_MINUTES by this to get auto-resolve window in minutes.
|
||||
AUTO_RESOLVE_MULTIPLIER: int = 8
|
||||
|
||||
#: Minimum hours before a pattern can be auto-resolved.
|
||||
AUTO_RESOLVE_MIN_HOURS: int = 6
|
||||
|
||||
#: Maximum hours before a pattern is force-resolved even if still active.
|
||||
AUTO_RESOLVE_MAX_HOURS: int = 168 # 1 week
|
||||
|
||||
#: Fallback resolve window (hours) if baseline data is unavailable.
|
||||
AUTO_RESOLVE_FALLBACK_HOURS: int = 48
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum Discord messages to send per monitor run (rate-limit guard).
|
||||
MAX_DISCORD_MESSAGES_PER_RUN: int = 10
|
||||
|
||||
#: Discord API hard limit on message length.
|
||||
DISCORD_MAX_MESSAGE_LENGTH: int = 2000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pattern tracking settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum number of active error patterns to track in Firestore.
|
||||
MAX_ACTIVE_PATTERNS: int = 500
|
||||
|
||||
#: Rolling window used when computing error baselines.
|
||||
ROLLING_WINDOW_DAYS: int = 7
|
||||
|
||||
#: Maximum length of a normalized error message stored in Firestore.
|
||||
MAX_NORMALIZED_MESSAGE_LENGTH: int = 200
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_llm_enabled() -> bool:
|
||||
"""Return True if LLM analysis is enabled via the LLM_ANALYSIS_ENABLED env var."""
|
||||
return os.environ.get("LLM_ANALYSIS_ENABLED", "false").strip().lower() == "true"
|
||||
|
||||
|
||||
def get_discord_webhook_secret_name() -> str:
|
||||
"""Return the Secret Manager secret name for the Discord webhook URL."""
|
||||
return os.environ.get("DISCORD_WEBHOOK_SECRET_NAME", "error-monitor-discord-webhook")
|
||||
|
||||
|
||||
def get_digest_mode() -> bool:
|
||||
"""Return True if the monitor should run in digest mode (batch alerts instead of immediate).
|
||||
|
||||
In digest mode all alerts are bundled into a single Discord message sent at
|
||||
the end of the run, rather than sending one message per error pattern.
|
||||
"""
|
||||
return os.environ.get("DIGEST_MODE", "false").strip().lower() == "true"
|
||||
@@ -0,0 +1,323 @@
|
||||
"""Discord alert client for the production error monitoring service.
|
||||
|
||||
Provides formatting functions for each alert type, and an ErrorMonitorDiscord
|
||||
webhook client that rate-limits outbound messages to MAX_DISCORD_MESSAGES_PER_RUN
|
||||
per monitor run.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.discord import (
|
||||
ErrorMonitorDiscord,
|
||||
format_new_pattern_alert,
|
||||
format_incident_alert,
|
||||
format_auto_resolved_alert,
|
||||
format_spike_alert,
|
||||
format_daily_digest,
|
||||
)
|
||||
|
||||
discord = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/...")
|
||||
msg = format_new_pattern_alert(...)
|
||||
discord.send_message(msg)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
DISCORD_MAX_MESSAGE_LENGTH,
|
||||
MAX_DISCORD_MESSAGES_PER_RUN,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SEVERITY_EMOJI: dict[str, str] = {
|
||||
"P0": "🚨",
|
||||
"P1": "🔴",
|
||||
"P2": "⚠️",
|
||||
"P3": "🟡",
|
||||
}
|
||||
|
||||
_EASTERN = ZoneInfo("America/New_York")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _now_eastern() -> str:
|
||||
"""Return the current Eastern time as 'HH:MM AM/PM ET' (DST-aware)."""
|
||||
now = datetime.now(tz=_EASTERN)
|
||||
return now.strftime("%I:%M %p ET").lstrip("0")
|
||||
|
||||
|
||||
def _truncate(msg: str) -> str:
|
||||
"""Truncate *msg* to DISCORD_MAX_MESSAGE_LENGTH characters."""
|
||||
if len(msg) <= DISCORD_MAX_MESSAGE_LENGTH:
|
||||
return msg
|
||||
suffix = "…"
|
||||
return msg[: DISCORD_MAX_MESSAGE_LENGTH - len(suffix)] + suffix
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Formatting functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def format_new_pattern_alert(
|
||||
service: str,
|
||||
resource_type: str,
|
||||
normalized_message: str,
|
||||
sample_message: str,
|
||||
count: int,
|
||||
first_seen: str,
|
||||
) -> str:
|
||||
"""Format a Discord alert for a newly-detected error pattern.
|
||||
|
||||
Args:
|
||||
service: Name of the service emitting the error.
|
||||
resource_type: GCP resource type (e.g. 'cloud_run_service', 'gce_instance').
|
||||
normalized_message: Normalised error pattern string.
|
||||
sample_message: A representative raw log message.
|
||||
count: Number of occurrences seen so far.
|
||||
first_seen: ISO 8601 timestamp when the pattern was first seen.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"🔴 **New Error Pattern Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Resource type:** {resource_type}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Sample:** {sample_message}",
|
||||
f"**Count:** {count}",
|
||||
f"**First seen:** {first_seen}",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
f"",
|
||||
f"To investigate: `/prod-investigate {service} \"{normalized_message}\"`",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_incident_alert(
|
||||
title: str,
|
||||
severity: str,
|
||||
root_cause: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
patterns: list[dict],
|
||||
) -> str:
|
||||
"""Format a Discord alert for an analysed incident (LLM-generated).
|
||||
|
||||
Args:
|
||||
title: Short incident title.
|
||||
severity: Severity level — one of P0, P1, P2, P3.
|
||||
root_cause: Human-readable root-cause analysis.
|
||||
suggested_fix: Recommended remediation steps.
|
||||
primary_service: The main service involved in the incident.
|
||||
patterns: List of dicts, each with keys: service, normalized_message, count.
|
||||
Only the first 5 are shown; normalized_message is truncated to 80 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
emoji = SEVERITY_EMOJI.get(severity, "⚠️")
|
||||
lines = [
|
||||
f"{emoji} **[{severity}] {title}**",
|
||||
f"",
|
||||
f"**Primary service:** {primary_service}",
|
||||
f"**Root cause:** {root_cause}",
|
||||
f"**Suggested fix:** {suggested_fix}",
|
||||
]
|
||||
|
||||
shown_patterns = patterns[:5]
|
||||
if shown_patterns:
|
||||
lines.append("")
|
||||
lines.append(f"**Patterns ({len(shown_patterns)} of {len(patterns)}):**")
|
||||
for p in shown_patterns:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("normalized_message", "")[:80]
|
||||
cnt = p.get("count", 0)
|
||||
lines.append(f" • `{svc}` — {msg} ({cnt}x)")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Alerted at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_auto_resolved_alert(resolved_patterns: list[dict]) -> str:
|
||||
"""Format a consolidated auto-resolved alert.
|
||||
|
||||
Args:
|
||||
resolved_patterns: List of dicts, each with keys: service, message, hours_silent.
|
||||
Only the first 8 are shown; message is truncated to 60 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"✅ **Patterns Auto-Resolved**",
|
||||
f"",
|
||||
]
|
||||
|
||||
shown = resolved_patterns[:8]
|
||||
if shown:
|
||||
for p in shown:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("message", "")[:60]
|
||||
hours = p.get("hours_silent", 0)
|
||||
lines.append(f" • `{svc}` — {msg} (silent {hours}h)")
|
||||
else:
|
||||
lines.append(" *(no patterns)*")
|
||||
|
||||
if len(resolved_patterns) > 8:
|
||||
lines.append(f" … and {len(resolved_patterns) - 8} more")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Resolved at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_spike_alert(
|
||||
service: str,
|
||||
normalized_message: str,
|
||||
current_count: int,
|
||||
rolling_average: float,
|
||||
) -> str:
|
||||
"""Format a Discord alert for an error rate spike.
|
||||
|
||||
Args:
|
||||
service: Name of the service.
|
||||
normalized_message: Normalised error pattern string.
|
||||
current_count: Error count in the current window.
|
||||
rolling_average: Baseline rolling average count.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
if rolling_average > 0:
|
||||
multiplier = current_count / rolling_average
|
||||
multiplier_str = f"{multiplier:.1f}x"
|
||||
else:
|
||||
multiplier_str = "∞x"
|
||||
|
||||
lines = [
|
||||
f"⚠️ **Error Rate Spike Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Current count:** {current_count}",
|
||||
f"**Normal (rolling avg):** {rolling_average}",
|
||||
f"**Multiplier:** {multiplier_str} above normal",
|
||||
f"",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_daily_digest(
|
||||
total_errors: int,
|
||||
new_patterns: int,
|
||||
resolved_patterns: int,
|
||||
active_patterns: int,
|
||||
per_service_counts: dict,
|
||||
) -> str:
|
||||
"""Format the daily 24h error digest.
|
||||
|
||||
Args:
|
||||
total_errors: Total error count in the last 24 hours.
|
||||
new_patterns: Number of new error patterns detected.
|
||||
resolved_patterns: Number of patterns auto-resolved.
|
||||
active_patterns: Total number of currently active patterns.
|
||||
per_service_counts: Mapping of service name → error count.
|
||||
Displayed sorted by count descending.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"📊 **Daily Error Digest (24h)**",
|
||||
f"",
|
||||
f"**Total errors:** {total_errors}",
|
||||
f"**New patterns:** {new_patterns}",
|
||||
f"**Resolved patterns:** {resolved_patterns}",
|
||||
f"**Active patterns:** {active_patterns}",
|
||||
]
|
||||
|
||||
if per_service_counts:
|
||||
lines.append("")
|
||||
lines.append("**Per-service breakdown:**")
|
||||
sorted_services = sorted(per_service_counts.items(), key=lambda kv: kv[1], reverse=True)
|
||||
for svc, cnt in sorted_services:
|
||||
lines.append(f" • `{svc}`: {cnt}")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Generated at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord webhook client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorMonitorDiscord:
|
||||
"""Webhook client for sending error monitor alerts to Discord.
|
||||
|
||||
Enforces a per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN to avoid
|
||||
flooding the channel during high-volume incident windows.
|
||||
|
||||
Attributes:
|
||||
webhook_url: The Discord incoming webhook URL.
|
||||
messages_sent: Counter of messages attempted this run (success or failure).
|
||||
"""
|
||||
|
||||
def __init__(self, webhook_url: str) -> None:
|
||||
self.webhook_url = webhook_url
|
||||
self.messages_sent: int = 0
|
||||
|
||||
def send_message(self, content: str) -> bool:
|
||||
"""Send a message to the configured Discord webhook.
|
||||
|
||||
Rate-limits: if messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN, the
|
||||
message is silently skipped and False is returned without incrementing
|
||||
the counter.
|
||||
|
||||
Args:
|
||||
content: The message text to send (should be pre-formatted and
|
||||
pre-truncated to ≤2000 chars).
|
||||
|
||||
Returns:
|
||||
True if the message was sent successfully, False otherwise.
|
||||
"""
|
||||
if self.messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN:
|
||||
logger.warning(
|
||||
"Discord rate limit reached (%d messages sent this run); skipping message.",
|
||||
self.messages_sent,
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.webhook_url,
|
||||
json={"content": content},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.debug("Discord message sent successfully.")
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error("Failed to send Discord message: %s", exc)
|
||||
return False
|
||||
finally:
|
||||
self.messages_sent += 1
|
||||
@@ -0,0 +1,489 @@
|
||||
"""Firestore adapter for the production error monitoring service.
|
||||
|
||||
Handles all CRUD for three Firestore collections:
|
||||
- error_patterns: normalized error patterns (pattern_id as doc ID)
|
||||
- error_incidents: groups of related patterns (incident_id as doc ID)
|
||||
- discord_alerts: audit trail for Discord messages (alert_id as doc ID)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
AUTO_RESOLVE_FALLBACK_HOURS,
|
||||
AUTO_RESOLVE_MAX_HOURS,
|
||||
AUTO_RESOLVE_MIN_HOURS,
|
||||
AUTO_RESOLVE_MULTIPLIER,
|
||||
ROLLING_WINDOW_DAYS,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatternData:
|
||||
"""Input data for creating or updating an error pattern."""
|
||||
|
||||
pattern_id: str
|
||||
service: str
|
||||
resource_type: str
|
||||
normalized_message: str
|
||||
sample_message: str
|
||||
count: int
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpsertResult:
|
||||
"""Result of an upsert_pattern operation."""
|
||||
|
||||
pattern_id: str
|
||||
is_new: bool
|
||||
previous_status: str | None = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Collection names
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_COL_PATTERNS = "error_patterns"
|
||||
_COL_INCIDENTS = "error_incidents"
|
||||
_COL_ALERTS = "discord_alerts"
|
||||
|
||||
# Statuses that can be queried as "active"
|
||||
_ACTIVE_STATUSES = ["new", "acknowledged", "known"]
|
||||
|
||||
# Statuses from which a pattern is reactivated when the error recurs
|
||||
_REACTIVATION_STATUSES = {"auto_resolved", "fixed"}
|
||||
|
||||
# Statuses eligible for auto-resolve checking
|
||||
_AUTO_RESOLVE_ELIGIBLE = {"new", "acknowledged"}
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
"""Return current UTC datetime."""
|
||||
return datetime.now(tz=timezone.utc)
|
||||
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
"""Serialise a datetime to ISO-8601 string."""
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
def _generate_id(prefix: str, fmt: str) -> str:
|
||||
"""Generate a time-stamped ID with 8 hex random suffix.
|
||||
|
||||
Args:
|
||||
prefix: e.g. "inc" or "alert"
|
||||
fmt: strftime format string applied to utcnow(), e.g. "%Y%m%d_%H%M"
|
||||
"""
|
||||
ts = _utcnow().strftime(fmt)
|
||||
suffix = secrets.token_hex(4) # 8 hex chars
|
||||
return f"{prefix}_{ts}_{suffix}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Adapter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorPatternsAdapter:
|
||||
"""Firestore CRUD adapter for error monitoring collections.
|
||||
|
||||
Args:
|
||||
db: Optional Firestore client. If omitted, a default client for the
|
||||
``nomadkaraoke`` GCP project is constructed on first use.
|
||||
"""
|
||||
|
||||
def __init__(self, db=None) -> None:
|
||||
if db is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
self._db = db
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — read
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_pattern(self, pattern_id: str) -> dict | None:
|
||||
"""Return the pattern document as a dict, or None if it doesn't exist.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID in the ``error_patterns`` collection.
|
||||
"""
|
||||
snap = self._db.collection(_COL_PATTERNS).document(pattern_id).get()
|
||||
if not snap.exists:
|
||||
return None
|
||||
return snap.to_dict()
|
||||
|
||||
def get_active_patterns(self) -> list[dict]:
|
||||
"""Return all patterns with status in [new, acknowledged, known]."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", _ACTIVE_STATUSES
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
def get_patterns_for_auto_resolve(self) -> list[dict]:
|
||||
"""Return active patterns eligible for auto-resolution (new or acknowledged)."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", list(_AUTO_RESOLVE_ELIGIBLE)
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — upsert
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def upsert_pattern(self, data: PatternData) -> UpsertResult:
|
||||
"""Create a new pattern or update an existing one.
|
||||
|
||||
New pattern:
|
||||
- status="new", severity="P3"
|
||||
- Initialize ``rolling_counts`` with one entry for this run.
|
||||
|
||||
Existing pattern:
|
||||
- Increment ``total_count`` and append to ``rolling_counts``.
|
||||
- If status was ``auto_resolved`` or ``fixed`` → reactivate (set status="new").
|
||||
- Prune ``rolling_counts`` entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Returns:
|
||||
UpsertResult with ``is_new=True`` for brand-new patterns *and* for
|
||||
reactivated patterns (auto_resolved → new, fixed → new).
|
||||
"""
|
||||
doc_ref = self._db.collection(_COL_PATTERNS).document(data.pattern_id)
|
||||
snap = doc_ref.get()
|
||||
ts_iso = _iso(data.timestamp)
|
||||
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count}
|
||||
|
||||
if not snap.exists:
|
||||
# ── brand new pattern ──────────────────────────────────────────
|
||||
doc_ref.set(
|
||||
{
|
||||
"pattern_id": data.pattern_id,
|
||||
"service": data.service,
|
||||
"resource_type": data.resource_type,
|
||||
"normalized_message": data.normalized_message,
|
||||
"sample_message": data.sample_message,
|
||||
"status": "new",
|
||||
"severity": "P3",
|
||||
"total_count": data.count,
|
||||
"rolling_counts": [new_rolling_entry],
|
||||
"first_seen": ts_iso,
|
||||
"last_seen": ts_iso,
|
||||
"alerted_at": None,
|
||||
"created_at": ts_iso,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
)
|
||||
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
|
||||
|
||||
# ── existing pattern ───────────────────────────────────────────────
|
||||
existing = snap.to_dict()
|
||||
prev_status = existing.get("status", "new")
|
||||
|
||||
rolling_counts: list[dict] = list(existing.get("rolling_counts") or [])
|
||||
rolling_counts.append(new_rolling_entry)
|
||||
rolling_counts = self._prune_rolling_counts(rolling_counts)
|
||||
|
||||
update: dict[str, Any] = {
|
||||
"total_count": existing.get("total_count", 0) + data.count,
|
||||
"rolling_counts": rolling_counts,
|
||||
"last_seen": ts_iso,
|
||||
"sample_message": data.sample_message,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
|
||||
# Reactivation: pattern was considered resolved/fixed but error recurred
|
||||
is_new = False
|
||||
if prev_status in _REACTIVATION_STATUSES:
|
||||
update["status"] = "new"
|
||||
update["alerted_at"] = None
|
||||
is_new = True
|
||||
|
||||
doc_ref.update(update)
|
||||
return UpsertResult(
|
||||
pattern_id=data.pattern_id,
|
||||
is_new=is_new,
|
||||
previous_status=prev_status,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — status changes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def auto_resolve_pattern(self, pattern_id: str, hours_silent: float) -> None:
|
||||
"""Mark a pattern as auto-resolved.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
hours_silent: How many hours the pattern has been silent.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "auto_resolved",
|
||||
"auto_resolve_hours_silent": hours_silent,
|
||||
"auto_resolved_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def resolve_pattern(
|
||||
self,
|
||||
pattern_id: str,
|
||||
pr_url: str | None = None,
|
||||
note: str = "",
|
||||
) -> None:
|
||||
"""Mark a pattern as fixed (human-resolved).
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
pr_url: Optional URL of the PR that fixed this pattern.
|
||||
note: Optional human-readable note about the fix.
|
||||
"""
|
||||
now_iso = _iso(_utcnow())
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "fixed",
|
||||
"fixed_by": {
|
||||
"pr_url": pr_url,
|
||||
"note": note,
|
||||
"fixed_at": now_iso,
|
||||
},
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
def update_pattern_alerted(self, pattern_id: str) -> None:
|
||||
"""Set the ``alerted_at`` timestamp on a pattern.
|
||||
|
||||
Called after a Discord alert has been successfully sent for the pattern.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"alerted_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def merge_pattern(self, source_id: str, target_id: str, reason: str) -> None:
|
||||
"""Merge *source* into *target* by muting the source pattern.
|
||||
|
||||
Args:
|
||||
source_id: Pattern to mute.
|
||||
target_id: Pattern that the source is being merged into.
|
||||
reason: Human-readable rationale for the merge.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(source_id).update(
|
||||
{
|
||||
"status": "muted",
|
||||
"merged_into": target_id,
|
||||
"merge_reason": reason,
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auto-resolve logic
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def check_auto_resolve(self, pattern: dict) -> float | None:
|
||||
"""Determine whether *pattern* should be auto-resolved.
|
||||
|
||||
Computes the frequency-aware silence threshold and compares it against
|
||||
how long the pattern has been silent.
|
||||
|
||||
Args:
|
||||
pattern: A pattern document dict (as returned by get_pattern).
|
||||
|
||||
Returns:
|
||||
The number of hours the pattern has been silent if the threshold is
|
||||
exceeded, or ``None`` if the pattern should not yet be resolved.
|
||||
"""
|
||||
status = pattern.get("status", "")
|
||||
if status not in _AUTO_RESOLVE_ELIGIBLE:
|
||||
return None
|
||||
|
||||
last_seen_str = pattern.get("last_seen")
|
||||
if not last_seen_str:
|
||||
return None
|
||||
|
||||
last_seen = datetime.fromisoformat(last_seen_str)
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
|
||||
# Ensure both datetimes are tz-aware for subtraction
|
||||
if last_seen.tzinfo is None:
|
||||
last_seen = last_seen.replace(tzinfo=timezone.utc)
|
||||
|
||||
hours_silent = (now - last_seen).total_seconds() / 3600.0
|
||||
|
||||
rolling_counts = pattern.get("rolling_counts") or []
|
||||
threshold = self._compute_resolve_threshold(rolling_counts)
|
||||
|
||||
if hours_silent >= threshold:
|
||||
return hours_silent
|
||||
return None
|
||||
|
||||
def _compute_resolve_threshold(self, rolling_counts: list[dict]) -> float:
|
||||
"""Compute the frequency-aware auto-resolve threshold in hours.
|
||||
|
||||
Algorithm:
|
||||
1. If fewer than 3 data points → return AUTO_RESOLVE_FALLBACK_HOURS (48).
|
||||
2. Compute mean interval between consecutive timestamps.
|
||||
3. threshold = mean_interval_hours * AUTO_RESOLVE_MULTIPLIER.
|
||||
4. Clamp result to [AUTO_RESOLVE_MIN_HOURS, AUTO_RESOLVE_MAX_HOURS].
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Threshold in hours (float).
|
||||
"""
|
||||
if len(rolling_counts) < 3:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
# Parse timestamps and sort ascending
|
||||
timestamps: list[datetime] = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
timestamps.append(ts)
|
||||
timestamps.sort()
|
||||
|
||||
# Compute pairwise intervals
|
||||
intervals_hours: list[float] = []
|
||||
for i in range(1, len(timestamps)):
|
||||
delta = (timestamps[i] - timestamps[i - 1]).total_seconds() / 3600.0
|
||||
intervals_hours.append(delta)
|
||||
|
||||
if not intervals_hours:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
mean_interval = sum(intervals_hours) / len(intervals_hours)
|
||||
threshold = mean_interval * AUTO_RESOLVE_MULTIPLIER
|
||||
|
||||
# Clamp to configured bounds
|
||||
threshold = max(float(AUTO_RESOLVE_MIN_HOURS), threshold)
|
||||
threshold = min(float(AUTO_RESOLVE_MAX_HOURS), threshold)
|
||||
return threshold
|
||||
|
||||
def _prune_rolling_counts(self, rolling_counts: list[dict]) -> list[dict]:
|
||||
"""Remove rolling_count entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Filtered list with only recent entries.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return []
|
||||
|
||||
cutoff = _utcnow() - timedelta(days=ROLLING_WINDOW_DAYS)
|
||||
result = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts >= cutoff:
|
||||
result.append(entry)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Incidents
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_incident(
|
||||
self,
|
||||
title: str,
|
||||
root_cause: str,
|
||||
severity: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
pattern_ids: list[str],
|
||||
used_llm: bool,
|
||||
) -> str:
|
||||
"""Create a new incident document and link associated patterns.
|
||||
|
||||
Args:
|
||||
title: Short human-readable title.
|
||||
root_cause: LLM-generated or manual root-cause description.
|
||||
severity: Severity string (e.g. "P1", "P2", "P3").
|
||||
suggested_fix: Suggested remediation steps.
|
||||
primary_service: The primary affected service.
|
||||
pattern_ids: List of pattern_ids that belong to this incident.
|
||||
used_llm: Whether LLM analysis was used to generate this incident.
|
||||
|
||||
Returns:
|
||||
The generated incident_id string.
|
||||
"""
|
||||
incident_id = _generate_id("inc", "%Y%m%d_%H%M")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_INCIDENTS).document(incident_id).set(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"title": title,
|
||||
"root_cause": root_cause,
|
||||
"severity": severity,
|
||||
"suggested_fix": suggested_fix,
|
||||
"primary_service": primary_service,
|
||||
"pattern_ids": pattern_ids,
|
||||
"used_llm": used_llm,
|
||||
"created_at": now_iso,
|
||||
"updated_at": now_iso,
|
||||
"status": "open",
|
||||
}
|
||||
)
|
||||
|
||||
# Link each pattern back to this incident
|
||||
for pattern_id in pattern_ids:
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
return incident_id
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Discord audit trail
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def log_discord_alert(
|
||||
self,
|
||||
alert_type: str,
|
||||
content: str,
|
||||
success: bool,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
"""Write an audit record to the ``discord_alerts`` collection.
|
||||
|
||||
Args:
|
||||
alert_type: Category of alert (e.g. "new_pattern", "digest").
|
||||
content: The message body that was (or would have been) sent.
|
||||
success: Whether the Discord webhook call succeeded.
|
||||
metadata: Optional additional data (pattern_ids, incident_id, etc.).
|
||||
"""
|
||||
alert_id = _generate_id("alert", "%Y%m%d_%H%M%S")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_ALERTS).document(alert_id).set(
|
||||
{
|
||||
"alert_id": alert_id,
|
||||
"alert_type": alert_type,
|
||||
"content": content,
|
||||
"success": success,
|
||||
"metadata": metadata or {},
|
||||
"created_at": now_iso,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Known infrastructure noise patterns for the production error monitoring service.
|
||||
|
||||
Filters out transient, expected log messages so the error monitor is not flooded
|
||||
with Cloud Run cold-start probes, deploy events, spot VM preemptions, and similar
|
||||
operational noise.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
reason = should_ignore(service, message)
|
||||
if reason:
|
||||
# skip this log entry — it's known infrastructure noise
|
||||
...
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class IgnoreReason:
|
||||
"""Describes why a log entry should be suppressed.
|
||||
|
||||
Attributes:
|
||||
pattern_name: Machine-readable name of the matching ignore pattern.
|
||||
reason: Human-readable explanation of why this is infrastructure noise.
|
||||
"""
|
||||
|
||||
pattern_name: str
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled ignore patterns (applied in order)
|
||||
# All patterns use re.IGNORECASE for case-insensitive matching.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
|
||||
(
|
||||
"startup_probe",
|
||||
re.compile(r"startup probe failed", re.IGNORECASE),
|
||||
"Cloud Run cold start — startup probe failure is transient and expected",
|
||||
),
|
||||
(
|
||||
"ready_condition",
|
||||
re.compile(r"ready condition status changed", re.IGNORECASE),
|
||||
"Cloud Run deploy event — readiness condition change is expected on deploy",
|
||||
),
|
||||
(
|
||||
"spot_preemption",
|
||||
re.compile(r"instance was preempted", re.IGNORECASE),
|
||||
"Spot/preemptible VM preemption — expected behaviour for spot instances",
|
||||
),
|
||||
(
|
||||
"idle_shutdown",
|
||||
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
|
||||
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
|
||||
),
|
||||
(
|
||||
"health_check_404",
|
||||
re.compile(
|
||||
r"(?:GET|HEAD)\b[^\n]*?/health[^\n]*?\b(?:404|not found)\b",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
"Load balancer health check returning 404 — transient during cold start",
|
||||
),
|
||||
(
|
||||
"scheduler_retry",
|
||||
re.compile(r"cloud scheduler.*retry", re.IGNORECASE),
|
||||
"Cloud Scheduler transient retry — expected on intermittent job failures",
|
||||
),
|
||||
(
|
||||
"runner_startup",
|
||||
re.compile(r"github\.runner\..*(?:starting|stopping|idle)", re.IGNORECASE),
|
||||
"GitHub Actions runner lifecycle event — expected during runner start/stop",
|
||||
),
|
||||
(
|
||||
"container_shutdown",
|
||||
re.compile(r"container called exit\(0\)", re.IGNORECASE),
|
||||
"Container clean exit — exit code 0 indicates a graceful, expected shutdown",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def should_ignore(service: str, message: str) -> IgnoreReason | None:
|
||||
"""Check whether a log entry matches a known infrastructure noise pattern.
|
||||
|
||||
The check is purely message-based; ``service`` is accepted for API symmetry
|
||||
and future service-specific overrides but does not gate any pattern today.
|
||||
|
||||
Args:
|
||||
service: The originating service name (e.g. ``"karaoke-backend"``).
|
||||
message: The raw log message string to evaluate.
|
||||
|
||||
Returns:
|
||||
An :class:`IgnoreReason` if the message matches a known noise pattern,
|
||||
or ``None`` if the message should be processed normally.
|
||||
"""
|
||||
if not message:
|
||||
return None
|
||||
|
||||
for pattern_name, pattern, reason in _IGNORE_PATTERNS:
|
||||
if pattern.search(message):
|
||||
return IgnoreReason(pattern_name=pattern_name, reason=reason)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,429 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Both functions fall back gracefully when the LLM is unavailable or returns
|
||||
unparseable output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataclasses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Incident:
|
||||
"""A grouped incident produced by LLM analysis or the fallback grouper."""
|
||||
|
||||
title: str
|
||||
root_cause: str | None
|
||||
severity: str # P0 / P1 / P2 / P3
|
||||
suggested_fix: str | None
|
||||
primary_service: str
|
||||
pattern_indices: list[int]
|
||||
|
||||
|
||||
@dataclass
|
||||
class IncidentAnalysis:
|
||||
"""The result of an incident grouping pass."""
|
||||
|
||||
incidents: list[Incident]
|
||||
used_llm: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplicateGroup:
|
||||
"""A canonical pattern plus the new patterns that duplicate it."""
|
||||
|
||||
canonical_index: int
|
||||
duplicate_indices: list[int]
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM call helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RETRY_ATTEMPTS = 3
|
||||
_RETRY_BASE_DELAY = 2.0 # seconds
|
||||
|
||||
|
||||
def _call_llm(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
temperature: float = 0.2,
|
||||
) -> str:
|
||||
"""Call Gemini and return the response text.
|
||||
|
||||
Retries up to _RETRY_ATTEMPTS times with exponential back-off on failure.
|
||||
|
||||
Args:
|
||||
system_prompt: System instruction for the model.
|
||||
user_prompt: User-facing prompt content.
|
||||
temperature: Sampling temperature (lower = more deterministic).
|
||||
|
||||
Returns:
|
||||
The model's response text.
|
||||
|
||||
Raises:
|
||||
Exception: Re-raises the last exception after all retries are exhausted.
|
||||
"""
|
||||
last_exc: Exception | None = None
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
config=genai_types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=temperature,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
"LLM call failed (attempt %d/%d): %s — retrying in %.1fs",
|
||||
attempt + 1,
|
||||
_RETRY_ATTEMPTS,
|
||||
exc,
|
||||
delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
raise last_exc # type: ignore[misc]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Response parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_MD_CODE_BLOCK_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)```", re.IGNORECASE)
|
||||
|
||||
|
||||
def _strip_markdown_code_block(text: str) -> str:
|
||||
"""Remove surrounding ```json ... ``` or ``` ... ``` fences if present."""
|
||||
match = _MD_CODE_BLOCK_RE.search(text)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _parse_llm_response(text: str) -> IncidentAnalysis | None:
|
||||
"""Parse the LLM response text into an IncidentAnalysis.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output, possibly wrapped in a markdown code block.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis on success, None on any parse failure.
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("LLM returned non-JSON response (first 200 chars): %.200s", text)
|
||||
return None
|
||||
|
||||
if "incidents" not in data:
|
||||
logger.warning("LLM response missing 'incidents' key: %s", list(data.keys()))
|
||||
return None
|
||||
|
||||
incidents: list[Incident] = []
|
||||
for raw in data["incidents"]:
|
||||
try:
|
||||
incidents.append(
|
||||
Incident(
|
||||
title=raw.get("title", "Unknown incident"),
|
||||
root_cause=raw.get("root_cause"),
|
||||
severity=raw.get("severity", "P2"),
|
||||
suggested_fix=raw.get("suggested_fix"),
|
||||
primary_service=raw.get("primary_service", "unknown"),
|
||||
pattern_indices=raw.get("pattern_indices", []),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed incident entry: %s — %s", raw, exc)
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fallback grouper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _fallback_group_by_service(patterns: list[dict]) -> IncidentAnalysis:
|
||||
"""Group patterns by service name when the LLM is unavailable.
|
||||
|
||||
Each unique service becomes one P2 incident containing all of that
|
||||
service's pattern indices.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts (must include 'service' key).
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis with used_llm=False.
|
||||
"""
|
||||
service_to_indices: dict[str, list[int]] = defaultdict(list)
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
service_to_indices[service].append(idx)
|
||||
|
||||
incidents = [
|
||||
Incident(
|
||||
title=f"Errors in {service}",
|
||||
root_cause=None,
|
||||
severity="P2",
|
||||
suggested_fix=None,
|
||||
primary_service=service,
|
||||
pattern_indices=indices,
|
||||
)
|
||||
for service, indices in service_to_indices.items()
|
||||
]
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main analysis functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ANALYZE_SYSTEM_PROMPT = f"""\
|
||||
You are an expert site-reliability engineer for Nomad Karaoke, a karaoke video
|
||||
generation platform running on Google Cloud Platform.
|
||||
|
||||
Your task is to analyse a list of active error patterns detected across
|
||||
production services, group them into meaningful incidents, and identify root
|
||||
causes.
|
||||
|
||||
## Service dependency map
|
||||
|
||||
{SERVICE_DEPENDENCY_MAP}
|
||||
|
||||
## Severity definitions
|
||||
|
||||
- P0: Service is completely down / total outage
|
||||
- P1: Major pipeline broken — orders cannot complete
|
||||
- P2: Degraded performance — some orders affected
|
||||
- P3: Minor / cosmetic issue with no direct user impact
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{{
|
||||
"incidents": [
|
||||
{{
|
||||
"title": "<short human-readable title>",
|
||||
"root_cause": "<root cause or null>",
|
||||
"severity": "P0|P1|P2|P3",
|
||||
"suggested_fix": "<actionable suggestion or null>",
|
||||
"primary_service": "<service name>",
|
||||
"pattern_indices": [<list of 0-based indices from the input list>]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Group related patterns together into a single incident where they share a
|
||||
common root cause (e.g., a downstream dependency failure). Unrelated patterns
|
||||
should be in separate incidents. Every input pattern must appear in exactly
|
||||
one incident.
|
||||
"""
|
||||
|
||||
_DEDUP_SYSTEM_PROMPT = """\
|
||||
You are an expert at identifying near-duplicate error patterns in production
|
||||
monitoring systems.
|
||||
|
||||
Your task is to compare a list of NEW error patterns against a list of
|
||||
EXISTING (canonical) patterns and identify which new patterns are essentially
|
||||
duplicates of existing ones — i.e., they describe the same underlying error
|
||||
but with slightly different wording due to variation in log messages.
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{
|
||||
"duplicates": [
|
||||
{
|
||||
"canonical_index": <0-based index into the EXISTING patterns list>,
|
||||
"duplicate_indices": [<0-based indices into the NEW patterns list>],
|
||||
"reason": "<brief explanation>"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
If no duplicates are found, return {"duplicates": []}.
|
||||
"""
|
||||
|
||||
|
||||
def analyze_patterns(patterns: list[dict]) -> IncidentAnalysis | None:
|
||||
"""Group error patterns into incidents using Gemini LLM analysis.
|
||||
|
||||
Returns None if there are fewer than MIN_PATTERNS_FOR_ANALYSIS patterns.
|
||||
Falls back to service-based grouping when the LLM fails or returns an
|
||||
unparseable response.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts to analyse.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis, or None if insufficient patterns.
|
||||
"""
|
||||
if len(patterns) < MIN_PATTERNS_FOR_ANALYSIS:
|
||||
return None
|
||||
|
||||
user_prompt = _build_analyze_user_prompt(patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_ANALYZE_SYSTEM_PROMPT, user_prompt, temperature=0.2)
|
||||
result = _parse_llm_response(raw_response)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
logger.warning("LLM returned unparseable response; falling back to service grouping")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("LLM analysis failed: %s — falling back to service grouping", exc)
|
||||
|
||||
return _fallback_group_by_service(patterns)
|
||||
|
||||
|
||||
def find_duplicate_patterns(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> list[DuplicateGroup]:
|
||||
"""Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Returns an empty list if either input list is empty, or if the LLM call
|
||||
fails for any reason.
|
||||
|
||||
Args:
|
||||
new_patterns: Newly detected error patterns to check.
|
||||
existing_patterns: Currently tracked (canonical) error patterns.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects (may be empty).
|
||||
"""
|
||||
if not new_patterns or not existing_patterns:
|
||||
return []
|
||||
|
||||
user_prompt = _build_dedup_user_prompt(new_patterns, existing_patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_DEDUP_SYSTEM_PROMPT, user_prompt, temperature=0.1)
|
||||
return _parse_duplicate_response(raw_response)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Duplicate detection LLM call failed: %s", exc)
|
||||
return []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt builders
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_analyze_user_prompt(patterns: list[dict]) -> str:
|
||||
"""Build the user prompt listing patterns for incident grouping."""
|
||||
lines = ["Error patterns to analyse:\n"]
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
count = pattern.get("count", 0)
|
||||
lines.append(f"[{idx}] service={service!r} count={count} message={message!r}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_dedup_user_prompt(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> str:
|
||||
"""Build the user prompt listing existing and new patterns for dedup."""
|
||||
lines = ["EXISTING (canonical) patterns:\n"]
|
||||
for idx, pattern in enumerate(existing_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
lines.append("\nNEW patterns to check:\n")
|
||||
for idx, pattern in enumerate(new_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_duplicate_response(text: str) -> list[DuplicateGroup]:
|
||||
"""Parse the LLM response for duplicate detection.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects, or [] on any failure.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Dedup LLM returned non-JSON: %.200s", text)
|
||||
return []
|
||||
|
||||
if "duplicates" not in data:
|
||||
logger.warning("Dedup LLM response missing 'duplicates' key")
|
||||
return []
|
||||
|
||||
groups: list[DuplicateGroup] = []
|
||||
for raw in data["duplicates"]:
|
||||
try:
|
||||
groups.append(
|
||||
DuplicateGroup(
|
||||
canonical_index=int(raw["canonical_index"]),
|
||||
duplicate_indices=list(raw.get("duplicate_indices", [])),
|
||||
reason=raw.get("reason", ""),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed duplicate entry: %s — %s", raw, exc)
|
||||
|
||||
return groups
|
||||
@@ -0,0 +1,641 @@
|
||||
"""Monitor orchestrator for the production error monitoring service.
|
||||
|
||||
This is the main entry point. Run as::
|
||||
|
||||
python -m backend.services.error_monitor.monitor
|
||||
|
||||
The ``ErrorMonitor.run()`` method executes the full pipeline:
|
||||
|
||||
* Monitor cycle (default) — query Cloud Logging, detect new patterns, send
|
||||
Discord alerts, check auto-resolution.
|
||||
* Daily digest mode (``DIGEST_MODE=true``) — bundle 24h stats into one message.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from google.cloud import logging as cloud_logging
|
||||
from google.cloud import secretmanager
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LOOKBACK_MINUTES,
|
||||
MAX_LOG_ENTRIES,
|
||||
MONITORED_CLOUD_FUNCTIONS,
|
||||
MONITORED_CLOUD_RUN_JOBS,
|
||||
MONITORED_CLOUD_RUN_SERVICES,
|
||||
MONITORED_GCE_INSTANCES,
|
||||
SPIKE_MIN_COUNT,
|
||||
SPIKE_MULTIPLIER,
|
||||
get_digest_mode,
|
||||
get_discord_webhook_secret_name,
|
||||
get_llm_enabled,
|
||||
)
|
||||
from backend.services.error_monitor.discord import (
|
||||
ErrorMonitorDiscord,
|
||||
format_auto_resolved_alert,
|
||||
format_daily_digest,
|
||||
format_incident_alert,
|
||||
format_new_pattern_alert,
|
||||
format_spike_alert,
|
||||
)
|
||||
from backend.services.error_monitor.firestore_adapter import (
|
||||
ErrorPatternsAdapter,
|
||||
PatternData,
|
||||
UpsertResult,
|
||||
)
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns, find_duplicate_patterns
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash, normalize_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Module-level constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maps log resource type → (label_key, service_name_list)
|
||||
RESOURCE_TYPE_FILTERS: dict[str, tuple[str, list[str]]] = {
|
||||
"cloud_run_revision": ("resource.labels.service_name", MONITORED_CLOUD_RUN_SERVICES),
|
||||
"cloud_run_job": ("resource.labels.job_name", MONITORED_CLOUD_RUN_JOBS),
|
||||
"cloud_function": ("resource.labels.function_name", MONITORED_CLOUD_FUNCTIONS),
|
||||
"gce_instance": ('labels."compute.googleapis.com/resource_name"', MONITORED_GCE_INSTANCES),
|
||||
}
|
||||
|
||||
#: Maps log resource type → canonical resource_type string stored in Firestore.
|
||||
RESOURCE_TYPE_MAP: dict[str, str] = {
|
||||
"cloud_run_revision": "cloud_run_service",
|
||||
"cloud_run_job": "cloud_run_job",
|
||||
"cloud_function": "cloud_function",
|
||||
"gce_instance": "gce_instance",
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Free functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_log_filter(
|
||||
resource_type: str,
|
||||
resource_names: list[str],
|
||||
lookback_minutes: int,
|
||||
) -> str:
|
||||
"""Build a Cloud Logging filter string.
|
||||
|
||||
Args:
|
||||
resource_type: GCP resource type (e.g. ``"cloud_run_revision"``).
|
||||
resource_names: List of service/job/function/instance names to include.
|
||||
lookback_minutes: How many minutes back to query.
|
||||
|
||||
Returns:
|
||||
A filter string suitable for ``logging_client.list_entries(filter_=...)``.
|
||||
"""
|
||||
label_key = RESOURCE_TYPE_FILTERS[resource_type][0]
|
||||
cutoff = datetime.now(tz=timezone.utc) - timedelta(minutes=lookback_minutes)
|
||||
cutoff_iso = cutoff.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
name_clause = " OR ".join(f'{label_key}="{name}"' for name in resource_names)
|
||||
if len(resource_names) > 1:
|
||||
name_clause = f"({name_clause})"
|
||||
|
||||
return (
|
||||
f'resource.type="{resource_type}" '
|
||||
f"severity>=ERROR "
|
||||
f'timestamp>="{cutoff_iso}" '
|
||||
f"{name_clause}"
|
||||
)
|
||||
|
||||
|
||||
def _extract_message(entry: Any) -> str | None:
|
||||
"""Extract the log message text from a Cloud Logging entry.
|
||||
|
||||
Handles several payload shapes:
|
||||
|
||||
* ``str`` payload — returned directly.
|
||||
* ``dict`` payload — tries ``"message"``, ``"textPayload"``, ``"error"``,
|
||||
``"msg"`` keys in that order.
|
||||
* ``None`` payload — returns ``None``.
|
||||
|
||||
Args:
|
||||
entry: A Cloud Logging ``LogEntry`` object.
|
||||
|
||||
Returns:
|
||||
The message string, or ``None`` if not extractable.
|
||||
"""
|
||||
payload = entry.payload
|
||||
if payload is None:
|
||||
return None
|
||||
if isinstance(payload, str):
|
||||
return payload if payload else None
|
||||
if isinstance(payload, dict):
|
||||
for key in ("message", "textPayload", "error", "msg"):
|
||||
value = payload.get(key)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
# Fallback: convert to string representation
|
||||
text = str(payload)
|
||||
return text if text else None
|
||||
|
||||
|
||||
def _extract_service_name(entry: Any, resource_type: str) -> str:
|
||||
"""Extract the service/job/function/instance name from a log entry.
|
||||
|
||||
Args:
|
||||
entry: A Cloud Logging ``LogEntry`` object.
|
||||
resource_type: GCP log resource type string.
|
||||
|
||||
Returns:
|
||||
The service name string (falls back to ``"unknown"`` if not found).
|
||||
"""
|
||||
labels = getattr(entry.resource, "labels", {}) or {}
|
||||
entry_labels = getattr(entry, "labels", {}) or {}
|
||||
|
||||
if resource_type == "cloud_run_revision":
|
||||
return labels.get("service_name") or "unknown"
|
||||
if resource_type == "cloud_run_job":
|
||||
return labels.get("job_name") or "unknown"
|
||||
if resource_type == "cloud_function":
|
||||
return labels.get("function_name") or "unknown"
|
||||
if resource_type == "gce_instance":
|
||||
# Prefer the human-readable resource name label
|
||||
name = entry_labels.get("compute.googleapis.com/resource_name")
|
||||
if name:
|
||||
return name
|
||||
return labels.get("instance_id") or "unknown"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _classify_resource_type(log_resource_type: str) -> str:
|
||||
"""Map a Cloud Logging resource type to the canonical type stored in Firestore.
|
||||
|
||||
Args:
|
||||
log_resource_type: Raw GCP resource type (e.g. ``"cloud_run_revision"``).
|
||||
|
||||
Returns:
|
||||
Canonical resource type string (falls back to the input if not in map).
|
||||
"""
|
||||
return RESOURCE_TYPE_MAP.get(log_resource_type, log_resource_type)
|
||||
|
||||
|
||||
def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
|
||||
"""Group normalised log entries by their pattern hash.
|
||||
|
||||
Args:
|
||||
entries: List of dicts with ``service``, ``normalized``, and ``message`` keys.
|
||||
|
||||
Returns:
|
||||
Dict mapping ``pattern_id`` → group dict containing ``service``,
|
||||
``resource_type``, ``normalized``, ``sample_message``, ``count``.
|
||||
"""
|
||||
groups: dict[str, dict] = {}
|
||||
for entry in entries:
|
||||
service = entry["service"]
|
||||
normalized = entry["normalized"]
|
||||
pattern_id = compute_pattern_hash(service, normalized)
|
||||
|
||||
if pattern_id not in groups:
|
||||
groups[pattern_id] = {
|
||||
"pattern_id": pattern_id,
|
||||
"service": service,
|
||||
"resource_type": entry.get("resource_type", "unknown"),
|
||||
"normalized": normalized,
|
||||
"sample_message": entry["message"],
|
||||
"count": 0,
|
||||
}
|
||||
groups[pattern_id]["count"] += 1
|
||||
return groups
|
||||
|
||||
|
||||
def _rolling_average(rolling_counts: list[dict]) -> float:
|
||||
"""Compute the mean count from a list of rolling_count dicts.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"count": int, ...}`` dicts.
|
||||
|
||||
Returns:
|
||||
The arithmetic mean as a float, or ``0.0`` for an empty list.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return 0.0
|
||||
total = sum(entry.get("count", 0) for entry in rolling_counts)
|
||||
return total / len(rolling_counts)
|
||||
|
||||
|
||||
def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
|
||||
"""Determine whether ``current_count`` represents an error rate spike.
|
||||
|
||||
A spike is detected when:
|
||||
- ``current_count`` >= ``SPIKE_MIN_COUNT`` (avoids noise from rare errors), AND
|
||||
- ``current_count`` > ``rolling_average * SPIKE_MULTIPLIER``
|
||||
|
||||
Args:
|
||||
current_count: Error count in the current monitoring window.
|
||||
rolling_counts: Historical rolling counts from Firestore.
|
||||
|
||||
Returns:
|
||||
``True`` if a spike is detected, ``False`` otherwise.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return False
|
||||
if current_count < SPIKE_MIN_COUNT:
|
||||
return False
|
||||
avg = _rolling_average(rolling_counts)
|
||||
if avg == 0.0:
|
||||
return False
|
||||
return current_count > avg * SPIKE_MULTIPLIER
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ErrorMonitor class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorMonitor:
|
||||
"""Orchestrates the full production error monitoring pipeline.
|
||||
|
||||
On each run (typically every 15 minutes via Cloud Scheduler), it:
|
||||
|
||||
1. Queries Cloud Logging for recent errors across all monitored services.
|
||||
2. Groups errors into patterns using normalisation + hashing.
|
||||
3. Upserts patterns to Firestore, tracking new vs. recurrent.
|
||||
4. Optionally uses an LLM to deduplicate patterns and create incidents.
|
||||
5. Sends Discord alerts for new patterns, incidents, and spikes.
|
||||
6. Auto-resolves patterns that have been silent long enough.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.logging_client = cloud_logging.Client(project=GCP_PROJECT)
|
||||
self.firestore_adapter = ErrorPatternsAdapter()
|
||||
self.discord = ErrorMonitorDiscord(webhook_url=self._get_discord_webhook())
|
||||
|
||||
def _get_discord_webhook(self) -> str:
|
||||
"""Retrieve the Discord webhook URL.
|
||||
|
||||
Checks ``DISCORD_WEBHOOK_URL`` environment variable first; falls back
|
||||
to Secret Manager.
|
||||
|
||||
Returns:
|
||||
Discord webhook URL string.
|
||||
"""
|
||||
url = os.environ.get("DISCORD_WEBHOOK_URL")
|
||||
if url:
|
||||
return url
|
||||
|
||||
secret_name = get_discord_webhook_secret_name()
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
secret_path = f"projects/{GCP_PROJECT}/secrets/{secret_name}/versions/latest"
|
||||
response = client.access_secret_version(name=secret_path)
|
||||
return response.payload.data.decode("utf-8").strip()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Main entry point
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run(self) -> None:
|
||||
"""Execute the monitor pipeline (digest or cycle mode)."""
|
||||
if get_digest_mode():
|
||||
self._run_daily_digest()
|
||||
else:
|
||||
self._run_monitor_cycle()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Monitor cycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _run_monitor_cycle(self) -> None:
|
||||
"""Execute one monitor cycle: collect → group → upsert → alert → auto-resolve."""
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
now_iso = now.isoformat()
|
||||
|
||||
# ── Step 1: Collect log entries ────────────────────────────────────
|
||||
raw_entries: list[dict] = []
|
||||
for resource_type, (_, resource_names) in RESOURCE_TYPE_FILTERS.items():
|
||||
log_filter = _build_log_filter(resource_type, resource_names, LOOKBACK_MINUTES)
|
||||
logger.info("Querying %s with filter: %s", resource_type, log_filter)
|
||||
try:
|
||||
entries = self.logging_client.list_entries(
|
||||
filter_=log_filter,
|
||||
max_results=MAX_LOG_ENTRIES,
|
||||
)
|
||||
for entry in entries:
|
||||
message = _extract_message(entry)
|
||||
if not message:
|
||||
continue
|
||||
service = _extract_service_name(entry, resource_type)
|
||||
ignore_reason = should_ignore(service, message)
|
||||
if ignore_reason:
|
||||
logger.debug(
|
||||
"Ignoring entry from %s (%s): %s",
|
||||
service,
|
||||
ignore_reason.pattern_name,
|
||||
ignore_reason.reason,
|
||||
)
|
||||
continue
|
||||
normalized = normalize_message(message)
|
||||
if not normalized:
|
||||
continue
|
||||
raw_entries.append(
|
||||
{
|
||||
"service": service,
|
||||
"resource_type": _classify_resource_type(resource_type),
|
||||
"normalized": normalized,
|
||||
"message": message,
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Failed to query %s logs: %s", resource_type, exc)
|
||||
|
||||
logger.info("Collected %d log entries after filtering", len(raw_entries))
|
||||
|
||||
# ── Step 2: Group by pattern ───────────────────────────────────────
|
||||
groups = _group_by_pattern(raw_entries)
|
||||
logger.info("Grouped into %d distinct patterns", len(groups))
|
||||
|
||||
if not groups:
|
||||
logger.info("No new error entries found this cycle; checking auto-resolve.")
|
||||
self._check_auto_resolve()
|
||||
return
|
||||
|
||||
# ── Step 3: Upsert to Firestore ────────────────────────────────────
|
||||
new_pattern_ids: list[str] = []
|
||||
spike_patterns: list[dict] = []
|
||||
|
||||
for pattern_id, group in groups.items():
|
||||
data = PatternData(
|
||||
pattern_id=pattern_id,
|
||||
service=group["service"],
|
||||
resource_type=group["resource_type"],
|
||||
normalized_message=group["normalized"],
|
||||
sample_message=group["sample_message"],
|
||||
count=group["count"],
|
||||
timestamp=now,
|
||||
)
|
||||
result: UpsertResult = self.firestore_adapter.upsert_pattern(data)
|
||||
if result.is_new:
|
||||
new_pattern_ids.append(pattern_id)
|
||||
logger.info("New pattern detected: %s (%s)", pattern_id, group["service"])
|
||||
|
||||
# Check for spike on existing patterns
|
||||
existing = self.firestore_adapter.get_pattern(pattern_id)
|
||||
if existing and not result.is_new:
|
||||
rolling = existing.get("rolling_counts") or []
|
||||
if _is_spike(group["count"], rolling):
|
||||
spike_patterns.append(
|
||||
{
|
||||
"service": group["service"],
|
||||
"normalized_message": group["normalized"],
|
||||
"current_count": group["count"],
|
||||
"rolling_average": _rolling_average(rolling),
|
||||
}
|
||||
)
|
||||
logger.info("Spike detected for pattern %s", pattern_id)
|
||||
|
||||
# ── Step 4: LLM dedup ─────────────────────────────────────────────
|
||||
if new_pattern_ids and get_llm_enabled():
|
||||
new_patterns_data = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in new_pattern_ids
|
||||
]
|
||||
existing_patterns = self.firestore_adapter.get_active_patterns()
|
||||
# Exclude newly added patterns from the canonical list
|
||||
canonical = [p for p in existing_patterns if p.get("pattern_id") not in new_pattern_ids]
|
||||
|
||||
if canonical:
|
||||
duplicate_groups = find_duplicate_patterns(new_patterns_data, canonical)
|
||||
for dup_group in duplicate_groups:
|
||||
# Merge each duplicate new pattern into the canonical
|
||||
canonical_pattern = canonical[dup_group.canonical_index]
|
||||
canonical_id = canonical_pattern.get("pattern_id", "")
|
||||
for dup_idx in dup_group.duplicate_indices:
|
||||
if dup_idx < len(new_pattern_ids):
|
||||
dup_id = new_pattern_ids[dup_idx]
|
||||
logger.info(
|
||||
"Merging duplicate pattern %s into %s: %s",
|
||||
dup_id,
|
||||
canonical_id,
|
||||
dup_group.reason,
|
||||
)
|
||||
self.firestore_adapter.merge_pattern(dup_id, canonical_id, dup_group.reason)
|
||||
# Remove from new_pattern_ids since it was merged
|
||||
new_pattern_ids = [pid for pid in new_pattern_ids if pid != dup_id]
|
||||
|
||||
# ── Step 5: LLM incident analysis ─────────────────────────────────
|
||||
incident_pattern_ids: set[str] = set()
|
||||
|
||||
if len(new_pattern_ids) >= 2 and get_llm_enabled():
|
||||
patterns_for_analysis = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in new_pattern_ids
|
||||
if pid in groups
|
||||
]
|
||||
analysis = analyze_patterns(patterns_for_analysis)
|
||||
|
||||
if analysis and analysis.incidents:
|
||||
for incident in analysis.incidents:
|
||||
incident_pids = [
|
||||
new_pattern_ids[idx]
|
||||
for idx in incident.pattern_indices
|
||||
if idx < len(new_pattern_ids)
|
||||
]
|
||||
if not incident_pids:
|
||||
continue
|
||||
|
||||
incident_id = self.firestore_adapter.create_incident(
|
||||
title=incident.title,
|
||||
root_cause=incident.root_cause or "",
|
||||
severity=incident.severity,
|
||||
suggested_fix=incident.suggested_fix or "",
|
||||
primary_service=incident.primary_service,
|
||||
pattern_ids=incident_pids,
|
||||
used_llm=analysis.used_llm,
|
||||
)
|
||||
logger.info(
|
||||
"Created incident %s (%s) with %d patterns",
|
||||
incident_id,
|
||||
incident.severity,
|
||||
len(incident_pids),
|
||||
)
|
||||
|
||||
# Build pattern list for the Discord alert
|
||||
pattern_dicts = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in incident_pids
|
||||
if pid in groups
|
||||
]
|
||||
msg = format_incident_alert(
|
||||
title=incident.title,
|
||||
severity=incident.severity,
|
||||
root_cause=incident.root_cause or "Unknown",
|
||||
suggested_fix=incident.suggested_fix or "Investigate logs",
|
||||
primary_service=incident.primary_service,
|
||||
patterns=pattern_dicts,
|
||||
)
|
||||
if self.discord.send_message(msg):
|
||||
for pid in incident_pids:
|
||||
try:
|
||||
self.firestore_adapter.update_pattern_alerted(pid)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Could not update alerted_at for %s: %s", pid, exc)
|
||||
|
||||
incident_pattern_ids.update(incident_pids)
|
||||
|
||||
# ── Step 6: Individual alerts for new patterns not in incidents ────
|
||||
for pattern_id in new_pattern_ids:
|
||||
if pattern_id in incident_pattern_ids:
|
||||
continue
|
||||
if pattern_id not in groups:
|
||||
continue
|
||||
group = groups[pattern_id]
|
||||
|
||||
# Fetch fresh copy to get first_seen timestamp
|
||||
existing = self.firestore_adapter.get_pattern(pattern_id)
|
||||
first_seen = existing.get("first_seen", now_iso) if existing else now_iso
|
||||
|
||||
msg = format_new_pattern_alert(
|
||||
service=group["service"],
|
||||
resource_type=group["resource_type"],
|
||||
normalized_message=group["normalized"],
|
||||
sample_message=group["sample_message"],
|
||||
count=group["count"],
|
||||
first_seen=first_seen,
|
||||
)
|
||||
if self.discord.send_message(msg):
|
||||
try:
|
||||
self.firestore_adapter.update_pattern_alerted(pattern_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Could not update alerted_at for %s: %s", pattern_id, exc)
|
||||
|
||||
# ── Step 7: Spike alerts ───────────────────────────────────────────
|
||||
for spike in spike_patterns:
|
||||
msg = format_spike_alert(
|
||||
service=spike["service"],
|
||||
normalized_message=spike["normalized_message"],
|
||||
current_count=spike["current_count"],
|
||||
rolling_average=spike["rolling_average"],
|
||||
)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
# ── Step 8: Auto-resolve check ─────────────────────────────────────
|
||||
self._check_auto_resolve()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auto-resolve helper
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _check_auto_resolve(self) -> None:
|
||||
"""Check all active patterns for auto-resolution and send a consolidated alert."""
|
||||
patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
|
||||
resolved: list[dict] = []
|
||||
|
||||
for pattern in patterns:
|
||||
pattern_id = pattern.get("pattern_id", "")
|
||||
hours_silent = self.firestore_adapter.check_auto_resolve(pattern)
|
||||
if hours_silent is not None:
|
||||
logger.info(
|
||||
"Auto-resolving pattern %s (silent %.1f hours)", pattern_id, hours_silent
|
||||
)
|
||||
self.firestore_adapter.auto_resolve_pattern(pattern_id, round(hours_silent, 1))
|
||||
resolved.append(
|
||||
{
|
||||
"service": pattern.get("service", "unknown"),
|
||||
"message": pattern.get("normalized_message", ""),
|
||||
"hours_silent": round(hours_silent, 1),
|
||||
}
|
||||
)
|
||||
|
||||
if resolved:
|
||||
msg = format_auto_resolved_alert(resolved)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Daily digest
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _run_daily_digest(self) -> None:
|
||||
"""Gather 24h stats and send a daily digest to Discord."""
|
||||
# Optional dedup sweep (best-effort; LLM errors are non-fatal)
|
||||
if get_llm_enabled():
|
||||
try:
|
||||
active = self.firestore_adapter.get_active_patterns()
|
||||
if len(active) >= 2:
|
||||
mid = len(active) // 2
|
||||
duplicates = find_duplicate_patterns(active[:mid], active[mid:])
|
||||
for dup in duplicates:
|
||||
for idx in dup.duplicate_indices:
|
||||
target_half = active[mid:]
|
||||
source_half = active[:mid]
|
||||
if idx < len(target_half) and dup.canonical_index < len(source_half):
|
||||
self.firestore_adapter.merge_pattern(
|
||||
target_half[idx]["pattern_id"],
|
||||
source_half[dup.canonical_index]["pattern_id"],
|
||||
dup.reason,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Digest dedup sweep failed (non-fatal): %s", exc)
|
||||
|
||||
# Gather stats from active patterns
|
||||
active_patterns = self.firestore_adapter.get_active_patterns()
|
||||
per_service_counts: dict[str, int] = {}
|
||||
new_count = 0
|
||||
total_errors = 0
|
||||
|
||||
for pattern in active_patterns:
|
||||
service = pattern.get("service", "unknown")
|
||||
count = pattern.get("total_count", 0)
|
||||
per_service_counts[service] = per_service_counts.get(service, 0) + count
|
||||
total_errors += count
|
||||
if pattern.get("status") == "new":
|
||||
new_count += 1
|
||||
|
||||
# Count recently auto-resolved patterns
|
||||
resolved_patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
|
||||
resolved_count = sum(
|
||||
1
|
||||
for p in resolved_patterns
|
||||
if self.firestore_adapter.check_auto_resolve(p) is not None
|
||||
)
|
||||
|
||||
msg = format_daily_digest(
|
||||
total_errors=total_errors,
|
||||
new_patterns=new_count,
|
||||
resolved_patterns=resolved_count,
|
||||
active_patterns=len(active_patterns),
|
||||
per_service_counts=per_service_counts,
|
||||
)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Configure logging and run the error monitor."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
monitor = ErrorMonitor()
|
||||
monitor.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Message normalizer for the production error monitoring service.
|
||||
|
||||
Replaces variable parts of error messages (IDs, timestamps, paths, etc.)
|
||||
with stable placeholders so the same logical error always produces the same
|
||||
pattern hash, regardless of which specific resource or timestamp was involved.
|
||||
|
||||
Normalizer rules are applied in order — more specific patterns first.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
from backend.services.error_monitor.config import MAX_NORMALIZED_MESSAGE_LENGTH
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled regex patterns (applied in order — more specific first)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_NORMALIZERS: list[tuple[re.Pattern, str]] = [
|
||||
# 1. GCS paths: gs://bucket/path/to/object → gs://<BUCKET>/<PATH>
|
||||
# Must come before Firestore and URL normalization.
|
||||
(
|
||||
re.compile(r"gs://([^/\s]+)/([^\s]+)"),
|
||||
r"gs://<BUCKET>/<PATH>",
|
||||
),
|
||||
# 1b. GCS bucket root (no object path): gs://bucket/ or gs://bucket
|
||||
# Uses a lookahead so the slash/end-of-string is not consumed, and uses
|
||||
# a character class that excludes '<' to avoid re-matching placeholders.
|
||||
(
|
||||
re.compile(r"gs://([^/<\s]+)(?=[/\s]|$)"),
|
||||
r"gs://<BUCKET>",
|
||||
),
|
||||
# 2. Firestore document paths (collection/doc/…/doc — at least 2 segments)
|
||||
# Negative lookbehind for '.' prevents matching inside domain names (URLs).
|
||||
# Negative lookbehind for '/' prevents matching inside already-replaced paths.
|
||||
(
|
||||
re.compile(
|
||||
r"(?<![./])\b([a-zA-Z_][a-zA-Z0-9_-]*/[a-zA-Z0-9_-]+(?:/[a-zA-Z0-9_-]+){1,})\b"
|
||||
),
|
||||
r"<DOC_PATH>",
|
||||
),
|
||||
# 3. UUIDs (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
|
||||
(
|
||||
re.compile(
|
||||
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
|
||||
),
|
||||
"<ID>",
|
||||
),
|
||||
# 4. ISO 8601 timestamps (2024-01-15T10:30:45Z / …+05:30 / ….123Z)
|
||||
(
|
||||
re.compile(
|
||||
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})"
|
||||
),
|
||||
"<TS>",
|
||||
),
|
||||
# 5. Epoch timestamps: 10+ digit number optionally followed by fractional seconds
|
||||
(
|
||||
re.compile(r"\b\d{10,}(?:\.\d+)?\b"),
|
||||
"<EPOCH>",
|
||||
),
|
||||
# 6. Email addresses
|
||||
(
|
||||
re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b"),
|
||||
"<EMAIL>",
|
||||
),
|
||||
# 7. IP addresses (IPv4) — must come before large-number replacement
|
||||
(
|
||||
re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
|
||||
"<IP>",
|
||||
),
|
||||
# 8. URLs — strip to domain only (https://host/path → https://host)
|
||||
# Handles http and https; preserves the scheme+domain for context.
|
||||
(
|
||||
re.compile(r"https?://([A-Za-z0-9.\-]+(:\d+)?)/[^\s]*"),
|
||||
r"https://\1",
|
||||
),
|
||||
# 9. Job IDs in paths (/jobs/<alphanumeric>)
|
||||
(
|
||||
re.compile(r"/jobs/[A-Za-z0-9]+"),
|
||||
"/jobs/<ID>",
|
||||
),
|
||||
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
|
||||
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
|
||||
# Must contain both letters and digits (to avoid replacing plain words).
|
||||
(
|
||||
re.compile(r"\b(?=[A-Za-z0-9]{20,28}\b)(?=[A-Za-z0-9]*[A-Z])(?=[A-Za-z0-9]*[a-z])(?=[A-Za-z0-9]*\d)[A-Za-z0-9]{20,28}\b"),
|
||||
"<UID>",
|
||||
),
|
||||
# 11. Hex/alphanumeric IDs: 8+ chars containing both letters and digits
|
||||
# (e.g. git SHAs, Cloud Run revision IDs, job IDs)
|
||||
# Uses a lookahead to require at least one digit AND one letter.
|
||||
(
|
||||
re.compile(r"\b(?=[a-fA-F0-9]*[a-fA-F][a-fA-F0-9]*\d|[a-fA-F0-9]*\d[a-fA-F0-9]*[a-fA-F])[a-fA-F0-9]{8,}\b"),
|
||||
"<ID>",
|
||||
),
|
||||
# 12. Large numbers (4+ digits) — must come after epoch/IP/UUID replacements
|
||||
(
|
||||
re.compile(r"\b\d{4,}\b"),
|
||||
"<NUM>",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def normalize_message(message: str) -> str:
|
||||
"""Normalize a raw log message by replacing variable parts with placeholders.
|
||||
|
||||
Applies each normalizer rule in order (more specific patterns first) and
|
||||
truncates the result to MAX_NORMALIZED_MESSAGE_LENGTH characters.
|
||||
|
||||
Args:
|
||||
message: Raw log message string.
|
||||
|
||||
Returns:
|
||||
Normalized message string, at most MAX_NORMALIZED_MESSAGE_LENGTH chars.
|
||||
"""
|
||||
if not message:
|
||||
return ""
|
||||
|
||||
result = message
|
||||
for pattern, replacement in _NORMALIZERS:
|
||||
result = pattern.sub(replacement, result)
|
||||
|
||||
return result[:MAX_NORMALIZED_MESSAGE_LENGTH]
|
||||
|
||||
|
||||
def compute_pattern_hash(service: str, normalized_message: str) -> str:
|
||||
"""Compute a stable SHA-256 fingerprint for an error pattern.
|
||||
|
||||
Args:
|
||||
service: The originating service name (e.g. "karaoke-backend").
|
||||
normalized_message: The output of normalize_message().
|
||||
|
||||
Returns:
|
||||
64-character lowercase hex SHA-256 digest.
|
||||
"""
|
||||
payload = f"{service}:{normalized_message}"
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
@@ -6,6 +6,7 @@ Handles:
|
||||
- Processing webhook events
|
||||
- Managing customer records
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
@@ -290,7 +291,10 @@ class StripeService:
|
||||
event = stripe.Webhook.construct_event(
|
||||
payload, signature, self.webhook_secret
|
||||
)
|
||||
return True, event, "Webhook verified"
|
||||
# Convert Stripe Event object to plain dict — Stripe SDK v14+
|
||||
# returns StripeObject instances that don't support .get()
|
||||
event_dict = json.loads(str(event))
|
||||
return True, event_dict, "Webhook verified"
|
||||
except stripe.error.SignatureVerificationError as e:
|
||||
logger.error(f"Invalid webhook signature: {e}")
|
||||
return False, None, "Invalid signature"
|
||||
|
||||
@@ -13,6 +13,7 @@ import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, List, Tuple
|
||||
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import Increment
|
||||
@@ -999,7 +1000,7 @@ class UserService:
|
||||
'amount': amount,
|
||||
'processed_at': datetime.utcnow()
|
||||
})
|
||||
except Exception:
|
||||
except google_exceptions.AlreadyExists:
|
||||
# Document already exists - this session was already processed
|
||||
logger.info(f"Stripe session {stripe_session_id} already processed (idempotent skip)")
|
||||
return False, 0, "Session already processed"
|
||||
|
||||
@@ -36,6 +36,21 @@
|
||||
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md.
|
||||
```
|
||||
|
||||
### Error Monitor
|
||||
|
||||
```text
|
||||
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, */15 min)
|
||||
│
|
||||
├─ Normalize & deduplicate
|
||||
├─ LLM incident grouping (Gemini Flash)
|
||||
├─ Discord alerts (new patterns, spikes, daily digest)
|
||||
├─ Firestore: error_patterns, error_incidents
|
||||
└─ Auto-resolve silent patterns
|
||||
|
||||
Entry point: python -m backend.services.error_monitor.monitor
|
||||
Design spec: docs/archive/2026-04-12-error-monitor-design.md
|
||||
```
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
|
||||
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# Referral Flyer Customisation — Design Spec
|
||||
|
||||
**Date:** 2026-04-09
|
||||
**Branch:** `feat/sess-20260409-1813-referral-flyer-customisation`
|
||||
**Status:** Design approved, ready for implementation planning
|
||||
|
||||
## Overview
|
||||
|
||||
Expand the existing QR Code Generator dialog into a tabbed "Referral Tools" dialog with two tabs: **QR Code** and **Printable Flyer**. The Flyer tab provides a live preview with extensive customisation options and client-side export (PDF, HTML, PNG). This replaces the current server-side flyer generation with a fully client-side approach.
|
||||
|
||||
## Goals
|
||||
|
||||
1. Live flyer preview with instant feedback on customisation changes
|
||||
2. Configurable colors, text, section visibility, branding, and print layout
|
||||
3. Client-side export to PDF (primary), HTML, and PNG — no server round-trip
|
||||
4. Preset themes (Light, Dark) with ability to save/load custom presets
|
||||
5. Multi-per-page PDF layout (1, 2, or 4 flyers per US Letter page)
|
||||
|
||||
## Architecture
|
||||
|
||||
### Approach: Client-Side Rendering
|
||||
|
||||
The flyer is rendered as a React component in the dialog preview. Export uses `html2canvas` + `jsPDF` for PDF/PNG, and DOM serialization for HTML. This gives:
|
||||
- Instant preview of all customisation changes
|
||||
- Export to PDF, HTML, and PNG without backend involvement
|
||||
- No backend changes required — existing server-side endpoints remain but are unused
|
||||
|
||||
### Component Structure
|
||||
|
||||
```
|
||||
frontend/components/referrals/
|
||||
├── ReferralToolsDialog.tsx # Tabbed shell (QR Code | Printable Flyer)
|
||||
├── QRCodeTab.tsx # Extracted from current QRCodeDialog (preview + controls)
|
||||
├── FlyerTab.tsx # Flyer preview + controls container
|
||||
├── FlyerPreview.tsx # Flyer rendered as React component (live preview)
|
||||
├── FlyerControls.tsx # Right-side customisation panel
|
||||
├── FlyerExport.tsx # PDF/HTML/PNG export logic
|
||||
└── flyer-presets.ts # Built-in presets + localStorage save/load helpers
|
||||
```
|
||||
|
||||
### State Flow
|
||||
|
||||
- `ReferralToolsDialog` owns active tab state and QR style prefs (both tabs need them)
|
||||
- `QRCodeTab` receives QR prefs + updater — works exactly as current `QRCodeDialog`
|
||||
- `FlyerTab` receives QR prefs (read-only, for embedding styled QR in flyer) + owns its own flyer config state
|
||||
- Flyer config persisted to localStorage under `nk-flyer-prefs` (same debounced pattern as QR prefs)
|
||||
- A small "Edit QR Style" link on the Flyer tab (near the QR in the preview) switches to the QR tab
|
||||
|
||||
## Flyer Config Model
|
||||
|
||||
```typescript
|
||||
interface FlyerConfig {
|
||||
// Colors
|
||||
bgColor: string; // default: '#faf8f5'
|
||||
headlineGradient: string[]; // default: ['#c45aff', '#ff7acc', '#ff5a8a']
|
||||
headlineSubColor: string; // default: '#1a1a1a'
|
||||
textColor: string; // default: '#1a1a1a'
|
||||
subtextColor: string; // default: '#666'
|
||||
accentColor: string; // step numbers, divider
|
||||
|
||||
// Text overrides (null = use default)
|
||||
headlineMain: string | null;
|
||||
headlineSub: string | null;
|
||||
subtitle: string | null;
|
||||
ctaLabel: string | null;
|
||||
ctaNote: string | null;
|
||||
steps: Array<{ title: string | null; desc: string | null }>;
|
||||
|
||||
// Section visibility
|
||||
showSubtitle: boolean;
|
||||
showSteps: boolean;
|
||||
showDivider: boolean;
|
||||
showBottomFeatures: boolean;
|
||||
showBottomTagline: boolean;
|
||||
|
||||
// Custom branding
|
||||
customLogoUrl: string | null; // data URL from file upload
|
||||
|
||||
// Print layout
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number; // page margin in mm, default 15
|
||||
}
|
||||
```
|
||||
|
||||
## Built-in Presets
|
||||
|
||||
**Light:** Current light template defaults — cream background (`#faf8f5`), dark text, pink/purple accent gradient.
|
||||
|
||||
**Dark:** Current dark template defaults — dark background, light text, pink/purple accent gradient.
|
||||
|
||||
## Custom Presets
|
||||
|
||||
- Stored in localStorage under `nk-flyer-custom-presets` as `Array<{ name: string; config: FlyerConfig }>`
|
||||
- "Save as Preset" button in controls — prompts for a name inline
|
||||
- "Load Preset" dropdown shows built-in + custom presets
|
||||
- "Delete" option on custom presets only
|
||||
- Editing any value after loading a preset shows dropdown as "Custom" / unsaved state
|
||||
|
||||
## Flyer Preview
|
||||
|
||||
`FlyerPreview.tsx` is a React port of the existing `backend/templates/printables/website-referral-flyer.html`.
|
||||
|
||||
- Rendered at fixed internal size matching US Letter proportions (8.5" x 11")
|
||||
- CSS `transform: scale()` fits it into the dialog preview area
|
||||
- All config changes reflect instantly via React re-rendering
|
||||
- QR code rendered via `qr-code-styling` instance using the current QR prefs from the QR tab
|
||||
- Custom logo shown to the right of the Nomad Karaoke logo in the header
|
||||
|
||||
**Multi-page preview:** When `perPage` is 2 or 4, the preview shows the page layout with the flyer duplicated and scaled into a grid (1x2 or 2x2) with configured margins. Shows exactly what the printed page will look like.
|
||||
|
||||
## Flyer Controls Panel
|
||||
|
||||
`FlyerControls.tsx` — right side, scrollable, organized in collapsible sections:
|
||||
|
||||
### Preset Selector (top, always visible)
|
||||
- Dropdown: Light, Dark, custom presets
|
||||
- "Save as Preset" button
|
||||
|
||||
### Colors
|
||||
- Background — color picker
|
||||
- Headline gradient — 3 color pickers (start, mid, end)
|
||||
- Headline sub — color picker
|
||||
- Text — color picker
|
||||
- Subtext — color picker
|
||||
- Accent — color picker
|
||||
- "Reset Colors" button
|
||||
|
||||
### Text Overrides
|
||||
- Each field shows default as placeholder; empty = use default
|
||||
- Headline main, Headline sub, Subtitle, CTA label, CTA note
|
||||
- Steps 1-4: title + description each, collapsible per step
|
||||
|
||||
### Sections
|
||||
- Toggle switches: Subtitle, How-It-Works Steps, Divider, Bottom Features, Bottom Tagline
|
||||
|
||||
### Branding
|
||||
- File upload (png, jpg, svg)
|
||||
- Thumbnail preview + "Remove" button
|
||||
|
||||
### Print Layout
|
||||
- Per page: segmented button (1 / 2 / 4)
|
||||
- Page margins: slider (0-30mm, default 15mm)
|
||||
|
||||
## Export
|
||||
|
||||
### Formats
|
||||
- **PDF** (primary) — `html2canvas` at 2x resolution + `jsPDF`. Multi-per-page: render once, place multiple times at scale with margins.
|
||||
- **HTML** — serialize flyer DOM + inline styles, Google Fonts as links. Self-contained file.
|
||||
- **PNG** — `html2canvas` at 2x, single flyer only (ignores per-page setting).
|
||||
|
||||
### UX
|
||||
- Primary button: "Download PDF"
|
||||
- Secondary buttons: "Download HTML", "Download PNG"
|
||||
- Filename: `nomad-karaoke-flyer-{referralCode}.{ext}` (overridable via `flyerFilename` prop)
|
||||
|
||||
### New Dependencies
|
||||
- `html2canvas` — DOM-to-canvas rasterization
|
||||
- `jspdf` — PDF composition
|
||||
- ~200KB combined, client-side only
|
||||
|
||||
## Migration & Integration
|
||||
|
||||
### Dialog Rename
|
||||
- `QRCodeDialog` → `ReferralToolsDialog` (same props interface)
|
||||
- `ReferralDashboard.tsx` — update import
|
||||
- `admin/referrals/page.tsx` — update import; `onGenerateFlyer` prop becomes unused but kept for backwards compat
|
||||
|
||||
### Dialog Sizing
|
||||
- Expand from `sm:max-w-2xl` to `sm:max-w-4xl`
|
||||
|
||||
### i18n
|
||||
- New keys in `referrals` namespace for tab names, control labels, section headers, preset names, export buttons
|
||||
- Run `translate.py --target all` for all 33 locales
|
||||
- Admin pages are English-only, no concern
|
||||
|
||||
### Backend
|
||||
- No changes. Existing flyer endpoints remain functional but unused by frontend.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests for preset save/load logic and config defaults (`flyer-presets.ts`)
|
||||
- Unit tests for export functions with mocked html2canvas/jsPDF (`FlyerExport.tsx`)
|
||||
- Update existing `QRCodeDialog.test.tsx` → `ReferralToolsDialog.test.tsx`
|
||||
- Tab switching
|
||||
- Flyer config persistence to localStorage
|
||||
- QR-to-flyer state flow (QR prefs reflected in flyer preview)
|
||||
- Section visibility toggles
|
||||
- Preset loading/saving
|
||||
|
||||
## Decisions Log
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Client-side rendering over server-side | Instant preview, export to HTML/PNG/PDF, no backend changes |
|
||||
| Tabbed dialog over separate modals | Cohesive UX, natural QR→flyer flow |
|
||||
| QR config shared via parent state | Single source of truth, "Edit QR Style" link for easy tab switch |
|
||||
| localStorage for presets | Same pattern as existing QR prefs, no backend persistence needed |
|
||||
| html2canvas + jsPDF over other libs | Well-maintained, reasonable bundle size, handles single-page flyer well |
|
||||
| Keep backend endpoints | No breaking changes, can deprecate later |
|
||||
@@ -0,0 +1,407 @@
|
||||
# Nomad Karaoke Error Monitor — Design Spec
|
||||
|
||||
> **Date:** 2026-04-12
|
||||
> **Status:** Approved
|
||||
> **Scope:** Error Monitor service for production error detection, normalization, dedup, alerting, and resolution tracking across all Nomad Karaoke services.
|
||||
> **Reference:** Based on the Aquarius Error Bot system (`/Users/andrew/Projects/aquarius/docs/archive/error-bot-system-reference.md`)
|
||||
|
||||
---
|
||||
|
||||
## 1. System Overview
|
||||
|
||||
A Cloud Run Job that runs every 15 minutes, queries GCP Cloud Logging for errors across all production services, normalizes and deduplicates them, uses Gemini Flash to group related errors into incidents, sends alerts to Discord, tracks patterns in Firestore, and auto-resolves patterns that go silent.
|
||||
|
||||
### End-to-End Flow
|
||||
|
||||
```
|
||||
Production Errors (Cloud Logging)
|
||||
|
|
||||
v
|
||||
Error Monitor (Cloud Run Job, every 15 min)
|
||||
|-- Query Cloud Logging (ERROR severity, last 15 min)
|
||||
| |-- cloud_run_revision: karaoke-backend, karaoke-decide, audio-separator
|
||||
| |-- cloud_run_job: video-encoding-job, lyrics-transcription-job,
|
||||
| | audio-separation-job, audio-download-job
|
||||
| |-- cloud_function: gdrive-validator, runner_manager, backup_to_aws,
|
||||
| | divebar_mirror, kn_data_sync, divebar_lookup,
|
||||
| | encoding_worker_idle
|
||||
| |-- gce_instance: encoding-worker-a, encoding-worker-b,
|
||||
| flacfetch-vm, divebar-sync-vm
|
||||
|-- Normalize messages (strip IDs, timestamps, emails, job IDs, GCS paths)
|
||||
|-- Group by pattern hash (SHA-256 of service::normalized_message)
|
||||
|-- Check Firestore for existing patterns
|
||||
|-- LLM dedup: check new patterns against existing (Gemini Flash)
|
||||
|-- If 2+ new patterns: LLM incident analysis (group by root cause)
|
||||
|-- Send Discord alerts (per-incident or per-pattern)
|
||||
|-- Auto-resolve stale patterns (frequency-aware thresholds)
|
||||
|
|
||||
v
|
||||
Daily Digest (08:00 UTC, same job with DIGEST_MODE=true)
|
||||
|-- Dedup sweep of all active patterns
|
||||
|-- 24h summary: total errors, new patterns, frequency stats
|
||||
|-- Per-service breakdown
|
||||
|-- Send digest to Discord
|
||||
```
|
||||
|
||||
### Monitored Resources
|
||||
|
||||
| Category | Resources |
|
||||
|----------|-----------|
|
||||
| **Cloud Run Services** | karaoke-backend, karaoke-decide, audio-separator |
|
||||
| **Cloud Run Jobs** | video-encoding-job, lyrics-transcription-job, audio-separation-job, audio-download-job |
|
||||
| **Cloud Functions** | gdrive-validator, runner_manager, backup_to_aws, divebar_mirror, kn_data_sync, divebar_lookup, encoding_worker_idle |
|
||||
| **GCE Instances** | encoding-worker-a, encoding-worker-b, flacfetch-vm, divebar-sync-vm |
|
||||
|
||||
---
|
||||
|
||||
## 2. Log Collection
|
||||
|
||||
Four separate Cloud Logging queries, one per resource type, each scoped to:
|
||||
- Severity: `>=ERROR`
|
||||
- Time window: last 15 minutes (configurable via `LOOKBACK_MINUTES`)
|
||||
- Max entries: 500 total across all queries
|
||||
|
||||
### Query Resource Types
|
||||
|
||||
| Resource Type | Filter Field | Values |
|
||||
|---------------|-------------|--------|
|
||||
| `cloud_run_revision` | `resource.labels.service_name` | karaoke-backend, karaoke-decide, audio-separator |
|
||||
| `cloud_run_job` | `resource.labels.job_name` | video-encoding-job, lyrics-transcription-job, audio-separation-job, audio-download-job |
|
||||
| `cloud_function` | `resource.labels.function_name` | gdrive-validator, runner_manager, backup_to_aws, divebar_mirror, kn_data_sync, divebar_lookup, encoding_worker_idle |
|
||||
| `gce_instance` | `labels."compute.googleapis.com/resource_name"` | encoding-worker-a, encoding-worker-b, flacfetch-vm, divebar-sync-vm |
|
||||
|
||||
### Payload Handling
|
||||
|
||||
Three payload types (same as Aquarius):
|
||||
- Structured JSON dict → extract message from `textPayload` or `jsonPayload.message`
|
||||
- Plain text string → use directly
|
||||
- HTTP request logs (no payload) → skip
|
||||
|
||||
---
|
||||
|
||||
## 3. Message Normalization
|
||||
|
||||
### Standard Normalizers (from Aquarius)
|
||||
|
||||
| Pattern | Placeholder |
|
||||
|---------|-------------|
|
||||
| UUIDs | `<ID>` |
|
||||
| ISO timestamps | `<TS>` |
|
||||
| Epoch timestamps | `<EPOCH>` |
|
||||
| Hex/alphanumeric IDs (8+ chars) | `<ID>` |
|
||||
| Email addresses | `<EMAIL>` |
|
||||
| IP addresses | `<IP>` |
|
||||
| URLs | domain only |
|
||||
| Numbers (4+ digits) | `<NUM>` |
|
||||
|
||||
### NK-Specific Normalizers
|
||||
|
||||
| Pattern | Placeholder |
|
||||
|---------|-------------|
|
||||
| Job IDs (`/jobs/<id>`) | `/jobs/<ID>` |
|
||||
| GCS paths (`gs://nomadkaraoke-*/**`) | `gs://<BUCKET>/<PATH>` |
|
||||
| Firebase UIDs | `<UID>` |
|
||||
| Audio file references (hashes, filenames) | `<FILE>` |
|
||||
| Firestore document paths | `<DOC_PATH>` |
|
||||
|
||||
### Pattern Hash
|
||||
|
||||
`SHA-256(service::normalized_message)` — deterministic, collision-resistant.
|
||||
|
||||
---
|
||||
|
||||
## 4. LLM Analysis
|
||||
|
||||
### Model & Provider
|
||||
|
||||
- **Model:** Gemini 2.0 Flash via Vertex AI
|
||||
- **Auth:** Application Default Credentials (service account)
|
||||
- **Temperature:** 0.2 for incident analysis, 0.1 for dedup
|
||||
- **Retry:** Exponential backoff, 3 attempts, 2s base delay
|
||||
- **Fallback:** If LLM unavailable, group by service name (no root cause analysis)
|
||||
|
||||
### Incident Grouping
|
||||
|
||||
When 2+ new patterns are detected, the LLM analyzes them together. The system prompt provides NK-specific service dependency context:
|
||||
|
||||
```
|
||||
karaoke-backend (API) → orchestrates all workers
|
||||
├── audio-download-job → flacfetch-vm (downloads audio)
|
||||
├── audio-separation-job / audio-separator (GPU stem separation)
|
||||
├── lyrics-transcription-job (AudioShake + AI correction)
|
||||
├── video-encoding-job → encoding-worker-a/b (FFmpeg rendering)
|
||||
└── youtube-upload (distribution)
|
||||
|
||||
karaoke-decide (independent) → BigQuery, Spotify, Last.fm
|
||||
|
||||
Cloud Functions: gdrive-validator, backup_to_aws, divebar_mirror,
|
||||
kn_data_sync, divebar_lookup, runner_manager,
|
||||
encoding_worker_idle
|
||||
```
|
||||
|
||||
### Output Format (JSON)
|
||||
|
||||
```json
|
||||
{
|
||||
"incidents": [
|
||||
{
|
||||
"title": "max 60 chars",
|
||||
"root_cause": "one-liner",
|
||||
"severity": "P0|P1|P2|P3",
|
||||
"suggested_fix": "actionable, 1-2 sentences",
|
||||
"primary_service": "upstream root cause service",
|
||||
"pattern_indices": [1, 3]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Severity Levels
|
||||
|
||||
- **P0:** Service completely down, all jobs failing, payment processing broken
|
||||
- **P1:** Major pipeline stage broken (audio separation, lyrics, encoding), auth failures
|
||||
- **P2:** Degraded but functional — intermittent errors, slow responses, single-job failures
|
||||
- **P3:** Minor — deprecation warnings, cleanup failures, spot VM preemptions
|
||||
|
||||
### Duplicate Detection
|
||||
|
||||
Identifies near-duplicate patterns that regex normalization missed (different phrasing of same error). Only merges new patterns into existing canonical ones to preserve alert history.
|
||||
|
||||
---
|
||||
|
||||
## 5. Firestore Data Model
|
||||
|
||||
### `error_patterns` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `pattern_id` | string | SHA-256(service::normalized_message) — document ID |
|
||||
| `service` | string | Resource name (e.g., `karaoke-backend`, `video-encoding-job`) |
|
||||
| `resource_type` | string | `cloud_run_service` / `cloud_run_job` / `cloud_function` / `gce_instance` |
|
||||
| `normalized_message` | string | Regex-normalized error (max 200 chars) |
|
||||
| `sample_message` | string | Raw error sample |
|
||||
| `first_seen` | string (ISO) | First occurrence |
|
||||
| `last_seen` | string (ISO) | Most recent occurrence |
|
||||
| `total_count` | int | Cumulative count |
|
||||
| `rolling_counts` | map | `{YYYY-MM-DDTHH:MM → count}` (7-day window) |
|
||||
| `status` | string | `new` / `acknowledged` / `known` / `muted` / `fixed` / `auto_resolved` |
|
||||
| `incident_id` | string? | Link to grouped incident |
|
||||
| `severity` | string | `P0` / `P1` / `P2` / `P3` |
|
||||
| `alerted_at` | string (ISO) | When Discord alert was sent |
|
||||
| `notes` | string? | Free-text notes |
|
||||
| `merged_into` | string? | Pattern ID this was merged into |
|
||||
| `fixed_by` | map? | `{pr_display, pr_url, note, resolved_at}` |
|
||||
|
||||
### `error_incidents` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `incident_id` | string | `inc_YYYYMMDD_HHMM_<8-hex>` — document ID |
|
||||
| `title` | string | Max 60 chars |
|
||||
| `root_cause` | string? | LLM-identified |
|
||||
| `severity` | string | `P0` / `P1` / `P2` / `P3` |
|
||||
| `suggested_fix` | string? | Actionable next step |
|
||||
| `primary_service` | string | Upstream root cause service |
|
||||
| `pattern_ids` | list | Related pattern IDs |
|
||||
| `used_llm` | bool | Whether LLM analysis was used |
|
||||
| `created_at` | string (ISO) | Creation timestamp |
|
||||
| `status` | string | `open` / `investigating` / `fixed` / `false_positive` |
|
||||
|
||||
### `discord_alerts` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| Document ID | string | `alert_YYYYMMDD_HHMMSS_<8-hex>` |
|
||||
| `timestamp` | string (ISO) | When sent |
|
||||
| `alert_type` | string | `new_pattern` / `spike` / `incident` / `resolved_batch` / `daily_digest` |
|
||||
| `content` | string | Message text (max 2000 chars) |
|
||||
| `success` | bool | Whether webhook POST succeeded |
|
||||
| + alert-specific metadata | varies | service, pattern, count, severity, etc. |
|
||||
|
||||
### Migration from `known-issues.yaml`
|
||||
|
||||
Existing entries in `known-issues.yaml` are migrated to `error_patterns` documents with status `known` or `muted`. The YAML file is then deprecated.
|
||||
|
||||
---
|
||||
|
||||
## 6. Discord Notifications
|
||||
|
||||
### Webhook
|
||||
|
||||
Reuses the existing `discord-alert-webhook` secret in Secret Manager.
|
||||
|
||||
### Alert Types
|
||||
|
||||
| Alert Type | Trigger | Emoji | Content |
|
||||
|------------|---------|-------|---------|
|
||||
| **New Pattern** | Unrecognized error | `🔴` | Service, resource type, normalized msg, sample, count, timestamps, `/prod-investigate` prompt |
|
||||
| **Incident** | 2+ patterns grouped by LLM | `🚨`/`🔴`/`⚠️`/`🟡` (P0-P3) | Title, root cause, per-pattern details, suggested fix |
|
||||
| **Auto-Resolved** | Pattern silent past threshold | `✅` | Pattern, hours silent, consolidated |
|
||||
| **Spike** | Count > 5x rolling avg (min 5) | `⚠️` | Pattern, current vs. normal count |
|
||||
| **Daily Digest** | 08:00 UTC | `📊` | 24h totals, per-service breakdown, frequency stats |
|
||||
|
||||
### Format Rules
|
||||
|
||||
- Compact inline formatting (no bullet lists)
|
||||
- Show actual error message text, never summarize
|
||||
- Include copy-paste `/prod-investigate` prompts
|
||||
- Rate limited: max 10 messages per run
|
||||
- 2000-char limit with truncation
|
||||
- Timestamps in Eastern time (America/New_York, DST-aware)
|
||||
- Honest when LLM fails: "LLM grouping unavailable"
|
||||
|
||||
---
|
||||
|
||||
## 7. Auto-Resolution
|
||||
|
||||
Frequency-aware thresholds based on historical occurrence rate:
|
||||
|
||||
```
|
||||
threshold_hours = mean_interval_between_occurrences * AUTO_RESOLVE_MULTIPLIER
|
||||
```
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| `AUTO_RESOLVE_MULTIPLIER` | 8 (99.97% confidence, Poisson) |
|
||||
| `AUTO_RESOLVE_MIN_HOURS` | 6 |
|
||||
| `AUTO_RESOLVE_MAX_HOURS` | 168 (1 week) |
|
||||
| `AUTO_RESOLVE_FALLBACK_HOURS` | 48 (when <3 data points) |
|
||||
|
||||
High-frequency errors resolve faster; rare errors wait longer.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known Issues / Ignore Patterns
|
||||
|
||||
Regex patterns for infrastructure noise that never triggers alerts:
|
||||
|
||||
- Cloud Run cold start / startup probe failures
|
||||
- Spot VM preemption events (GitHub runners)
|
||||
- GitHub runner startup/shutdown noise
|
||||
- Encoding worker idle shutdown (expected)
|
||||
- Cloud Scheduler retry transients
|
||||
- Health check 404s from load balancers
|
||||
- Ready condition changes during deploys
|
||||
|
||||
Defined in `known_issues.py`, easy to add to without code changes.
|
||||
|
||||
---
|
||||
|
||||
## 9. Infrastructure (Pulumi)
|
||||
|
||||
### New Resources (`infrastructure/modules/error_monitor.py`)
|
||||
|
||||
1. **Cloud Run Job** (`nomad-error-monitor`)
|
||||
- Image: existing karaoke-backend Docker image
|
||||
- Command: `["python", "-m", "backend.services.error_monitor.monitor"]`
|
||||
- Memory: 512Mi, CPU: 1, Timeout: 300s, Max retries: 0
|
||||
- Env vars: `GCP_PROJECT_ID`, `ENVIRONMENT`, `DISCORD_WEBHOOK_URL` (Secret Manager ref)
|
||||
|
||||
2. **Cloud Scheduler — Monitor** (`error-monitor-trigger`)
|
||||
- Schedule: `*/15 * * * *` (UTC)
|
||||
- Target: Cloud Run Jobs API `:run`
|
||||
- Auth: OAuth token via scheduler service account
|
||||
- Retry: 1 attempt, 60s max
|
||||
|
||||
3. **Cloud Scheduler — Daily Digest** (`error-monitor-daily-digest`)
|
||||
- Schedule: `0 8 * * *` (UTC)
|
||||
- Same job, with `DIGEST_MODE=true` environment override
|
||||
|
||||
4. **Service Account** (`error-monitor-scheduler`)
|
||||
- `roles/run.invoker` on the Cloud Run Job
|
||||
|
||||
### IAM for Error Monitor Job
|
||||
|
||||
The job runs under the existing backend service account (`karaoke-backend-sa`), which already has Firestore and Secret Manager access. Additional role needed:
|
||||
- `roles/logging.viewer` (read Cloud Logging — not currently on the backend SA)
|
||||
|
||||
---
|
||||
|
||||
## 10. Slash Command Updates
|
||||
|
||||
All five `/prod-*` commands updated to use `error_patterns` as primary data source.
|
||||
|
||||
### `/prod-health`
|
||||
Add error pattern summary (active count, new patterns in last hour) alongside existing health endpoint checks.
|
||||
|
||||
### `/prod-errors`
|
||||
**Primary source becomes Firestore `error_patterns`** — fast, pre-deduplicated, pre-categorized. Cloud Logging becomes secondary, used only for stack traces when investigating a specific pattern.
|
||||
|
||||
### `/prod-investigate`
|
||||
Query `error_patterns` first for pattern context (history, frequency, related incidents), then Cloud Logging for stack traces and detailed samples.
|
||||
|
||||
### `/prod-review`
|
||||
Replace raw Cloud Logging categorization with pattern statuses: NEW, REGRESSIONS (previously fixed reoccurred), IN PROGRESS (acknowledged), KNOWN, VERIFIED FIXED. Remove `known-issues.yaml` dependency.
|
||||
|
||||
### `/prod-known-issue`
|
||||
Write to Firestore `error_patterns` (status: `known`/`muted`) instead of YAML file.
|
||||
|
||||
### Helper Scripts
|
||||
|
||||
- `scripts/query-error-patterns.py` — CLI to query patterns from Firestore (used by slash commands)
|
||||
- `scripts/resolve-error-pattern.py` — CLI to mark patterns as fixed with PR reference
|
||||
|
||||
---
|
||||
|
||||
## 11. Code Structure
|
||||
|
||||
```
|
||||
backend/services/error_monitor/
|
||||
├── __init__.py
|
||||
├── monitor.py # Entry point — query, normalize, group, analyze, alert
|
||||
├── config.py # Configuration constants, monitored services list
|
||||
├── normalizer.py # Message normalization (regex replacements)
|
||||
├── known_issues.py # Ignore pattern matching
|
||||
├── llm_analysis.py # Vertex AI Gemini incident grouping + dedup
|
||||
├── discord.py # Discord webhook client
|
||||
└── firestore_adapter.py # CRUD for error_patterns, incidents, alerts
|
||||
```
|
||||
|
||||
### Configuration (`config.py`)
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| `GCP_PROJECT` | `nomadkaraoke` |
|
||||
| `LOOKBACK_MINUTES` | 15 |
|
||||
| `MAX_LOG_ENTRIES` | 500 |
|
||||
| `LLM_ANALYSIS_ENABLED` | true (env var) |
|
||||
| `LLM_ANALYSIS_MODEL` | `gemini-2.0-flash` |
|
||||
| `MIN_PATTERNS_FOR_ANALYSIS` | 2 |
|
||||
| `SPIKE_MULTIPLIER` | 5.0 |
|
||||
| `SPIKE_MIN_COUNT` | 5 |
|
||||
| `MAX_DISCORD_MESSAGES_PER_RUN` | 10 |
|
||||
| `MAX_ACTIVE_PATTERNS` | 500 |
|
||||
| `ROLLING_WINDOW_DAYS` | 7 |
|
||||
| `DISCORD_WEBHOOK_SECRET` | `discord-alert-webhook` |
|
||||
|
||||
---
|
||||
|
||||
## 12. Testing
|
||||
|
||||
### Unit Tests
|
||||
|
||||
```
|
||||
tests/unit/services/error_monitor/
|
||||
├── test_monitor.py # Core grouping, windowing logic
|
||||
├── test_normalizer.py # Message normalization
|
||||
├── test_llm_analysis.py # LLM grouping, dedup
|
||||
├── test_firestore_adapter.py # CRUD, rolling counts, resolution
|
||||
├── test_discord.py # Message formatting
|
||||
├── test_known_issues.py # Ignore pattern matching
|
||||
├── test_dedup.py # Duplicate detection
|
||||
└── test_monitor_orchestration.py # Full pipeline integration
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- Test against Firestore emulator for pattern CRUD
|
||||
- Test Cloud Logging query construction (mock the API client)
|
||||
- Test Discord webhook formatting (mock HTTP)
|
||||
|
||||
---
|
||||
|
||||
## 13. Out of Scope (Future Work)
|
||||
|
||||
- **Auto-fixer (Nomad-fix):** Autonomous Claude Code agent that receives errors via Pub/Sub, creates fix PRs. Designed as a separate follow-up project.
|
||||
- **Frontend admin dashboard:** Visual error monitoring UI. The slash commands serve this purpose for now.
|
||||
- **Cross-repo error correlation:** Correlating errors between karaoke-gen and karaoke-decide Firestore. Both write to the same `error_patterns` collection, so patterns from both are visible together.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ import { useTranslations } from 'next-intl';
|
||||
import { getReferralInterstitial } from '@/lib/api';
|
||||
import { setReferralCode } from '@/lib/referral';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { getAccessToken } from '@/lib/api';
|
||||
import { getAccessToken, clearAccessToken, API_BASE_URL } from '@/lib/api';
|
||||
import type { ReferralInterstitial } from '@/lib/types';
|
||||
import { Gift, ArrowRight, Mail, CheckCircle, Loader2 } from 'lucide-react';
|
||||
|
||||
@@ -34,9 +34,23 @@ export function ReferralInterstitialClient() {
|
||||
// Store referral code immediately
|
||||
setReferralCode(code);
|
||||
|
||||
// Check if already logged in
|
||||
if (getAccessToken()) {
|
||||
setIsLoggedIn(true);
|
||||
// Validate token with backend (don't trust localStorage alone — token may be stale)
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
fetch(`${API_BASE_URL}/api/users/me`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.ok) {
|
||||
setIsLoggedIn(true);
|
||||
} else {
|
||||
// Stale token — clear it so the user can re-authenticate
|
||||
clearAccessToken();
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Network error — don't assume logged in
|
||||
});
|
||||
}
|
||||
|
||||
getReferralInterstitial(code)
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
Share2, Link as LinkIcon, Users, MousePointerClick, DollarSign,
|
||||
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight, Pencil, QrCode,
|
||||
} from "lucide-react"
|
||||
import QRCodeDialog from "@/components/referrals/QRCodeDialog"
|
||||
import ReferralToolsDialog from "@/components/referrals/ReferralToolsDialog"
|
||||
import { NextIntlClientProvider } from "next-intl"
|
||||
import enMessages from "@/messages/en.json"
|
||||
|
||||
@@ -498,12 +498,12 @@ export default function ReferralsPage() {
|
||||
{/* QR Code / Flyer Dialog */}
|
||||
{qrDialogCode && (
|
||||
<NextIntlClientProvider locale="en" messages={enMessages}>
|
||||
<QRCodeDialog
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${qrDialogCode}`}
|
||||
open={!!qrDialogCode}
|
||||
onOpenChange={(open) => { if (!open) setQrDialogCode(null) }}
|
||||
onGenerateFlyer={(theme, qrDataUrl) => adminApi.generateFlyer(qrDialogCode, theme, qrDataUrl)}
|
||||
flyerFilename={`nomad-karaoke-flyer-${qrDialogCode}.pdf`}
|
||||
flyerFilename={`nomad-karaoke-flyer-${qrDialogCode}`}
|
||||
referralCode={qrDialogCode}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
)}
|
||||
|
||||
@@ -207,6 +207,33 @@ export default function LyricsAnalyzer({
|
||||
[history, historyIndex]
|
||||
)
|
||||
|
||||
// Compute which word IDs have been edited by the user (compared to initial state)
|
||||
const editedWordIds = useMemo(() => {
|
||||
const initial = history[0]
|
||||
if (!initial || data === initial) return new Set<string>()
|
||||
// Build map of word ID → text from initial state
|
||||
const initialWordText = new Map<string, string>()
|
||||
for (const segment of initial.corrected_segments) {
|
||||
for (const word of segment.words) {
|
||||
initialWordText.set(word.id, word.text)
|
||||
}
|
||||
}
|
||||
const edited = new Set<string>()
|
||||
for (const segment of data.corrected_segments) {
|
||||
for (const word of segment.words) {
|
||||
const originalText = initialWordText.get(word.id)
|
||||
if (originalText === undefined) {
|
||||
// Word was added by the user
|
||||
edited.add(word.id)
|
||||
} else if (originalText !== word.text) {
|
||||
// Word text was changed
|
||||
edited.add(word.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
return edited
|
||||
}, [data, history])
|
||||
|
||||
// Reset history when initial data changes
|
||||
useEffect(() => {
|
||||
setHistory([initialData])
|
||||
@@ -1254,6 +1281,7 @@ export default function LyricsAnalyzer({
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
advancedMode={advancedMode}
|
||||
onAdvancedModeToggle={handleAdvancedModeToggle}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
<ReferenceView
|
||||
referenceSources={data.reference_lyrics}
|
||||
|
||||
@@ -33,6 +33,7 @@ export default function TranscriptionView({
|
||||
activeGapWordIds,
|
||||
advancedMode = false,
|
||||
onAdvancedModeToggle,
|
||||
editedWordIds,
|
||||
}: TranscriptionViewProps) {
|
||||
const t = useTranslations('lyricsReview.transcription')
|
||||
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
|
||||
@@ -201,6 +202,7 @@ export default function TranscriptionView({
|
||||
onEditCorrection={onEditCorrection}
|
||||
onAcceptCorrection={onAcceptCorrection}
|
||||
onShowCorrectionDetail={onShowCorrectionDetail}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -49,6 +49,8 @@ export interface HighlightedTextProps {
|
||||
onEditCorrection?: (wordId: string) => void
|
||||
onAcceptCorrection?: (wordId: string) => void
|
||||
onShowCorrectionDetail?: (wordId: string) => void
|
||||
// User-edited word tracking
|
||||
editedWordIds?: Set<string>
|
||||
}
|
||||
|
||||
export function HighlightedText({
|
||||
@@ -76,6 +78,7 @@ export function HighlightedText({
|
||||
onEditCorrection,
|
||||
onAcceptCorrection,
|
||||
onShowCorrectionDetail,
|
||||
editedWordIds,
|
||||
}: HighlightedTextProps) {
|
||||
const { handleWordClick } = useWordClick({
|
||||
mode,
|
||||
@@ -242,6 +245,7 @@ export function HighlightedText({
|
||||
isUncorrectedGap={wordPos.type === 'gap' && !wordPos.isCorrected}
|
||||
isCurrentlyPlaying={shouldHighlightWord(wordPos)}
|
||||
isActiveGap={activeGapWordIds?.has(wordPos.word.id)}
|
||||
isUserEdited={editedWordIds?.has(wordPos.word.id)}
|
||||
id={`word-${wordPos.word.id}`}
|
||||
onClick={() =>
|
||||
handleWordClick(
|
||||
@@ -348,6 +352,7 @@ export function HighlightedText({
|
||||
wordPos || { word: word.text, id: word.id }
|
||||
)}
|
||||
isActiveGap={activeGapWordIds?.has(word.id)}
|
||||
isUserEdited={editedWordIds?.has(word.id)}
|
||||
id={`word-${word.id}`}
|
||||
onClick={() => handleWordClick(word.text, word.id, anchor, sequence)}
|
||||
correction={correctionInfo}
|
||||
|
||||
@@ -14,6 +14,7 @@ export const WordComponent = React.memo(function Word({
|
||||
isUncorrectedGap,
|
||||
isCurrentlyPlaying,
|
||||
isActiveGap,
|
||||
isUserEdited,
|
||||
padding = 'px-[3px] py-[1px]',
|
||||
onClick,
|
||||
id,
|
||||
@@ -24,15 +25,18 @@ export const WordComponent = React.memo(function Word({
|
||||
}
|
||||
|
||||
// Determine background color class
|
||||
// User-edited takes priority over gap states (but not currently-playing or anchor)
|
||||
const bgColorClass = isCurrentlyPlaying
|
||||
? 'bg-blue-500 text-white'
|
||||
: isAnchor
|
||||
? HIGHLIGHT_CLASSES.anchor
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
: isUserEdited
|
||||
? HIGHLIGHT_CLASSES.userEdited
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
|
||||
const wordElement = (
|
||||
<span
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
'use client';
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { ChevronDown, Trash2, Upload, X } from 'lucide-react';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import type { FlyerConfig, NamedPreset } from './flyer-presets';
|
||||
import {
|
||||
BUILT_IN_PRESETS,
|
||||
loadCustomPresets,
|
||||
saveCustomPreset,
|
||||
deleteCustomPreset,
|
||||
} from './flyer-presets';
|
||||
|
||||
interface FlyerControlsProps {
|
||||
config: FlyerConfig;
|
||||
onChange: <K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => void;
|
||||
onLoadPreset: (config: FlyerConfig) => void;
|
||||
}
|
||||
|
||||
function ColorPicker({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={value.startsWith('#') ? value : '#000000'}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, defaultOpen, children }: { title: string; defaultOpen?: boolean; children: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(defaultOpen ?? true);
|
||||
return (
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
<CollapsibleTrigger className="flex items-center justify-between w-full py-1.5 text-sm font-medium text-foreground hover:text-primary transition-colors">
|
||||
{title}
|
||||
<ChevronDown className={`w-4 h-4 transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pt-2 pb-3 space-y-3">
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
const STEP_PLACEHOLDERS = [
|
||||
{ title: 'Pick any song', desc: 'Search by artist & title...' },
|
||||
{ title: 'Our system does the work', desc: 'Vocals removed, lyrics synced...' },
|
||||
{ title: 'Review & correct the lyrics and instrumental', desc: 'Fine-tune everything...' },
|
||||
{ title: 'Download or publish to YouTube', desc: 'Get your finished karaoke video...' },
|
||||
];
|
||||
|
||||
function detectActivePreset(config: FlyerConfig): string {
|
||||
const all = [...BUILT_IN_PRESETS, ...loadCustomPresets()];
|
||||
for (const preset of all) {
|
||||
if (preset.config.bgColor === config.bgColor
|
||||
&& preset.config.textColor === config.textColor
|
||||
&& preset.config.accentColor === config.accentColor
|
||||
&& JSON.stringify(preset.config.headlineGradient) === JSON.stringify(config.headlineGradient)) {
|
||||
return preset.name;
|
||||
}
|
||||
}
|
||||
return 'Custom';
|
||||
}
|
||||
|
||||
export default function FlyerControls({ config, onChange, onLoadPreset }: FlyerControlsProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const [customPresets, setCustomPresets] = useState<NamedPreset[]>(loadCustomPresets);
|
||||
const [activePreset, setActivePreset] = useState<string>(() => detectActivePreset(config));
|
||||
const [saveName, setSaveName] = useState('');
|
||||
const [showSave, setShowSave] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const allPresets = [...BUILT_IN_PRESETS, ...customPresets];
|
||||
|
||||
const handleLoadPreset = (name: string) => {
|
||||
const preset = allPresets.find(p => p.name === name);
|
||||
if (preset) {
|
||||
onLoadPreset(preset.config);
|
||||
setActivePreset(name);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSavePreset = () => {
|
||||
if (!saveName.trim()) return;
|
||||
saveCustomPreset(saveName.trim(), config);
|
||||
setCustomPresets(loadCustomPresets());
|
||||
setActivePreset(saveName.trim());
|
||||
setSaveName('');
|
||||
setShowSave(false);
|
||||
};
|
||||
|
||||
const handleDeletePreset = (name: string) => {
|
||||
deleteCustomPreset(name);
|
||||
setCustomPresets(loadCustomPresets());
|
||||
if (activePreset === name) setActivePreset('Custom');
|
||||
};
|
||||
|
||||
const handleConfigChange = <K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => {
|
||||
setActivePreset('Custom');
|
||||
onChange(key, value);
|
||||
};
|
||||
|
||||
const handleStepChange = (index: number, field: 'title' | 'desc', value: string) => {
|
||||
const newSteps = [...config.steps];
|
||||
newSteps[index] = { ...newSteps[index], [field]: value || null };
|
||||
handleConfigChange('steps', newSteps);
|
||||
};
|
||||
|
||||
const handleGradientChange = (index: number, value: string) => {
|
||||
const newGradient = [...config.headlineGradient];
|
||||
newGradient[index] = value;
|
||||
handleConfigChange('headlineGradient', newGradient);
|
||||
};
|
||||
|
||||
const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
handleConfigChange('customLogoUrl', reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 space-y-1 min-w-0 overflow-y-auto max-h-[65vh] pr-1">
|
||||
{/* Preset selector */}
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border">
|
||||
<select
|
||||
value={activePreset}
|
||||
onChange={(e) => handleLoadPreset(e.target.value)}
|
||||
className="flex-1 rounded border border-border bg-background text-foreground text-sm px-2 py-1.5"
|
||||
>
|
||||
{activePreset === 'Custom' && <option value="Custom">{t('flyerPresetCustom')}</option>}
|
||||
{allPresets.map(p => (
|
||||
<option key={p.name} value={p.name}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
{showSave ? (
|
||||
<div className="flex gap-1">
|
||||
<input
|
||||
value={saveName}
|
||||
onChange={(e) => setSaveName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSavePreset()}
|
||||
placeholder={t('flyerPresetName')}
|
||||
className="w-28 rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
autoFocus
|
||||
/>
|
||||
<button onClick={handleSavePreset} className="text-xs px-2 py-1 bg-primary text-primary-foreground rounded">
|
||||
{t('save')}
|
||||
</button>
|
||||
<button onClick={() => setShowSave(false)} className="text-xs px-1 py-1 text-muted-foreground">
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => setShowSave(true)} className="text-xs px-2 py-1.5 border border-border rounded text-muted-foreground hover:text-foreground">
|
||||
{t('flyerPresetSave')}
|
||||
</button>
|
||||
)}
|
||||
{customPresets.some(p => p.name === activePreset) && (
|
||||
<button onClick={() => handleDeletePreset(activePreset)} className="text-xs px-1 py-1 text-destructive">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<Section title={t('flyerColors')}>
|
||||
<ColorPicker label={t('qrBackground')} value={config.bgColor} onChange={(v) => handleConfigChange('bgColor', v)} />
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground">{t('flyerHeadlineGradient')}</span>
|
||||
<div className="flex gap-2 mt-1">
|
||||
{config.headlineGradient.map((c, i) => (
|
||||
<input
|
||||
key={i}
|
||||
type="color"
|
||||
value={c}
|
||||
onChange={(e) => handleGradientChange(i, e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ColorPicker label={t('flyerHeadlineSubColor')} value={config.headlineSubColor} onChange={(v) => handleConfigChange('headlineSubColor', v)} />
|
||||
<ColorPicker label={t('flyerTextColor')} value={config.textColor} onChange={(v) => handleConfigChange('textColor', v)} />
|
||||
<ColorPicker label={t('flyerSubtextColor')} value={config.subtextColor} onChange={(v) => handleConfigChange('subtextColor', v)} />
|
||||
<ColorPicker label={t('flyerAccentColor')} value={config.accentColor} onChange={(v) => handleConfigChange('accentColor', v)} />
|
||||
</Section>
|
||||
|
||||
{/* Text Overrides */}
|
||||
<Section title={t('flyerTextOverrides')} defaultOpen={false}>
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={config.headlineMain ?? ''}
|
||||
onChange={(e) => handleConfigChange('headlineMain', e.target.value || null)}
|
||||
placeholder="MAKE YOUR OWN"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<input
|
||||
value={config.headlineSub ?? ''}
|
||||
onChange={(e) => handleConfigChange('headlineSub', e.target.value || null)}
|
||||
placeholder="KARAOKE VIDEOS"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<textarea
|
||||
value={config.subtitle ?? ''}
|
||||
onChange={(e) => handleConfigChange('subtitle', e.target.value || null)}
|
||||
placeholder="Turn any song into a professional karaoke video..."
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5 h-16 resize-none"
|
||||
/>
|
||||
<input
|
||||
value={config.ctaLabel ?? ''}
|
||||
onChange={(e) => handleConfigChange('ctaLabel', e.target.value || null)}
|
||||
placeholder="First track free + X% off with this link"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<input
|
||||
value={config.ctaNote ?? ''}
|
||||
onChange={(e) => handleConfigChange('ctaNote', e.target.value || null)}
|
||||
placeholder="Scan the QR code or visit the link above"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
{config.steps.map((step, i) => (
|
||||
<Collapsible key={i}>
|
||||
<CollapsibleTrigger className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1">
|
||||
<ChevronDown className="w-3 h-3" /> Step {i + 1}
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pl-4 pt-1 space-y-1">
|
||||
<input
|
||||
value={step.title ?? ''}
|
||||
onChange={(e) => handleStepChange(i, 'title', e.target.value)}
|
||||
placeholder={STEP_PLACEHOLDERS[i].title}
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
/>
|
||||
<input
|
||||
value={step.desc ?? ''}
|
||||
onChange={(e) => handleStepChange(i, 'desc', e.target.value)}
|
||||
placeholder={STEP_PLACEHOLDERS[i].desc}
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{/* Sections */}
|
||||
<Section title={t('flyerSections')}>
|
||||
{([
|
||||
['showSubtitle', t('flyerToggleSubtitle')],
|
||||
['showSteps', t('flyerToggleSteps')],
|
||||
['showDivider', t('flyerToggleDivider')],
|
||||
['showBottomFeatures', t('flyerToggleFeatures')],
|
||||
['showBottomTagline', t('flyerToggleTagline')],
|
||||
] as const).map(([key, label]) => (
|
||||
<div key={key} className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<Switch
|
||||
checked={config[key] as boolean}
|
||||
onCheckedChange={(v) => handleConfigChange(key, v)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
{/* Branding */}
|
||||
<Section title={t('flyerBranding')} defaultOpen={false}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/svg+xml"
|
||||
onChange={handleLogoUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
{config.customLogoUrl ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<img src={config.customLogoUrl} alt="Custom logo" className="h-10 w-auto rounded border border-border" />
|
||||
<button
|
||||
onClick={() => handleConfigChange('customLogoUrl', null)}
|
||||
className="text-xs text-destructive flex items-center gap-1"
|
||||
>
|
||||
<X className="w-3 h-3" /> {t('flyerRemoveLogo')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="text-xs px-3 py-1.5 border border-border rounded text-muted-foreground hover:text-foreground flex items-center gap-1.5"
|
||||
>
|
||||
<Upload className="w-3.5 h-3.5" /> {t('flyerUploadLogo')}
|
||||
</button>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* Print Layout */}
|
||||
<Section title={t('flyerPrintLayout')}>
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground">{t('flyerPerPage')}</span>
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
{([1, 2, 4] as const).map(n => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => handleConfigChange('perPage', n)}
|
||||
className={`px-3 py-1.5 text-xs rounded border transition-colors ${
|
||||
config.perPage === n
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">{t('flyerMargins')}</span>
|
||||
<span className="text-xs text-muted-foreground">{config.marginMm}mm</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[config.marginMm]}
|
||||
onValueChange={([v]) => handleConfigChange('marginMm', v)}
|
||||
min={0}
|
||||
max={30}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import html2canvas from 'html2canvas';
|
||||
import jsPDF from 'jspdf';
|
||||
|
||||
// US Letter in mm
|
||||
const PAGE_W_MM = 215.9;
|
||||
const PAGE_H_MM = 279.4;
|
||||
|
||||
interface PdfOptions {
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
export async function exportFlyerPdf(
|
||||
flyerElement: HTMLElement,
|
||||
options: PdfOptions,
|
||||
): Promise<void> {
|
||||
const { perPage, marginMm, filename } = options;
|
||||
|
||||
const canvas = await html2canvas(flyerElement, {
|
||||
scale: 2,
|
||||
useCORS: true,
|
||||
allowTaint: true,
|
||||
backgroundColor: null,
|
||||
});
|
||||
|
||||
const imgData = canvas.toDataURL('image/png');
|
||||
const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'letter' });
|
||||
|
||||
const margin = marginMm;
|
||||
const usableW = PAGE_W_MM - margin * 2;
|
||||
const usableH = PAGE_H_MM - margin * 2;
|
||||
const flyerAspect = 8.5 / 11;
|
||||
|
||||
if (perPage === 1) {
|
||||
let w = usableW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > usableH) {
|
||||
h = usableH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const x = margin + (usableW - w) / 2;
|
||||
const y = margin + (usableH - h) / 2;
|
||||
pdf.addImage(imgData, 'PNG', x, y, w, h);
|
||||
} else if (perPage === 2) {
|
||||
const gapMm = margin;
|
||||
const slotH = (usableH - gapMm) / 2;
|
||||
let w = usableW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > slotH) {
|
||||
h = slotH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const x = margin + (usableW - w) / 2;
|
||||
pdf.addImage(imgData, 'PNG', x, margin, w, h);
|
||||
pdf.addImage(imgData, 'PNG', x, margin + slotH + gapMm, w, h);
|
||||
} else {
|
||||
const gapMm = margin;
|
||||
const slotW = (usableW - gapMm) / 2;
|
||||
const slotH = (usableH - gapMm) / 2;
|
||||
let w = slotW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > slotH) {
|
||||
h = slotH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const positions = [
|
||||
[margin, margin],
|
||||
[margin + slotW + gapMm, margin],
|
||||
[margin, margin + slotH + gapMm],
|
||||
[margin + slotW + gapMm, margin + slotH + gapMm],
|
||||
];
|
||||
for (const [px, py] of positions) {
|
||||
const offsetX = px + (slotW - w) / 2;
|
||||
const offsetY = py + (slotH - h) / 2;
|
||||
pdf.addImage(imgData, 'PNG', offsetX, offsetY, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
pdf.save(filename);
|
||||
}
|
||||
|
||||
export function exportFlyerHtml(flyerElement: HTMLElement): Blob {
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke Referral Flyer</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
@page { size: 8.5in 11in; margin: 0; }
|
||||
body { display: flex; justify-content: center; }
|
||||
@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${flyerElement.outerHTML}
|
||||
</body>
|
||||
</html>`;
|
||||
return new Blob([html], { type: 'text/html' });
|
||||
}
|
||||
|
||||
export async function exportFlyerPng(
|
||||
flyerElement: HTMLElement,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const canvas = await html2canvas(flyerElement, {
|
||||
scale: 2,
|
||||
useCORS: true,
|
||||
allowTaint: true,
|
||||
backgroundColor: null,
|
||||
});
|
||||
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob((b: Blob | null) => {
|
||||
if (b) resolve(b);
|
||||
else reject(new Error('Failed to export flyer as PNG'));
|
||||
}, 'image/png');
|
||||
});
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { FlyerConfig } from './flyer-presets';
|
||||
|
||||
// Default text values matching the original HTML template
|
||||
const DEFAULTS = {
|
||||
headlineMain: 'MAKE YOUR OWN',
|
||||
headlineSub: 'KARAOKE VIDEOS',
|
||||
subtitle:
|
||||
'Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.',
|
||||
ctaLabel: (discountPercent: number) =>
|
||||
`First track free + ${discountPercent}% off with this link`,
|
||||
ctaNote: 'Scan the QR code or visit the link above',
|
||||
steps: [
|
||||
{ title: 'Pick any song', desc: 'Search by artist & title or paste a YouTube link' },
|
||||
{ title: 'Our system does the work', desc: 'Vocals removed, lyrics synced, video rendered automatically' },
|
||||
{ title: 'Review & correct the lyrics and instrumental', desc: 'Fine-tune everything before publishing' },
|
||||
{ title: 'Download or publish to YouTube', desc: 'Get your finished karaoke video in minutes' },
|
||||
],
|
||||
};
|
||||
|
||||
// Inline SVG Nomad Karaoke wordmark (from the HTML template)
|
||||
function NomadLogo({ color }: { color: string }) {
|
||||
return (
|
||||
<svg style={{ width: 260, height: 'auto' }} viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill={color} transform="translate(48.368003845214844,62.62239074707031)">
|
||||
<g transform="translate(0,0)">
|
||||
<g transform="scale(1.4000000000000004)">
|
||||
<g stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" paintOrder="stroke" fillOpacity="0">
|
||||
<path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)" />
|
||||
</g>
|
||||
<g transform="translate(0,38.959999084472656)">
|
||||
<g stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" paintOrder="stroke" fill={color} fillOpacity="0" transform="scale(1.02719)">
|
||||
<path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
interface FlyerPreviewProps {
|
||||
config: FlyerConfig;
|
||||
referralCode: string;
|
||||
discountPercent: number;
|
||||
qrDataUrl: string | null;
|
||||
/** Ref to the inner flyer element for export */
|
||||
flyerRef?: React.RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
|
||||
export default function FlyerPreview({
|
||||
config,
|
||||
referralCode,
|
||||
discountPercent,
|
||||
qrDataUrl,
|
||||
flyerRef,
|
||||
}: FlyerPreviewProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Scale flyer to fit its preview container
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const resize = () => {
|
||||
const flyerEl = container.querySelector('[data-flyer-page]') as HTMLElement;
|
||||
if (!flyerEl) return;
|
||||
const parentW = container.parentElement?.clientWidth || container.clientWidth;
|
||||
// Flyer: 8.5in x 11in at 96dpi = 816 x 1056 px
|
||||
const flyerW = 816;
|
||||
const flyerH = 1056;
|
||||
const scale = Math.min(parentW / flyerW, 1);
|
||||
flyerEl.style.transform = `scale(${scale})`;
|
||||
flyerEl.style.transformOrigin = 'top left';
|
||||
container.style.width = `${flyerW * scale}px`;
|
||||
container.style.height = `${flyerH * scale}px`;
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(container.parentElement || container);
|
||||
resize();
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const headlineMain = config.headlineMain ?? DEFAULTS.headlineMain;
|
||||
const headlineSub = config.headlineSub ?? DEFAULTS.headlineSub;
|
||||
const subtitle = config.subtitle ?? DEFAULTS.subtitle;
|
||||
const ctaLabel = config.ctaLabel ?? DEFAULTS.ctaLabel(discountPercent);
|
||||
const ctaNote = config.ctaNote ?? DEFAULTS.ctaNote;
|
||||
const steps = DEFAULTS.steps.map((def, i) => ({
|
||||
title: config.steps[i]?.title ?? def.title,
|
||||
desc: config.steps[i]?.desc ?? def.desc,
|
||||
}));
|
||||
|
||||
const gradientStr = `linear-gradient(135deg, ${config.headlineGradient.join(', ')})`;
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative overflow-hidden">
|
||||
<div
|
||||
ref={flyerRef}
|
||||
data-flyer-page=""
|
||||
style={{
|
||||
width: 816,
|
||||
height: 1056,
|
||||
fontFamily: "'Outfit', sans-serif",
|
||||
background: config.bgColor,
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
padding: '0.6in 0.65in 0.5in',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* Logo row */}
|
||||
<div style={{ marginBottom: 24, display: 'flex', alignItems: 'center', gap: 16 }}>
|
||||
<NomadLogo color={config.accentColor} />
|
||||
{config.customLogoUrl && (
|
||||
<img
|
||||
src={config.customLogoUrl}
|
||||
alt="Custom logo"
|
||||
style={{ height: 60, width: 'auto', objectFit: 'contain' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Headline */}
|
||||
<div style={{ fontFamily: "'Bebas Neue', sans-serif", textAlign: 'center', lineHeight: 0.92, marginBottom: 6 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 96,
|
||||
letterSpacing: 3,
|
||||
background: gradientStr,
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
backgroundClip: 'text',
|
||||
}}
|
||||
>
|
||||
{headlineMain}
|
||||
</div>
|
||||
<div style={{ fontSize: 62, letterSpacing: 2, color: config.headlineSubColor }}>
|
||||
{headlineSub}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Subtitle */}
|
||||
{config.showSubtitle && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 20,
|
||||
fontWeight: 500,
|
||||
color: config.subtextColor,
|
||||
textAlign: 'center',
|
||||
maxWidth: '5.5in',
|
||||
lineHeight: 1.4,
|
||||
marginBottom: 28,
|
||||
}}
|
||||
>
|
||||
{subtitle}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Steps */}
|
||||
{config.showSteps && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 18, width: '100%', maxWidth: '6in', marginBottom: 28 }}>
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
|
||||
<div
|
||||
style={{
|
||||
width: 52,
|
||||
height: 52,
|
||||
flexShrink: 0,
|
||||
borderRadius: '50%',
|
||||
background: `linear-gradient(135deg, ${config.accentColor}, ${config.headlineGradient[1] || config.accentColor})`,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontFamily: "'Bebas Neue', sans-serif",
|
||||
fontSize: 30,
|
||||
color: '#fff',
|
||||
letterSpacing: 1,
|
||||
}}
|
||||
>
|
||||
{i + 1}
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 22, fontWeight: 800, color: config.textColor, letterSpacing: -0.3 }}>
|
||||
{step.title}
|
||||
</div>
|
||||
<div style={{ fontSize: 16, fontWeight: 400, color: config.subtextColor, marginTop: 2 }}>
|
||||
{step.desc}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Divider */}
|
||||
{config.showDivider && (
|
||||
<div
|
||||
style={{
|
||||
width: '80%',
|
||||
height: 2,
|
||||
background: `linear-gradient(90deg, transparent, ${config.accentColor}4D, ${config.headlineGradient[1] || config.accentColor}4D, transparent)`,
|
||||
margin: '4px 0 24px',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* CTA section */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 40, width: '100%', marginBottom: 20 }}>
|
||||
<div
|
||||
style={{
|
||||
width: 180,
|
||||
height: 180,
|
||||
borderRadius: 16,
|
||||
background: '#fff',
|
||||
border: '3px solid #e8e4e0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.06)',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt={`QR Code - nomadkaraoke.com/r/${referralCode.toLowerCase()}`} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
|
||||
) : (
|
||||
<span style={{ fontSize: 14, color: '#999', textAlign: 'center', padding: 20 }}>QR Code</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 600, color: config.subtextColor, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 6 }}>
|
||||
{ctaLabel}
|
||||
</div>
|
||||
<div style={{ fontFamily: "'Bebas Neue', sans-serif", fontSize: 38, letterSpacing: 2, color: config.textColor, lineHeight: 1, whiteSpace: 'nowrap' }}>
|
||||
NOMADKARAOKE.COM/R/
|
||||
<span
|
||||
style={{
|
||||
background: `linear-gradient(135deg, ${config.headlineGradient.join(', ')}, #ffdf6b)`,
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
backgroundClip: 'text',
|
||||
letterSpacing: 4,
|
||||
}}
|
||||
>
|
||||
{referralCode.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 15, color: config.subtextColor, marginTop: 8, fontWeight: 500 }}>
|
||||
{ctaNote}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom */}
|
||||
<div style={{ marginTop: 'auto', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
{config.showBottomFeatures && (
|
||||
<div style={{ display: 'flex', gap: 24 }}>
|
||||
{[
|
||||
{ icon: '\u{1F3A4}', label: 'Any Song' },
|
||||
{ icon: '\u26A1', label: 'Automatic' },
|
||||
{ icon: '\u{1F3AC}', label: 'Pro Quality' },
|
||||
].map(({ icon, label }) => (
|
||||
<div key={label} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 600, color: config.subtextColor }}>
|
||||
<span style={{ fontSize: 20 }}>{icon}</span>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{config.showBottomTagline && (
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: config.subtextColor, letterSpacing: 1, marginLeft: 'auto' }}>
|
||||
Wherever you are, sing!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Download, Pencil } from 'lucide-react';
|
||||
import type { QRStylePrefs } from './QRCodeTab';
|
||||
import type { FlyerConfig } from './flyer-presets';
|
||||
import { DEFAULT_FLYER_CONFIG, loadFlyerConfig, saveFlyerConfig } from './flyer-presets';
|
||||
import FlyerPreview from './FlyerPreview';
|
||||
import FlyerControls from './FlyerControls';
|
||||
import { exportFlyerPdf, exportFlyerHtml, exportFlyerPng } from './FlyerExport';
|
||||
|
||||
interface FlyerTabProps {
|
||||
referralCode: string;
|
||||
discountPercent: number;
|
||||
qrPrefs: QRStylePrefs;
|
||||
onSwitchToQr: () => void;
|
||||
flyerFilename?: string;
|
||||
}
|
||||
|
||||
export default function FlyerTab({ referralCode, discountPercent, qrPrefs, onSwitchToQr, flyerFilename }: FlyerTabProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const flyerRef = useRef<HTMLDivElement>(null);
|
||||
const [config, setConfig] = useState<FlyerConfig>(DEFAULT_FLYER_CONFIG);
|
||||
const [exporting, setExporting] = useState<string | null>(null);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
|
||||
// Load saved config
|
||||
useEffect(() => {
|
||||
setConfig(loadFlyerConfig());
|
||||
}, []);
|
||||
|
||||
// Debounced save
|
||||
const updateConfig = useCallback(<K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => {
|
||||
setConfig(prev => {
|
||||
const next = { ...prev, [key]: value };
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => saveFlyerConfig(next), 300);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadPreset = useCallback((presetConfig: FlyerConfig) => {
|
||||
// Cancel any pending debounce to avoid overwriting the preset
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current);
|
||||
debounceRef.current = null;
|
||||
}
|
||||
setConfig(presetConfig);
|
||||
saveFlyerConfig(presetConfig);
|
||||
}, []);
|
||||
|
||||
// Render QR code for flyer using qr-code-styling
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const renderQr = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
if (cancelled) return;
|
||||
|
||||
let image: string | undefined;
|
||||
if (qrPrefs.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (qrPrefs.logo === 'emoji' && qrPrefs.logoEmoji) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 64;
|
||||
canvas.height = 64;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
ctx.font = '52px serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(qrPrefs.logoEmoji, 32, 36);
|
||||
image = canvas.toDataURL('image/png');
|
||||
}
|
||||
}
|
||||
|
||||
const qr = new QRCodeStyling({
|
||||
width: 160,
|
||||
height: 160,
|
||||
data: `https://nomadkaraoke.com/r/${referralCode.toLowerCase()}`,
|
||||
dotsOptions: { type: qrPrefs.dotStyle, color: qrPrefs.fgColor },
|
||||
cornersSquareOptions: { type: qrPrefs.cornerSquareStyle, color: qrPrefs.fgColor },
|
||||
cornersDotOptions: { type: qrPrefs.cornerDotStyle, color: qrPrefs.fgColor },
|
||||
backgroundOptions: { color: qrPrefs.bgColor },
|
||||
image,
|
||||
imageOptions: { hideBackgroundDots: true, imageSize: 0.2, margin: 4 },
|
||||
});
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
const blob = await qr.getRawData('png');
|
||||
if (blob && !cancelled) {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
if (!cancelled) setQrDataUrl(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(blob as Blob);
|
||||
}
|
||||
};
|
||||
renderQr();
|
||||
return () => { cancelled = true; };
|
||||
}, [qrPrefs, referralCode]);
|
||||
|
||||
// Cleanup debounce
|
||||
useEffect(() => {
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, []);
|
||||
|
||||
const baseFilename = flyerFilename?.replace(/\.[^.]+$/, '') || `nomad-karaoke-flyer-${referralCode}`;
|
||||
|
||||
const handleExport = async (format: 'pdf' | 'html' | 'png') => {
|
||||
const el = flyerRef.current;
|
||||
if (!el) return;
|
||||
setExporting(format);
|
||||
try {
|
||||
if (format === 'pdf') {
|
||||
await exportFlyerPdf(el, {
|
||||
perPage: config.perPage,
|
||||
marginMm: config.marginMm,
|
||||
filename: `${baseFilename}.pdf`,
|
||||
});
|
||||
} else if (format === 'html') {
|
||||
const blob = exportFlyerHtml(el);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${baseFilename}.html`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} else {
|
||||
await exportFlyerPng(el, `${baseFilename}.png`);
|
||||
}
|
||||
} finally {
|
||||
setExporting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: Flyer Preview */}
|
||||
<div className="flex-shrink-0 relative">
|
||||
<FlyerPreview
|
||||
config={config}
|
||||
referralCode={referralCode}
|
||||
discountPercent={discountPercent}
|
||||
qrDataUrl={qrDataUrl}
|
||||
flyerRef={flyerRef}
|
||||
/>
|
||||
{/* Edit QR Style link */}
|
||||
<button
|
||||
onClick={onSwitchToQr}
|
||||
className="absolute bottom-2 left-2 text-xs text-primary flex items-center gap-1 hover:underline bg-background/80 rounded px-1.5 py-0.5"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
{t('flyerEditQr')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<FlyerControls config={config} onChange={updateConfig} onLoadPreset={loadPreset} />
|
||||
</div>
|
||||
|
||||
{/* Export buttons */}
|
||||
<div className="flex gap-2 pt-2 border-t border-border sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleExport('pdf')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{exporting === 'pdf' ? t('flyerExporting') : t('flyerDownloadPdf')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExport('html')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('flyerDownloadHtml')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExport('png')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('flyerDownloadPng')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,461 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { QrCode, Download } from 'lucide-react';
|
||||
import { generateFlyer } from '@/lib/api';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
const STORAGE_KEY = 'nk-qr-style-prefs';
|
||||
|
||||
type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
|
||||
type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
|
||||
type CornerDotStyle = 'square' | 'dot';
|
||||
type LogoOption = 'none' | 'nomad' | 'emoji';
|
||||
|
||||
interface QRStylePrefs {
|
||||
dotStyle: DotStyle;
|
||||
cornerSquareStyle: CornerSquareStyle;
|
||||
cornerDotStyle: CornerDotStyle;
|
||||
fgColor: string;
|
||||
bgColor: string;
|
||||
logo: LogoOption;
|
||||
logoEmoji: string;
|
||||
}
|
||||
|
||||
const DEFAULT_PREFS: QRStylePrefs = {
|
||||
dotStyle: 'square',
|
||||
cornerSquareStyle: 'square',
|
||||
cornerDotStyle: 'square',
|
||||
fgColor: '#000000',
|
||||
bgColor: '#ffffff',
|
||||
logo: 'none',
|
||||
logoEmoji: '🎤',
|
||||
};
|
||||
|
||||
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
|
||||
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
|
||||
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
|
||||
|
||||
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'rounded': 'qrStyleRounded',
|
||||
'dots': 'qrStyleDots',
|
||||
'classy': 'qrStyleClassy',
|
||||
'classy-rounded': 'qrStyleClassyRounded',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
};
|
||||
|
||||
function loadPrefs(): QRStylePrefs {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_PREFS, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_PREFS };
|
||||
}
|
||||
|
||||
function savePrefs(prefs: QRStylePrefs) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function emojiToDataUrl(emoji: string): string {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 64;
|
||||
canvas.height = 64;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return '';
|
||||
ctx.font = '52px serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(emoji, 32, 36);
|
||||
return canvas.toDataURL('image/png');
|
||||
}
|
||||
|
||||
interface QRCodeDialogProps {
|
||||
referralUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Override the flyer generator (e.g. admin endpoint). Receives theme + QR data URL, returns PDF blob. */
|
||||
onGenerateFlyer?: (theme: 'light' | 'dark', qrDataUrl: string) => Promise<Blob>;
|
||||
/** Override the download filename */
|
||||
flyerFilename?: string;
|
||||
}
|
||||
|
||||
export default function QRCodeDialog({ referralUrl, open, onOpenChange, onGenerateFlyer, flyerFilename }: QRCodeDialogProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
|
||||
const [prefs, setPrefs] = useState<QRStylePrefs>(DEFAULT_PREFS);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [flyerTheme, setFlyerTheme] = useState<'light' | 'dark'>('light');
|
||||
const [flyerLoading, setFlyerLoading] = useState(false);
|
||||
const [flyerError, setFlyerError] = useState('');
|
||||
|
||||
// Load prefs from localStorage on open
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setPrefs(loadPrefs());
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Build QR options from prefs
|
||||
const buildOptions = useCallback((p: QRStylePrefs) => {
|
||||
let image: string | undefined;
|
||||
if (p.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (p.logo === 'emoji' && p.logoEmoji) {
|
||||
image = emojiToDataUrl(p.logoEmoji);
|
||||
}
|
||||
|
||||
return {
|
||||
width: 250,
|
||||
height: 250,
|
||||
data: referralUrl,
|
||||
dotsOptions: { type: p.dotStyle, color: p.fgColor },
|
||||
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
|
||||
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
|
||||
backgroundOptions: { color: p.bgColor },
|
||||
image,
|
||||
imageOptions: { hideBackgroundDots: true, imageSize: 0.2, margin: 4 },
|
||||
};
|
||||
}, [referralUrl]);
|
||||
|
||||
// Initialize / update QR code
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const init = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
if (!qrRef.current) {
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
if (!cancelled && containerRef.current) {
|
||||
containerRef.current.innerHTML = '';
|
||||
qrRef.current.append(containerRef.current);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
qrRef.current.update(buildOptions(prefs));
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
init();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, prefs, buildOptions]);
|
||||
|
||||
// Clean up on close
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
qrRef.current = null;
|
||||
setLoaded(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Clean up debounce timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
|
||||
setPrefs(prev => {
|
||||
const next = { ...prev, [key]: value };
|
||||
// Debounce localStorage save
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => savePrefs(next), 300);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleGenerateFlyer = async () => {
|
||||
setFlyerLoading(true);
|
||||
setFlyerError('');
|
||||
try {
|
||||
let qrDataUrl: string;
|
||||
if (qrRef.current) {
|
||||
const blob = await qrRef.current.getRawData('svg');
|
||||
if (blob) {
|
||||
qrDataUrl = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(new Error('Failed to read QR code data'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} else {
|
||||
throw new Error('Failed to generate QR code image');
|
||||
}
|
||||
} else {
|
||||
throw new Error('QR code not initialized');
|
||||
}
|
||||
|
||||
const flyerFn = onGenerateFlyer || generateFlyer;
|
||||
const pdfBlob = await flyerFn(flyerTheme, qrDataUrl);
|
||||
const url = URL.createObjectURL(pdfBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = flyerFilename || 'nomad-karaoke-referral-flyer.pdf';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to generate flyer';
|
||||
setFlyerError(message);
|
||||
console.error('Failed to generate flyer:', err);
|
||||
} finally {
|
||||
setFlyerLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownload = async (extension: 'png' | 'svg') => {
|
||||
// Initialize QR instance if not yet ready (e.g., download clicked before init effect completes)
|
||||
if (!qrRef.current) {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
}
|
||||
await qrRef.current.download({ name: 'referral-qr', extension });
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl bg-card border-border max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<QrCode className="w-5 h-5" />
|
||||
{t('qrTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: QR Preview */}
|
||||
<div className="flex-shrink-0 flex items-center justify-center">
|
||||
<div
|
||||
className="relative w-[250px] h-[250px] rounded-lg border border-border"
|
||||
style={{ backgroundColor: prefs.bgColor }}
|
||||
>
|
||||
{/* QR code is appended into this container by qr-code-styling */}
|
||||
<div ref={containerRef} className="w-full h-full" />
|
||||
{/* Loading skeleton rendered as a sibling so innerHTML clear doesn't affect React tree */}
|
||||
{!loaded && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<div className="flex-1 space-y-4 min-w-0">
|
||||
{/* Dot Style */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('dotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.dotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(DOT_STYLE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Frame */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_SQUARE_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerSquareStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerSquareStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_SQUARE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Dot */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerDotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerDotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_DOT_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
|
||||
<div className="flex gap-4 mt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.fgColor}
|
||||
onChange={(e) => updatePref('fgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.bgColor}
|
||||
onChange={(e) => updatePref('bgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center Logo */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
{(['none', 'nomad', 'emoji'] as LogoOption[]).map(option => {
|
||||
const labelKeys: Record<LogoOption, string> = {
|
||||
none: 'qrLogoNone',
|
||||
nomad: 'qrLogoNomad',
|
||||
emoji: 'qrLogoEmoji',
|
||||
};
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
onClick={() => updatePref('logo', option)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.logo === option
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(labelKeys[option])}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{prefs.logo === 'emoji' && (
|
||||
<input
|
||||
type="text"
|
||||
value={prefs.logoEmoji}
|
||||
onChange={(e) => {
|
||||
// Take only the last entered character/emoji
|
||||
const val = e.target.value;
|
||||
const emoji = [...val].pop() || '';
|
||||
updatePref('logoEmoji', emoji);
|
||||
}}
|
||||
className="w-10 h-7 text-center text-base rounded border border-border"
|
||||
maxLength={4}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="w-full space-y-3">
|
||||
{/* Flyer generation */}
|
||||
<div className="flex items-center gap-3 pt-2 border-t border-border">
|
||||
<span className="text-sm font-medium text-foreground">{t('flyerTheme')}</span>
|
||||
<div className="flex gap-1.5">
|
||||
{(['light', 'dark'] as const).map(theme => (
|
||||
<button
|
||||
key={theme}
|
||||
onClick={() => setFlyerTheme(theme)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors ${
|
||||
flyerTheme === theme
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(theme === 'light' ? 'flyerThemeLight' : 'flyerThemeDark')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleGenerateFlyer}
|
||||
disabled={flyerLoading}
|
||||
className="ml-auto px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{flyerLoading ? t('flyerGenerating') : t('flyerGenerate')}
|
||||
</button>
|
||||
</div>
|
||||
{flyerError && (
|
||||
<p className="text-xs text-destructive">{flyerError}</p>
|
||||
)}
|
||||
{/* QR download buttons */}
|
||||
<div className="flex gap-2 sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleDownload('png')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadPng')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDownload('svg')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadSvg')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Download } from 'lucide-react';
|
||||
|
||||
export type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
|
||||
export type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
|
||||
export type CornerDotStyle = 'square' | 'dot';
|
||||
export type LogoOption = 'none' | 'nomad' | 'emoji';
|
||||
|
||||
export interface QRStylePrefs {
|
||||
dotStyle: DotStyle;
|
||||
cornerSquareStyle: CornerSquareStyle;
|
||||
cornerDotStyle: CornerDotStyle;
|
||||
fgColor: string;
|
||||
bgColor: string;
|
||||
logo: LogoOption;
|
||||
logoEmoji: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_QR_PREFS: QRStylePrefs = {
|
||||
dotStyle: 'square',
|
||||
cornerSquareStyle: 'square',
|
||||
cornerDotStyle: 'square',
|
||||
fgColor: '#000000',
|
||||
bgColor: '#ffffff',
|
||||
logo: 'none',
|
||||
logoEmoji: '🎤',
|
||||
};
|
||||
|
||||
const QR_STORAGE_KEY = 'nk-qr-style-prefs';
|
||||
|
||||
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
|
||||
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
|
||||
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
|
||||
|
||||
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'rounded': 'qrStyleRounded',
|
||||
'dots': 'qrStyleDots',
|
||||
'classy': 'qrStyleClassy',
|
||||
'classy-rounded': 'qrStyleClassyRounded',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
};
|
||||
|
||||
export function loadQrPrefs(): QRStylePrefs {
|
||||
try {
|
||||
const saved = localStorage.getItem(QR_STORAGE_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_QR_PREFS, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_QR_PREFS };
|
||||
}
|
||||
|
||||
export function saveQrPrefs(prefs: QRStylePrefs): void {
|
||||
try {
|
||||
localStorage.setItem(QR_STORAGE_KEY, JSON.stringify(prefs));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function emojiToDataUrl(emoji: string): string {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 64;
|
||||
canvas.height = 64;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return '';
|
||||
ctx.font = '52px serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(emoji, 32, 36);
|
||||
return canvas.toDataURL('image/png');
|
||||
}
|
||||
|
||||
interface QRCodeTabProps {
|
||||
referralUrl: string;
|
||||
prefs: QRStylePrefs;
|
||||
onPrefsChange: (prefs: QRStylePrefs) => void;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export default function QRCodeTab({ referralUrl, prefs, onPrefsChange, visible }: QRCodeTabProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const buildOptions = useCallback((p: QRStylePrefs) => {
|
||||
let image: string | undefined;
|
||||
if (p.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (p.logo === 'emoji' && p.logoEmoji) {
|
||||
image = emojiToDataUrl(p.logoEmoji);
|
||||
}
|
||||
return {
|
||||
width: 250,
|
||||
height: 250,
|
||||
data: referralUrl,
|
||||
dotsOptions: { type: p.dotStyle, color: p.fgColor },
|
||||
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
|
||||
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
|
||||
backgroundOptions: { color: p.bgColor },
|
||||
image,
|
||||
imageOptions: { hideBackgroundDots: true, imageSize: 0.2, margin: 4 },
|
||||
};
|
||||
}, [referralUrl]);
|
||||
|
||||
// Initialize / update QR code
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
let cancelled = false;
|
||||
const init = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
if (cancelled) return;
|
||||
if (!qrRef.current) {
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
if (!cancelled && containerRef.current) {
|
||||
containerRef.current.innerHTML = '';
|
||||
qrRef.current.append(containerRef.current);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
qrRef.current.update(buildOptions(prefs));
|
||||
}
|
||||
if (!cancelled) setLoaded(true);
|
||||
};
|
||||
init();
|
||||
return () => { cancelled = true; };
|
||||
}, [visible, prefs, buildOptions]);
|
||||
|
||||
// Clean up on hide
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
qrRef.current = null;
|
||||
setLoaded(false);
|
||||
}
|
||||
}, [visible]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, []);
|
||||
|
||||
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
|
||||
const next = { ...prefs, [key]: value };
|
||||
onPrefsChange(next);
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => saveQrPrefs(next), 300);
|
||||
};
|
||||
|
||||
const handleDownload = async (extension: 'png' | 'svg') => {
|
||||
if (!qrRef.current) {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
}
|
||||
await qrRef.current.download({ name: 'referral-qr', extension });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: QR Preview */}
|
||||
<div className="flex-shrink-0 flex items-center justify-center">
|
||||
<div
|
||||
className="relative w-[250px] h-[250px] rounded-lg border border-border"
|
||||
style={{ backgroundColor: prefs.bgColor }}
|
||||
>
|
||||
<div ref={containerRef} className="w-full h-full" />
|
||||
{!loaded && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<div className="flex-1 space-y-4 min-w-0">
|
||||
{/* Dot Style */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('dotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.dotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(DOT_STYLE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Frame */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_SQUARE_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerSquareStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerSquareStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_SQUARE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Dot */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerDotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerDotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_DOT_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
|
||||
<div className="flex gap-4 mt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.fgColor}
|
||||
onChange={(e) => updatePref('fgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.bgColor}
|
||||
onChange={(e) => updatePref('bgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center Logo */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
{(['none', 'nomad', 'emoji'] as const).map(option => {
|
||||
const labelKeys = { none: 'qrLogoNone', nomad: 'qrLogoNomad', emoji: 'qrLogoEmoji' } as const;
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
onClick={() => updatePref('logo', option)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.logo === option
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(labelKeys[option])}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{prefs.logo === 'emoji' && (
|
||||
<input
|
||||
type="text"
|
||||
value={prefs.logoEmoji}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
const emoji = [...val].pop() || '';
|
||||
updatePref('logoEmoji', emoji);
|
||||
}}
|
||||
className="w-10 h-7 text-center text-base rounded border border-border"
|
||||
maxLength={4}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* QR download buttons */}
|
||||
<div className="flex gap-2 pt-2 border-t border-border sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleDownload('png')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadPng')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDownload('svg')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadSvg')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
QrCode, Sparkles, ExternalLink, CheckCircle, AlertCircle,
|
||||
Loader2, Banknote, Settings,
|
||||
} from 'lucide-react';
|
||||
import QRCodeDialog from './QRCodeDialog';
|
||||
import ReferralToolsDialog from './ReferralToolsDialog';
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`;
|
||||
@@ -417,19 +417,21 @@ export default function ReferralDashboard() {
|
||||
|
||||
{/* Management buttons */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={handleManagePayouts}
|
||||
disabled={dashboardLinkLoading}
|
||||
className="px-3 py-1.5 rounded text-sm border flex items-center gap-1.5 hover:bg-white/5 transition-colors disabled:opacity-50"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
{dashboardLinkLoading ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{t('managePayouts')}
|
||||
</button>
|
||||
{connectAccount?.details_submitted && (
|
||||
<button
|
||||
onClick={handleManagePayouts}
|
||||
disabled={dashboardLinkLoading}
|
||||
className="px-3 py-1.5 rounded text-sm border flex items-center gap-1.5 hover:bg-white/5 transition-colors disabled:opacity-50"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
{dashboardLinkLoading ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{t('managePayouts')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleUpdateAccount}
|
||||
disabled={connectLoading}
|
||||
@@ -511,10 +513,12 @@ export default function ReferralDashboard() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<QRCodeDialog
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${data.link.code}`}
|
||||
open={qrOpen}
|
||||
onOpenChange={setQrOpen}
|
||||
referralCode={data.link.code}
|
||||
discountPercent={data.link.discount_percent}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { QrCode, FileText } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import QRCodeTab, { type QRStylePrefs, DEFAULT_QR_PREFS, loadQrPrefs } from './QRCodeTab';
|
||||
import FlyerTab from './FlyerTab';
|
||||
|
||||
interface ReferralToolsDialogProps {
|
||||
referralUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** @deprecated — flyer generation is now client-side. Kept for backwards compat. */
|
||||
onGenerateFlyer?: (theme: 'light' | 'dark', qrDataUrl: string) => Promise<Blob>;
|
||||
flyerFilename?: string;
|
||||
/** Referral code (for flyer CTA display). Extracted from referralUrl if not provided. */
|
||||
referralCode?: string;
|
||||
/** Discount percentage (for flyer CTA). Defaults to 20. */
|
||||
discountPercent?: number;
|
||||
}
|
||||
|
||||
export default function ReferralToolsDialog({
|
||||
referralUrl,
|
||||
open,
|
||||
onOpenChange,
|
||||
flyerFilename,
|
||||
referralCode: referralCodeProp,
|
||||
discountPercent = 20,
|
||||
}: ReferralToolsDialogProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const [activeTab, setActiveTab] = useState('qr');
|
||||
const [qrPrefs, setQrPrefs] = useState<QRStylePrefs>(DEFAULT_QR_PREFS);
|
||||
|
||||
// Extract referral code from URL if not provided, stripping query/hash/path
|
||||
const referralCode = referralCodeProp
|
||||
|| referralUrl.split('/r/').pop()?.split(/[?#/]/)[0]
|
||||
|| 'CODE';
|
||||
|
||||
// Load QR prefs on open
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setQrPrefs(loadQrPrefs());
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-4xl bg-card border-border max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<QrCode className="w-5 h-5" />
|
||||
{t('toolsTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="qr" className="flex items-center gap-1.5">
|
||||
<QrCode className="w-3.5 h-3.5" />
|
||||
{t('tabQrCode')}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="flyer" className="flex items-center gap-1.5">
|
||||
<FileText className="w-3.5 h-3.5" />
|
||||
{t('tabFlyer')}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="qr">
|
||||
<QRCodeTab
|
||||
referralUrl={referralUrl}
|
||||
prefs={qrPrefs}
|
||||
onPrefsChange={setQrPrefs}
|
||||
visible={activeTab === 'qr' && open}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="flyer">
|
||||
<FlyerTab
|
||||
referralCode={referralCode}
|
||||
discountPercent={discountPercent}
|
||||
qrPrefs={qrPrefs}
|
||||
onSwitchToQr={() => setActiveTab('qr')}
|
||||
flyerFilename={flyerFilename}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { exportFlyerPdf, exportFlyerHtml, exportFlyerPng } from '../FlyerExport';
|
||||
|
||||
// Mock html2canvas — factory must be self-contained (jest hoists it)
|
||||
jest.mock('html2canvas', () => {
|
||||
return jest.fn().mockResolvedValue({
|
||||
toDataURL: jest.fn().mockReturnValue('data:image/png;base64,fakepng'),
|
||||
toBlob: jest.fn((cb: (blob: Blob) => void) => cb(new Blob(['png'], { type: 'image/png' }))),
|
||||
width: 1632,
|
||||
height: 2112,
|
||||
});
|
||||
});
|
||||
|
||||
// Mock jsPDF
|
||||
const mockAddImage = jest.fn();
|
||||
const mockSave = jest.fn();
|
||||
jest.mock('jspdf', () => {
|
||||
// Must use require-style access for outer variables with jest.mock hoisting
|
||||
return function JsPDFMock() {
|
||||
return {
|
||||
addImage: (...args: unknown[]) => mockAddImage(...args),
|
||||
save: (...args: unknown[]) => mockSave(...args),
|
||||
addPage: jest.fn(),
|
||||
internal: { pageSize: { getWidth: () => 215.9, getHeight: () => 279.4 } },
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('FlyerExport', () => {
|
||||
const mockElement = document.createElement('div');
|
||||
mockElement.setAttribute('data-flyer-page', '');
|
||||
Object.defineProperty(mockElement, 'outerHTML', { value: '<div data-flyer-page="">test</div>' });
|
||||
|
||||
describe('exportFlyerPdf', () => {
|
||||
it('generates PDF with 1 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 1, marginMm: 15, filename: 'test.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(1);
|
||||
expect(mockSave).toHaveBeenCalledWith('test.pdf');
|
||||
});
|
||||
|
||||
it('generates PDF with 2 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 2, marginMm: 10, filename: 'test-2up.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(2);
|
||||
expect(mockSave).toHaveBeenCalledWith('test-2up.pdf');
|
||||
});
|
||||
|
||||
it('generates PDF with 4 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 4, marginMm: 5, filename: 'test-4up.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(4);
|
||||
expect(mockSave).toHaveBeenCalledWith('test-4up.pdf');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportFlyerHtml', () => {
|
||||
it('returns a blob containing the flyer HTML', () => {
|
||||
const blob = exportFlyerHtml(mockElement);
|
||||
expect(blob).toBeInstanceOf(Blob);
|
||||
expect(blob.type).toBe('text/html');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportFlyerPng', () => {
|
||||
it('calls html2canvas and triggers download', async () => {
|
||||
const mockUrl = 'blob:test-png';
|
||||
global.URL.createObjectURL = jest.fn().mockReturnValue(mockUrl);
|
||||
global.URL.revokeObjectURL = jest.fn();
|
||||
|
||||
const mockClick = jest.fn();
|
||||
const origCreateElement = document.createElement.bind(document);
|
||||
jest.spyOn(document, 'createElement').mockImplementation((tag: string) => {
|
||||
const el = origCreateElement(tag);
|
||||
if (tag === 'a') {
|
||||
el.click = mockClick;
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
await exportFlyerPng(mockElement, 'test.png');
|
||||
|
||||
const html2canvas = require('html2canvas');
|
||||
expect(html2canvas).toHaveBeenCalledWith(mockElement, expect.objectContaining({ scale: 2 }));
|
||||
expect(mockClick).toHaveBeenCalled();
|
||||
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,145 +0,0 @@
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import QRCodeDialog from '../QRCodeDialog';
|
||||
|
||||
// Mock qr-code-styling — it requires canvas/DOM APIs not available in jsdom
|
||||
const mockAppend = jest.fn();
|
||||
const mockUpdate = jest.fn();
|
||||
const mockDownload = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
jest.mock('qr-code-styling', () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
append: mockAppend,
|
||||
update: mockUpdate,
|
||||
download: mockDownload,
|
||||
}));
|
||||
});
|
||||
|
||||
// Load real English messages for the referrals namespace
|
||||
const messages = require('../../../messages/en.json');
|
||||
|
||||
function renderDialog(props: Partial<React.ComponentProps<typeof QRCodeDialog>> = {}) {
|
||||
return render(
|
||||
<NextIntlClientProvider locale="en" messages={messages}>
|
||||
<QRCodeDialog
|
||||
referralUrl="https://nomadkaraoke.com/r/testcode"
|
||||
open={true}
|
||||
onOpenChange={jest.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('QRCodeDialog', () => {
|
||||
it('renders the dialog title and download buttons when open', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('QR Code Generator')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download PNG')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download SVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
renderDialog({ open: false });
|
||||
expect(screen.queryByText('QR Code Generator')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all dot style options', () => {
|
||||
renderDialog();
|
||||
// "Square" appears multiple times (dot style, corner frame, corner dot) — use getAllByText
|
||||
expect(screen.getAllByText('Square').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('Rounded')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dots')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Extra Rounded').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders corner frame and corner dot style sections', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
|
||||
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders center logo options', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Center Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('None')).toBeInTheDocument();
|
||||
expect(screen.getByText('NK Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('Emoji')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders color picker inputs', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Foreground')).toBeInTheDocument();
|
||||
expect(screen.getByText('Background')).toBeInTheDocument();
|
||||
// Color inputs
|
||||
const colorInputs = screen.getAllByDisplayValue('#000000');
|
||||
expect(colorInputs.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('saves style prefs to localStorage on change', async () => {
|
||||
jest.useFakeTimers();
|
||||
renderDialog();
|
||||
// Click "Rounded" dot style
|
||||
fireEvent.click(screen.getByText('Rounded'));
|
||||
// Flush the debounce timer
|
||||
act(() => { jest.runAllTimers(); });
|
||||
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
|
||||
expect(saved.dotStyle).toBe('rounded');
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('restores style prefs from localStorage on open', () => {
|
||||
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
|
||||
dotStyle: 'dots',
|
||||
cornerSquareStyle: 'dot',
|
||||
cornerDotStyle: 'dot',
|
||||
fgColor: '#ff0000',
|
||||
bgColor: '#00ff00',
|
||||
logo: 'nomad',
|
||||
}));
|
||||
renderDialog();
|
||||
// The foreground color input should have the saved value
|
||||
const fgInput = screen.getByDisplayValue('#ff0000');
|
||||
expect(fgInput).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls download with PNG extension when Download PNG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download PNG'));
|
||||
await waitFor(() => {
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'png',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('calls download with SVG extension when Download SVG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download SVG'));
|
||||
await waitFor(() => {
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'svg',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('renders flyer generation controls', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Generate Flyer')).toBeInTheDocument();
|
||||
expect(screen.getByText('Light')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dark')).toBeInTheDocument();
|
||||
expect(screen.getByText('Flyer Theme')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import ReferralToolsDialog from '../ReferralToolsDialog';
|
||||
|
||||
// Mock qr-code-styling
|
||||
const mockAppend = jest.fn();
|
||||
const mockUpdate = jest.fn();
|
||||
const mockDownload = jest.fn().mockResolvedValue(undefined);
|
||||
const mockGetRawData = jest.fn().mockResolvedValue(new Blob(['fake'], { type: 'image/png' }));
|
||||
|
||||
jest.mock('qr-code-styling', () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
append: mockAppend,
|
||||
update: mockUpdate,
|
||||
download: mockDownload,
|
||||
getRawData: mockGetRawData,
|
||||
}));
|
||||
});
|
||||
|
||||
// Mock html2canvas
|
||||
jest.mock('html2canvas', () => {
|
||||
return jest.fn().mockResolvedValue({
|
||||
toDataURL: jest.fn().mockReturnValue('data:image/png;base64,fake'),
|
||||
toBlob: jest.fn((cb: (b: Blob) => void) => cb(new Blob(['png']))),
|
||||
width: 1632,
|
||||
height: 2112,
|
||||
});
|
||||
});
|
||||
|
||||
// Mock jsPDF
|
||||
jest.mock('jspdf', () => {
|
||||
return function JsPDFMock() {
|
||||
return {
|
||||
addImage: jest.fn(),
|
||||
save: jest.fn(),
|
||||
addPage: jest.fn(),
|
||||
internal: { pageSize: { getWidth: () => 215.9, getHeight: () => 279.4 } },
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
const messages = require('../../../messages/en.json');
|
||||
|
||||
function renderDialog(props: Partial<React.ComponentProps<typeof ReferralToolsDialog>> = {}) {
|
||||
return render(
|
||||
<NextIntlClientProvider locale="en" messages={messages}>
|
||||
<ReferralToolsDialog
|
||||
referralUrl="https://nomadkaraoke.com/r/testcode"
|
||||
open={true}
|
||||
onOpenChange={jest.fn()}
|
||||
referralCode="testcode"
|
||||
discountPercent={20}
|
||||
{...props}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('ReferralToolsDialog', () => {
|
||||
it('renders with tabs for QR Code and Flyer', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('QR Code & Flyer Generator')).toBeInTheDocument();
|
||||
expect(screen.getByText('QR Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('Printable Flyer')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
renderDialog({ open: false });
|
||||
expect(screen.queryByText('QR Code & Flyer Generator')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows QR Code tab content by default', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Dot Style')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download PNG')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download SVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all QR dot style options on QR tab', () => {
|
||||
renderDialog();
|
||||
expect(screen.getAllByText('Square').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('Rounded')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dots')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Extra Rounded').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders corner frame and corner dot style sections', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
|
||||
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders center logo options', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Center Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('None')).toBeInTheDocument();
|
||||
expect(screen.getByText('NK Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('Emoji')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves QR style prefs to localStorage on change', async () => {
|
||||
jest.useFakeTimers();
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByText('Rounded'));
|
||||
act(() => { jest.runAllTimers(); });
|
||||
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
|
||||
expect(saved.dotStyle).toBe('rounded');
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('restores QR style prefs from localStorage on open', () => {
|
||||
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
|
||||
dotStyle: 'dots',
|
||||
cornerSquareStyle: 'dot',
|
||||
cornerDotStyle: 'dot',
|
||||
fgColor: '#ff0000',
|
||||
bgColor: '#00ff00',
|
||||
logo: 'nomad',
|
||||
logoEmoji: '🎤',
|
||||
}));
|
||||
renderDialog();
|
||||
const fgInput = screen.getByDisplayValue('#ff0000');
|
||||
expect(fgInput).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches to Flyer tab when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Download PDF')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download HTML')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders flyer controls on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Colors')).toBeInTheDocument();
|
||||
expect(screen.getByText('Sections')).toBeInTheDocument();
|
||||
expect(screen.getByText('Print Layout')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows flyer per-page options on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Flyers Per Page')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '2' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '4' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders section visibility toggles on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Subtitle')).toBeInTheDocument();
|
||||
expect(screen.getByText('How It Works Steps')).toBeInTheDocument();
|
||||
expect(screen.getByText('Divider')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bottom Features')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bottom Tagline')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows Edit QR Style link on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Edit QR Style')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls download with PNG extension when Download PNG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download PNG'));
|
||||
// QR download should be triggered
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'png',
|
||||
});
|
||||
});
|
||||
|
||||
it('calls download with SVG extension when Download SVG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download SVG'));
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'svg',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import {
|
||||
type FlyerConfig,
|
||||
DEFAULT_FLYER_CONFIG,
|
||||
LIGHT_PRESET,
|
||||
DARK_PRESET,
|
||||
BUILT_IN_PRESETS,
|
||||
loadFlyerConfig,
|
||||
saveFlyerConfig,
|
||||
loadCustomPresets,
|
||||
saveCustomPreset,
|
||||
deleteCustomPreset,
|
||||
} from '../flyer-presets';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('flyer-presets', () => {
|
||||
describe('DEFAULT_FLYER_CONFIG', () => {
|
||||
it('has all required fields with sensible defaults', () => {
|
||||
expect(DEFAULT_FLYER_CONFIG.bgColor).toBe('#faf8f5');
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineGradient).toEqual(['#c45aff', '#ff7acc', '#ff5a8a']);
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineSubColor).toBe('#1a1a1a');
|
||||
expect(DEFAULT_FLYER_CONFIG.textColor).toBe('#1a1a1a');
|
||||
expect(DEFAULT_FLYER_CONFIG.subtextColor).toBe('#666666');
|
||||
expect(DEFAULT_FLYER_CONFIG.accentColor).toBe('#c45aff');
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineMain).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineSub).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.subtitle).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.ctaLabel).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.ctaNote).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.steps).toHaveLength(4);
|
||||
expect(DEFAULT_FLYER_CONFIG.steps[0]).toEqual({ title: null, desc: null });
|
||||
expect(DEFAULT_FLYER_CONFIG.showSubtitle).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showSteps).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showDivider).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showBottomFeatures).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showBottomTagline).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.customLogoUrl).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.perPage).toBe(1);
|
||||
expect(DEFAULT_FLYER_CONFIG.marginMm).toBe(15);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BUILT_IN_PRESETS', () => {
|
||||
it('has Light and Dark presets', () => {
|
||||
expect(BUILT_IN_PRESETS).toHaveLength(2);
|
||||
expect(BUILT_IN_PRESETS[0].name).toBe('Light');
|
||||
expect(BUILT_IN_PRESETS[1].name).toBe('Dark');
|
||||
});
|
||||
|
||||
it('Light preset matches default config colors', () => {
|
||||
expect(LIGHT_PRESET.bgColor).toBe('#faf8f5');
|
||||
expect(LIGHT_PRESET.textColor).toBe('#1a1a1a');
|
||||
});
|
||||
|
||||
it('Dark preset has dark background and light text', () => {
|
||||
expect(DARK_PRESET.bgColor).toBe('#0c0a1a');
|
||||
expect(DARK_PRESET.textColor).toBe('#ffffff');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFlyerConfig / saveFlyerConfig', () => {
|
||||
it('returns default config when nothing saved', () => {
|
||||
const config = loadFlyerConfig();
|
||||
expect(config).toEqual(DEFAULT_FLYER_CONFIG);
|
||||
});
|
||||
|
||||
it('round-trips a config through save and load', () => {
|
||||
const custom: FlyerConfig = {
|
||||
...DEFAULT_FLYER_CONFIG,
|
||||
bgColor: '#ffffff',
|
||||
perPage: 2,
|
||||
marginMm: 5,
|
||||
};
|
||||
saveFlyerConfig(custom);
|
||||
expect(loadFlyerConfig()).toEqual(custom);
|
||||
});
|
||||
|
||||
it('merges partial saved data with defaults', () => {
|
||||
localStorage.setItem('nk-flyer-prefs', JSON.stringify({ bgColor: '#ff0000' }));
|
||||
const config = loadFlyerConfig();
|
||||
expect(config.bgColor).toBe('#ff0000');
|
||||
expect(config.textColor).toBe('#1a1a1a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom presets', () => {
|
||||
it('returns empty array when no custom presets saved', () => {
|
||||
expect(loadCustomPresets()).toEqual([]);
|
||||
});
|
||||
|
||||
it('saves and loads a custom preset', () => {
|
||||
const config: FlyerConfig = { ...DEFAULT_FLYER_CONFIG, bgColor: '#ff0000' };
|
||||
saveCustomPreset('My Red Theme', config);
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].name).toBe('My Red Theme');
|
||||
expect(presets[0].config.bgColor).toBe('#ff0000');
|
||||
});
|
||||
|
||||
it('overwrites preset with same name', () => {
|
||||
saveCustomPreset('Theme A', { ...DEFAULT_FLYER_CONFIG, bgColor: '#111111' });
|
||||
saveCustomPreset('Theme A', { ...DEFAULT_FLYER_CONFIG, bgColor: '#222222' });
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].config.bgColor).toBe('#222222');
|
||||
});
|
||||
|
||||
it('deletes a custom preset by name', () => {
|
||||
saveCustomPreset('To Delete', DEFAULT_FLYER_CONFIG);
|
||||
saveCustomPreset('To Keep', DEFAULT_FLYER_CONFIG);
|
||||
deleteCustomPreset('To Delete');
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].name).toBe('To Keep');
|
||||
});
|
||||
|
||||
it('no-ops when deleting non-existent preset', () => {
|
||||
saveCustomPreset('Exists', DEFAULT_FLYER_CONFIG);
|
||||
deleteCustomPreset('Does Not Exist');
|
||||
expect(loadCustomPresets()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
export interface FlyerConfig {
|
||||
// Colors
|
||||
bgColor: string;
|
||||
headlineGradient: string[];
|
||||
headlineSubColor: string;
|
||||
textColor: string;
|
||||
subtextColor: string;
|
||||
accentColor: string;
|
||||
|
||||
// Text overrides (null = use default)
|
||||
headlineMain: string | null;
|
||||
headlineSub: string | null;
|
||||
subtitle: string | null;
|
||||
ctaLabel: string | null;
|
||||
ctaNote: string | null;
|
||||
steps: Array<{ title: string | null; desc: string | null }>;
|
||||
|
||||
// Section visibility
|
||||
showSubtitle: boolean;
|
||||
showSteps: boolean;
|
||||
showDivider: boolean;
|
||||
showBottomFeatures: boolean;
|
||||
showBottomTagline: boolean;
|
||||
|
||||
// Custom branding
|
||||
customLogoUrl: string | null;
|
||||
|
||||
// Print layout
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number;
|
||||
}
|
||||
|
||||
export interface NamedPreset {
|
||||
name: string;
|
||||
config: FlyerConfig;
|
||||
}
|
||||
|
||||
const FLYER_CONFIG_KEY = 'nk-flyer-prefs';
|
||||
const CUSTOM_PRESETS_KEY = 'nk-flyer-custom-presets';
|
||||
|
||||
const DEFAULT_STEPS: Array<{ title: string | null; desc: string | null }> = [
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
];
|
||||
|
||||
export const LIGHT_PRESET: FlyerConfig = {
|
||||
bgColor: '#faf8f5',
|
||||
headlineGradient: ['#c45aff', '#ff7acc', '#ff5a8a'],
|
||||
headlineSubColor: '#1a1a1a',
|
||||
textColor: '#1a1a1a',
|
||||
subtextColor: '#666666',
|
||||
accentColor: '#c45aff',
|
||||
headlineMain: null,
|
||||
headlineSub: null,
|
||||
subtitle: null,
|
||||
ctaLabel: null,
|
||||
ctaNote: null,
|
||||
steps: [...DEFAULT_STEPS],
|
||||
showSubtitle: true,
|
||||
showSteps: true,
|
||||
showDivider: true,
|
||||
showBottomFeatures: true,
|
||||
showBottomTagline: true,
|
||||
customLogoUrl: null,
|
||||
perPage: 1,
|
||||
marginMm: 15,
|
||||
};
|
||||
|
||||
export const DARK_PRESET: FlyerConfig = {
|
||||
bgColor: '#0c0a1a',
|
||||
headlineGradient: ['#ffd86b', '#ff7acc', '#c45aff'],
|
||||
headlineSubColor: '#ffffff',
|
||||
textColor: '#ffffff',
|
||||
subtextColor: 'rgba(255, 255, 255, 0.6)',
|
||||
accentColor: '#c45aff',
|
||||
headlineMain: null,
|
||||
headlineSub: null,
|
||||
subtitle: null,
|
||||
ctaLabel: null,
|
||||
ctaNote: null,
|
||||
steps: [...DEFAULT_STEPS],
|
||||
showSubtitle: true,
|
||||
showSteps: true,
|
||||
showDivider: true,
|
||||
showBottomFeatures: true,
|
||||
showBottomTagline: true,
|
||||
customLogoUrl: null,
|
||||
perPage: 1,
|
||||
marginMm: 15,
|
||||
};
|
||||
|
||||
export const DEFAULT_FLYER_CONFIG: FlyerConfig = { ...LIGHT_PRESET };
|
||||
|
||||
export const BUILT_IN_PRESETS: NamedPreset[] = [
|
||||
{ name: 'Light', config: LIGHT_PRESET },
|
||||
{ name: 'Dark', config: DARK_PRESET },
|
||||
];
|
||||
|
||||
const isBrowser = typeof window !== 'undefined';
|
||||
|
||||
export function loadFlyerConfig(): FlyerConfig {
|
||||
if (!isBrowser) return { ...DEFAULT_FLYER_CONFIG };
|
||||
try {
|
||||
const saved = localStorage.getItem(FLYER_CONFIG_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_FLYER_CONFIG, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_FLYER_CONFIG };
|
||||
}
|
||||
|
||||
export function saveFlyerConfig(config: FlyerConfig): void {
|
||||
if (!isBrowser) return;
|
||||
try {
|
||||
localStorage.setItem(FLYER_CONFIG_KEY, JSON.stringify(config));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadCustomPresets(): NamedPreset[] {
|
||||
if (!isBrowser) return [];
|
||||
try {
|
||||
const saved = localStorage.getItem(CUSTOM_PRESETS_KEY);
|
||||
if (saved) {
|
||||
return JSON.parse(saved);
|
||||
}
|
||||
} catch {}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function saveCustomPreset(name: string, config: FlyerConfig): void {
|
||||
if (!isBrowser) return;
|
||||
const presets = loadCustomPresets();
|
||||
const idx = presets.findIndex(p => p.name === name);
|
||||
if (idx >= 0) {
|
||||
presets[idx] = { name, config };
|
||||
} else {
|
||||
presets.push({ name, config });
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(CUSTOM_PRESETS_KEY, JSON.stringify(presets));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function deleteCustomPreset(name: string): void {
|
||||
if (!isBrowser) return;
|
||||
const presets = loadCustomPresets().filter(p => p.name !== name);
|
||||
try {
|
||||
localStorage.setItem(CUSTOM_PRESETS_KEY, JSON.stringify(presets));
|
||||
} catch {}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Tests for auth store's fetchUser() behavior, specifically:
|
||||
* - Abort errors (from page navigation) should NOT clear auth
|
||||
* - Other errors (expired session) SHOULD clear auth
|
||||
* - 401 errors (expired session) SHOULD clear auth
|
||||
* - Network errors (fetch failures) should NOT clear auth
|
||||
*/
|
||||
|
||||
// Mock api module before importing auth
|
||||
@@ -50,18 +51,31 @@ describe('fetchUser', () => {
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('clears auth state when API returns a non-abort error (expired session)', async () => {
|
||||
mockGetCurrentUser.mockRejectedValueOnce(new Error('Unauthorized'))
|
||||
it('clears auth state when API returns 401 (expired session)', async () => {
|
||||
const err = new Error('Unauthorized') as Error & { status: number }
|
||||
err.status = 401
|
||||
mockGetCurrentUser.mockRejectedValueOnce(err)
|
||||
|
||||
const result = await useAuth.getState().fetchUser()
|
||||
|
||||
expect(result).toBe(false)
|
||||
// Auth SHOULD be cleared
|
||||
// Auth SHOULD be cleared on explicit 401
|
||||
expect(clearAccessToken).toHaveBeenCalled()
|
||||
expect(useAuth.getState().user).toBeNull()
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves auth state on network errors (non-401)', async () => {
|
||||
mockGetCurrentUser.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
|
||||
const result = await useAuth.getState().fetchUser()
|
||||
|
||||
expect(result).toBe(false)
|
||||
// Auth should NOT be cleared on network errors
|
||||
expect(clearAccessToken).not.toHaveBeenCalled()
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('sets user on successful fetch', async () => {
|
||||
mockGetCurrentUser.mockResolvedValueOnce({
|
||||
user: {
|
||||
|
||||
@@ -152,9 +152,14 @@ export const useAuth = create<AuthStore>()(
|
||||
set({ isLoading: false })
|
||||
return false
|
||||
}
|
||||
// Session may have expired
|
||||
clearAccessToken()
|
||||
set({ user: null, isLoading: false })
|
||||
// Only clear token on explicit 401 (session expired/invalid)
|
||||
// Network errors, timeouts, cold-start delays, etc. should not log the user out
|
||||
if (err && typeof err === 'object' && 'status' in err && (err as any).status === 401) {
|
||||
clearAccessToken()
|
||||
set({ user: null, isLoading: false })
|
||||
} else {
|
||||
set({ isLoading: false })
|
||||
}
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,6 +30,7 @@ export const HIGHLIGHT_CLASSES = {
|
||||
uncorrectedGap: 'bg-orange-500/25',
|
||||
highlighted: 'bg-amber-400/40',
|
||||
playing: 'text-blue-500',
|
||||
userEdited: 'bg-lime-400/40',
|
||||
} as const
|
||||
|
||||
// CSS keyframes for flash animation (use with Tailwind animate utilities)
|
||||
|
||||
@@ -337,6 +337,7 @@ export interface WordProps {
|
||||
isUncorrectedGap?: boolean
|
||||
isCurrentlyPlaying?: boolean
|
||||
isActiveGap?: boolean
|
||||
isUserEdited?: boolean
|
||||
padding?: string
|
||||
onClick?: () => void
|
||||
id?: string
|
||||
@@ -381,6 +382,7 @@ export interface TranscriptionViewProps {
|
||||
onShowCorrectionDetail?: (wordId: string) => void
|
||||
advancedMode?: boolean
|
||||
onAdvancedModeToggle?: (enabled: boolean) => void
|
||||
editedWordIds?: Set<string>
|
||||
}
|
||||
|
||||
export interface ReferenceViewProps extends BaseViewProps {
|
||||
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "يُطبق تلقائياً عند الدفع",
|
||||
"expires": "ينتهي في {date}",
|
||||
"referredBy": "بإحالة من {name}",
|
||||
"usingCode": "الرمز: {code}"
|
||||
"usingCode": "الرمز: {code}",
|
||||
"connectBankLoading": "جاري الإعداد...",
|
||||
"connectDetailsNeeded": "تحتاج Stripe إلى معلومات إضافية لتمكين المدفوعات. انقر على \"تحديث الحساب البنكي\" أدناه لإكمال الإعداد.",
|
||||
"connectRefresh": "يبدو أنك لم تكمل إعداد حسابك البنكي. انقر أدناه للمحاولة مرة أخرى.",
|
||||
"connectStatusActive": "تم تمكين المدفوعات",
|
||||
"connectStatusPending": "الإعداد قيد التقدم",
|
||||
"connectStripeNote": "ستتم إعادة توجيهك إلى موقع Stripe الآمن لإدخال تفاصيل حسابك البنكي. يستغرق هذا عادةً بضع دقائق.",
|
||||
"flyerAccentColor": "لون التمييز",
|
||||
"flyerBranding": "العلامة التجارية",
|
||||
"flyerColors": "الألوان",
|
||||
"flyerDownloadHtml": "تنزيل HTML",
|
||||
"flyerDownloadPdf": "تنزيل PDF",
|
||||
"flyerDownloadPng": "تنزيل PNG",
|
||||
"flyerEditQr": "تعديل نمط QR",
|
||||
"flyerExporting": "جاري التصدير...",
|
||||
"flyerHeadlineGradient": "تدرج العنوان",
|
||||
"flyerHeadlineSubColor": "لون العنوان الفرعي",
|
||||
"flyerMargins": "هوامش الصفحة",
|
||||
"flyerPerPage": "عدد النشرات في الصفحة",
|
||||
"flyerPresetCustom": "مخصص",
|
||||
"flyerPresetName": "اسم الإعداد المسبق",
|
||||
"flyerPresetSave": "حفظ الإعداد المسبق",
|
||||
"flyerPrintLayout": "تخطيط الطباعة",
|
||||
"flyerSections": "الأقسام",
|
||||
"flyerSubtextColor": "النص الفرعي",
|
||||
"flyerTextColor": "النص",
|
||||
"flyerTextOverrides": "تعديلات النص",
|
||||
"flyerToggleDivider": "الفاصل",
|
||||
"flyerToggleFeatures": "الميزات السفلية",
|
||||
"flyerToggleSteps": "خطوات الاستخدام",
|
||||
"flyerToggleSubtitle": "العنوان الفرعي",
|
||||
"flyerToggleTagline": "العبارة الترويجية السفلية",
|
||||
"flyerUploadLogo": "رفع الشعار",
|
||||
"managePayouts": "إدارة المدفوعات",
|
||||
"payoutTitle": "المدفوعات والحساب البنكي",
|
||||
"tabFlyer": "نشرة إعلانية قابلة للطباعة",
|
||||
"tabQrCode": "رمز QR",
|
||||
"toolsTitle": "Generator رمز QR والنشرات الإعلانية",
|
||||
"updateBankAccount": "تحديث الحساب البنكي",
|
||||
"connectFailed": "حدث خطأ ما. يرجى المحاولة مرة أخرى.",
|
||||
"flyerRemoveLogo": "إزالة"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "S'aplica automàticament en finalitzar la compra",
|
||||
"expires": "Caduca el {date}",
|
||||
"referredBy": "Recomanat per {name}",
|
||||
"usingCode": "Codi: {code}"
|
||||
"usingCode": "Codi: {code}",
|
||||
"connectBankLoading": "Configurant...",
|
||||
"connectDetailsNeeded": "Stripe necessita informació addicional per activar els pagaments. Fes clic a \"Actualitza el compte bancari\" a continuació per completar la configuració.",
|
||||
"connectRefresh": "Sembla que no has acabat de configurar el teu compte bancari. Fes clic a continuació per tornar-ho a provar.",
|
||||
"connectStatusActive": "Pagaments activats",
|
||||
"connectStatusPending": "Configuració en curs",
|
||||
"connectStripeNote": "Se't redirigirà al lloc segur de Stripe per introduir les teves dades bancàries. Això sol trigar un parell de minuts.",
|
||||
"flyerAccentColor": "Color d'accent",
|
||||
"flyerBranding": "Marca",
|
||||
"flyerColors": "Colors",
|
||||
"flyerDownloadHtml": "Descarrega HTML",
|
||||
"flyerDownloadPdf": "Descarrega PDF",
|
||||
"flyerDownloadPng": "Descarrega PNG",
|
||||
"flyerEditQr": "Edita l'estil del QR",
|
||||
"flyerExporting": "Exportant...",
|
||||
"flyerHeadlineGradient": "Degradat del titular",
|
||||
"flyerHeadlineSubColor": "Subtitular",
|
||||
"flyerMargins": "Marges de la pàgina",
|
||||
"flyerPerPage": "Fullets per pàgina",
|
||||
"flyerPresetCustom": "Personalitzat",
|
||||
"flyerPresetName": "Nom del preajust",
|
||||
"flyerPresetSave": "Desa el preajust",
|
||||
"flyerPrintLayout": "Disposició d'impressió",
|
||||
"flyerSections": "Seccions",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Substitucions de text",
|
||||
"flyerToggleDivider": "Separador",
|
||||
"flyerToggleFeatures": "Característiques inferiors",
|
||||
"flyerToggleSteps": "Passos de com funciona",
|
||||
"flyerToggleSubtitle": "Subtítol",
|
||||
"flyerToggleTagline": "Eslògan inferior",
|
||||
"flyerUploadLogo": "Puja el logotip",
|
||||
"managePayouts": "Gestiona els pagaments",
|
||||
"payoutTitle": "Pagaments i compte bancari",
|
||||
"tabFlyer": "Fullet imprimible",
|
||||
"tabQrCode": "Codi QR",
|
||||
"toolsTitle": "Generator de codis QR i fullets",
|
||||
"updateBankAccount": "Actualitza el compte bancari",
|
||||
"connectFailed": "Alguna cosa ha anat malament. Torna-ho a provar.",
|
||||
"flyerRemoveLogo": "Elimina"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Automaticky uplatněno při platbě",
|
||||
"expires": "Platnost do {date}",
|
||||
"referredBy": "Doporučil/a {name}",
|
||||
"usingCode": "Kód: {code}"
|
||||
"usingCode": "Kód: {code}",
|
||||
"connectBankLoading": "Nastavování...",
|
||||
"connectDetailsNeeded": "Stripe potřebuje další informace k povolení výplat. Klikni níže na „Aktualizovat bankovní účet“ a dokonči nastavení.",
|
||||
"connectRefresh": "Vypadá to, že nemáš dokončené nastavení svého bankovního účtu. Klikni níže a zkus to znovu.",
|
||||
"connectStatusActive": "Výplaty povoleny",
|
||||
"connectStatusPending": "Probíhá nastavení",
|
||||
"connectStripeNote": "Přesměrujeme tě na zabezpečenou stránku Stripe, kde zadáš své bankovní údaje. Obvykle to trvá jen pár minut.",
|
||||
"flyerAccentColor": "Akcentní barva",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Barvy",
|
||||
"flyerDownloadHtml": "Stáhnout HTML",
|
||||
"flyerDownloadPdf": "Stáhnout PDF",
|
||||
"flyerDownloadPng": "Stáhnout PNG",
|
||||
"flyerEditQr": "Upravit styl QR",
|
||||
"flyerExporting": "Probíhá export...",
|
||||
"flyerHeadlineGradient": "Přechod nadpisu",
|
||||
"flyerHeadlineSubColor": "Podnadpis",
|
||||
"flyerMargins": "Okraje stránky",
|
||||
"flyerPerPage": "Letáků na stránku",
|
||||
"flyerPresetCustom": "Vlastní",
|
||||
"flyerPresetName": "Název předvolby",
|
||||
"flyerPresetSave": "Uložit předvolbu",
|
||||
"flyerPrintLayout": "Rozvržení tisku",
|
||||
"flyerSections": "Sekce",
|
||||
"flyerSubtextColor": "Podtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Vlastní texty",
|
||||
"flyerToggleDivider": "Oddělovač",
|
||||
"flyerToggleFeatures": "Funkce v dolní části",
|
||||
"flyerToggleSteps": "Kroky „Jak to funguje“",
|
||||
"flyerToggleSubtitle": "Podtitul",
|
||||
"flyerToggleTagline": "Spodní slogan",
|
||||
"flyerUploadLogo": "Nahrát logo",
|
||||
"managePayouts": "Spravovat výplaty",
|
||||
"payoutTitle": "Výplaty a bankovní účet",
|
||||
"tabFlyer": "Leták k tisku",
|
||||
"tabQrCode": "QR kód",
|
||||
"toolsTitle": "Generator QR kódů a letáků",
|
||||
"updateBankAccount": "Aktualizovat bankovní účet",
|
||||
"connectFailed": "Něco se pokazilo. Zkus to prosím znovu.",
|
||||
"flyerRemoveLogo": "Odstranit"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Anvendes automatisk ved kassen",
|
||||
"expires": "Udløber {date}",
|
||||
"referredBy": "Henvist af {name}",
|
||||
"usingCode": "Kode: {code}"
|
||||
"usingCode": "Kode: {code}",
|
||||
"connectBankLoading": "Gør klar...",
|
||||
"connectDetailsNeeded": "Stripe har brug for yderligere oplysninger for at aktivere udbetalinger. Klik på \"Opdater bankkonto\" nedenfor for at fuldføre opsætningen.",
|
||||
"connectRefresh": "Det ser ud til, at du ikke blev færdig med at opsætte din bankkonto. Klik nedenfor for at prøve igen.",
|
||||
"connectStatusActive": "Udbetalinger aktiveret",
|
||||
"connectStatusPending": "Opsætning i gang",
|
||||
"connectStripeNote": "Du vil blive viderestillet til Stripes sikre side for at indtaste dine bankoplysninger. Det tager normalt et par minutter.",
|
||||
"flyerAccentColor": "Accentfarve",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Farver",
|
||||
"flyerDownloadHtml": "Download HTML",
|
||||
"flyerDownloadPdf": "Download PDF",
|
||||
"flyerDownloadPng": "Download PNG",
|
||||
"flyerEditQr": "Rediger QR-stil",
|
||||
"flyerExporting": "Eksporterer...",
|
||||
"flyerHeadlineGradient": "Overskriftsgradient",
|
||||
"flyerHeadlineSubColor": "Underoverskrift",
|
||||
"flyerMargins": "Sidemargener",
|
||||
"flyerPerPage": "Flyers pr. side",
|
||||
"flyerPresetCustom": "Brugerdefineret",
|
||||
"flyerPresetName": "Navn på forudindstilling",
|
||||
"flyerPresetSave": "Gem forudindstilling",
|
||||
"flyerPrintLayout": "Udskriftslayout",
|
||||
"flyerSections": "Sektioner",
|
||||
"flyerSubtextColor": "Undertekst",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Tilpasning af tekst",
|
||||
"flyerToggleDivider": "Skillelinje",
|
||||
"flyerToggleFeatures": "Funktioner i bunden",
|
||||
"flyerToggleSteps": "Trin til 'Sådan fungerer det'",
|
||||
"flyerToggleSubtitle": "Undertitel",
|
||||
"flyerToggleTagline": "Slogan i bunden",
|
||||
"flyerUploadLogo": "Upload logo",
|
||||
"managePayouts": "Administrer udbetalinger",
|
||||
"payoutTitle": "Udbetalinger & bankkonto",
|
||||
"tabFlyer": "Udskriftsvenlig flyer",
|
||||
"tabQrCode": "QR-kode",
|
||||
"toolsTitle": "QR-kode & Flyer Generator",
|
||||
"updateBankAccount": "Opdater bankkonto",
|
||||
"connectFailed": "Noget gik galt. Prøv venligst igen.",
|
||||
"flyerRemoveLogo": "Fjern"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Wird an der Kasse automatisch angewendet",
|
||||
"expires": "Läuft am {date} ab",
|
||||
"referredBy": "Empfohlen von {name}",
|
||||
"usingCode": "Code: {code}"
|
||||
"usingCode": "Code: {code}",
|
||||
"connectBankLoading": "Wird eingerichtet...",
|
||||
"connectDetailsNeeded": "Stripe benötigt zusätzliche Informationen, um Auszahlungen zu aktivieren. Klicke unten auf \"Bankkonto aktualisieren\", um die Einrichtung abzuschließen.",
|
||||
"connectRefresh": "Es sieht so aus, als hättest du die Einrichtung deines Bankkontos nicht abgeschlossen. Klicke unten, um es erneut zu versuchen.",
|
||||
"connectStatusActive": "Auszahlungen aktiviert",
|
||||
"connectStatusPending": "Einrichtung läuft",
|
||||
"connectStripeNote": "Du wirst zur sicheren Website von Stripe weitergeleitet, um deine Bankdaten einzugeben. Dies dauert normalerweise ein paar Minuten.",
|
||||
"flyerAccentColor": "Akzentfarbe",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Farben",
|
||||
"flyerDownloadHtml": "HTML herunterladen",
|
||||
"flyerDownloadPdf": "PDF herunterladen",
|
||||
"flyerDownloadPng": "PNG herunterladen",
|
||||
"flyerEditQr": "QR-Stil bearbeiten",
|
||||
"flyerExporting": "Wird exportiert...",
|
||||
"flyerHeadlineGradient": "Überschrift-Farbverlauf",
|
||||
"flyerHeadlineSubColor": "Unterüberschrift",
|
||||
"flyerMargins": "Seitenränder",
|
||||
"flyerPerPage": "Flyer pro Seite",
|
||||
"flyerPresetCustom": "Benutzerdefiniert",
|
||||
"flyerPresetName": "Name der Voreinstellung",
|
||||
"flyerPresetSave": "Voreinstellung speichern",
|
||||
"flyerPrintLayout": "Drucklayout",
|
||||
"flyerSections": "Abschnitte",
|
||||
"flyerSubtextColor": "Untertext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Eigene Texte",
|
||||
"flyerToggleDivider": "Trennlinie",
|
||||
"flyerToggleFeatures": "Funktionen unten",
|
||||
"flyerToggleSteps": "Schritte 'So funktioniert's'",
|
||||
"flyerToggleSubtitle": "Untertitel",
|
||||
"flyerToggleTagline": "Slogan unten",
|
||||
"flyerUploadLogo": "Logo hochladen",
|
||||
"managePayouts": "Auszahlungen verwalten",
|
||||
"payoutTitle": "Auszahlungen & Bankkonto",
|
||||
"tabFlyer": "Druckbarer Flyer",
|
||||
"tabQrCode": "QR-Code",
|
||||
"toolsTitle": "QR-Code- & Flyer-Generator",
|
||||
"updateBankAccount": "Bankkonto aktualisieren",
|
||||
"connectFailed": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
|
||||
"flyerRemoveLogo": "Entfernen"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Εφαρμόζεται αυτόματα κατά την ολοκλήρωση της αγοράς",
|
||||
"expires": "Λήγει στις {date}",
|
||||
"referredBy": "Σύσταση από {name}",
|
||||
"usingCode": "Κωδικός: {code}"
|
||||
"usingCode": "Κωδικός: {code}",
|
||||
"connectBankLoading": "Ρύθμιση...",
|
||||
"connectDetailsNeeded": "Η Stripe χρειάζεται πρόσθετες πληροφορίες για να ενεργοποιήσει τις πληρωμές. Κάνε κλικ στο \"Ενημέρωση Τραπεζικού Λογαριασμού\" παρακάτω για να ολοκληρώσεις τη ρύθμιση.",
|
||||
"connectRefresh": "Φαίνεται ότι δεν ολοκλήρωσες τη ρύθμιση του τραπεζικού σου λογαριασμού. Κάνε κλικ παρακάτω για να δοκιμάσεις ξανά.",
|
||||
"connectStatusActive": "Οι πληρωμές ενεργοποιήθηκαν",
|
||||
"connectStatusPending": "Η ρύθμιση είναι σε εξέλιξη",
|
||||
"connectStripeNote": "Θα ανακατευθυνθείς στον ασφαλή ιστότοπο της Stripe για να εισαγάγεις τα τραπεζικά σου στοιχεία. Αυτό συνήθως διαρκεί μερικά λεπτά.",
|
||||
"flyerAccentColor": "Έμφαση",
|
||||
"flyerBranding": "Επωνυμία",
|
||||
"flyerColors": "Χρώματα",
|
||||
"flyerDownloadHtml": "Λήψη HTML",
|
||||
"flyerDownloadPdf": "Λήψη PDF",
|
||||
"flyerDownloadPng": "Λήψη PNG",
|
||||
"flyerEditQr": "Επεξεργασία Στυλ QR",
|
||||
"flyerExporting": "Εξαγωγή...",
|
||||
"flyerHeadlineGradient": "Ντεγκραντέ Επικεφαλίδας",
|
||||
"flyerHeadlineSubColor": "Δευτερεύουσα Επικεφαλίδα",
|
||||
"flyerMargins": "Περιθώρια Σελίδας",
|
||||
"flyerPerPage": "Φυλλάδια Ανά Σελίδα",
|
||||
"flyerPresetCustom": "Προσαρμοσμένο",
|
||||
"flyerPresetName": "Όνομα προεπιλογής",
|
||||
"flyerPresetSave": "Αποθήκευση Προεπιλογής",
|
||||
"flyerPrintLayout": "Διάταξη Εκτύπωσης",
|
||||
"flyerSections": "Ενότητες",
|
||||
"flyerSubtextColor": "Δευτερεύον κείμενο",
|
||||
"flyerTextColor": "Κείμενο",
|
||||
"flyerTextOverrides": "Παρακάμψεις Κειμένου",
|
||||
"flyerToggleDivider": "Διαχωριστικό",
|
||||
"flyerToggleFeatures": "Χαρακτηριστικά στο κάτω μέρος",
|
||||
"flyerToggleSteps": "Βήματα «Πώς λειτουργεί»",
|
||||
"flyerToggleSubtitle": "Υπότιτλος",
|
||||
"flyerToggleTagline": "Σλόγκαν στο κάτω μέρος",
|
||||
"flyerUploadLogo": "Μεταφόρτωση Λογότυπου",
|
||||
"managePayouts": "Διαχείριση Πληρωμών",
|
||||
"payoutTitle": "Πληρωμές & Τραπεζικός Λογαριασμός",
|
||||
"tabFlyer": "Εκτυπώσιμο Φυλλάδιο",
|
||||
"tabQrCode": "Κωδικός QR",
|
||||
"toolsTitle": "Generator Κωδικού QR & Φυλλαδίου",
|
||||
"updateBankAccount": "Ενημέρωση Τραπεζικού Λογαριασμού",
|
||||
"connectFailed": "Κάτι πήγε στραβά. Παρακαλώ δοκίμασε ξανά.",
|
||||
"flyerRemoveLogo": "Αφαίρεση"
|
||||
}
|
||||
}
|
||||
@@ -1318,6 +1318,36 @@
|
||||
"flyerThemeLight": "Light",
|
||||
"flyerThemeDark": "Dark",
|
||||
"flyerGenerate": "Generate Flyer",
|
||||
"flyerGenerating": "Generating..."
|
||||
"flyerGenerating": "Generating...",
|
||||
"toolsTitle": "QR Code & Flyer Generator",
|
||||
"tabQrCode": "QR Code",
|
||||
"tabFlyer": "Printable Flyer",
|
||||
"flyerPresetCustom": "Custom",
|
||||
"flyerPresetName": "Preset name",
|
||||
"flyerPresetSave": "Save Preset",
|
||||
"flyerColors": "Colors",
|
||||
"flyerHeadlineGradient": "Headline Gradient",
|
||||
"flyerHeadlineSubColor": "Headline Sub",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerTextOverrides": "Text Overrides",
|
||||
"flyerSections": "Sections",
|
||||
"flyerToggleSubtitle": "Subtitle",
|
||||
"flyerToggleSteps": "How It Works Steps",
|
||||
"flyerToggleDivider": "Divider",
|
||||
"flyerToggleFeatures": "Bottom Features",
|
||||
"flyerToggleTagline": "Bottom Tagline",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerUploadLogo": "Upload Logo",
|
||||
"flyerRemoveLogo": "Remove",
|
||||
"flyerPrintLayout": "Print Layout",
|
||||
"flyerPerPage": "Flyers Per Page",
|
||||
"flyerMargins": "Page Margins",
|
||||
"flyerEditQr": "Edit QR Style",
|
||||
"flyerDownloadPdf": "Download PDF",
|
||||
"flyerDownloadHtml": "Download HTML",
|
||||
"flyerDownloadPng": "Download PNG",
|
||||
"flyerExporting": "Exporting..."
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Aplicado automáticamente al finalizar la compra",
|
||||
"expires": "Expira {date}",
|
||||
"referredBy": "Referido por {name}",
|
||||
"usingCode": "Código: {code}"
|
||||
"usingCode": "Código: {code}",
|
||||
"connectBankLoading": "Configurando...",
|
||||
"connectDetailsNeeded": "Stripe necesita información adicional para habilitar los pagos. Haz clic en \"Actualizar cuenta bancaria\" a continuación para completar la configuración.",
|
||||
"connectRefresh": "Parece que no terminaste de configurar tu cuenta bancaria. Haz clic abajo para intentarlo de nuevo.",
|
||||
"connectStatusActive": "Pagos habilitados",
|
||||
"connectStatusPending": "Configuración en curso",
|
||||
"connectStripeNote": "Serás redirigido al sitio seguro de Stripe para ingresar tus datos bancarios. Esto generalmente toma un par de minutos.",
|
||||
"flyerAccentColor": "Acento",
|
||||
"flyerBranding": "Marca",
|
||||
"flyerColors": "Colores",
|
||||
"flyerDownloadHtml": "Descargar HTML",
|
||||
"flyerDownloadPdf": "Descargar PDF",
|
||||
"flyerDownloadPng": "Descargar PNG",
|
||||
"flyerEditQr": "Editar estilo del QR",
|
||||
"flyerExporting": "Exportando...",
|
||||
"flyerHeadlineGradient": "Degradado del titular",
|
||||
"flyerHeadlineSubColor": "Subtítulo del titular",
|
||||
"flyerMargins": "Márgenes de página",
|
||||
"flyerPerPage": "Folletos por página",
|
||||
"flyerPresetCustom": "Personalizado",
|
||||
"flyerPresetName": "Nombre del preset",
|
||||
"flyerPresetSave": "Guardar preset",
|
||||
"flyerPrintLayout": "Diseño de impresión",
|
||||
"flyerSections": "Secciones",
|
||||
"flyerSubtextColor": "Subtexto",
|
||||
"flyerTextColor": "Texto",
|
||||
"flyerTextOverrides": "Modificaciones de texto",
|
||||
"flyerToggleDivider": "Separador",
|
||||
"flyerToggleFeatures": "Características inferiores",
|
||||
"flyerToggleSteps": "Pasos de 'Cómo funciona'",
|
||||
"flyerToggleSubtitle": "Subtítulo",
|
||||
"flyerToggleTagline": "Eslogan inferior",
|
||||
"flyerUploadLogo": "Subir logo",
|
||||
"managePayouts": "Gestionar pagos",
|
||||
"payoutTitle": "Pagos y cuenta bancaria",
|
||||
"tabFlyer": "Folleto imprimible",
|
||||
"tabQrCode": "Código QR",
|
||||
"toolsTitle": "Generator de código QR y folletos",
|
||||
"updateBankAccount": "Actualizar cuenta bancaria",
|
||||
"connectFailed": "Algo salió mal. Por favor, inténtalo de nuevo.",
|
||||
"flyerRemoveLogo": "Quitar"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Lisätään automaattisesti kassalla",
|
||||
"expires": "Vanhenee {date}",
|
||||
"referredBy": "Suosittelija: {name}",
|
||||
"usingCode": "Koodi: {code}"
|
||||
"usingCode": "Koodi: {code}",
|
||||
"connectBankLoading": "Määritetään...",
|
||||
"connectDetailsNeeded": "Stripe tarvitsee lisätietoja tilitysten aktivoimiseksi. Klikkaa alta \"Päivitä pankkitili\" viimeistelläksesi asetukset.",
|
||||
"connectRefresh": "Näyttää siltä, että pankkitilisi asetukset jäivät kesken. Klikkaa alta yrittääksesi uudelleen.",
|
||||
"connectStatusActive": "Tilitykset käytössä",
|
||||
"connectStatusPending": "Asetukset kesken",
|
||||
"connectStripeNote": "Sinut ohjataan Stripen turvalliselle sivustolle syöttämään pankkitietosi. Tämä kestää yleensä pari minuuttia.",
|
||||
"flyerAccentColor": "Korostusväri",
|
||||
"flyerBranding": "Brändäys",
|
||||
"flyerColors": "Värit",
|
||||
"flyerDownloadHtml": "Lataa HTML",
|
||||
"flyerDownloadPdf": "Lataa PDF",
|
||||
"flyerDownloadPng": "Lataa PNG",
|
||||
"flyerEditQr": "Muokkaa QR-tyyliä",
|
||||
"flyerExporting": "Viedään...",
|
||||
"flyerHeadlineGradient": "Otsikon liukuväri",
|
||||
"flyerHeadlineSubColor": "Alaotsikon väri",
|
||||
"flyerMargins": "Sivun marginaalit",
|
||||
"flyerPerPage": "Esitteitä sivulla",
|
||||
"flyerPresetCustom": "Mukautettu",
|
||||
"flyerPresetName": "Esiasetuksen nimi",
|
||||
"flyerPresetSave": "Tallenna esiasetus",
|
||||
"flyerPrintLayout": "Tulostusasettelu",
|
||||
"flyerSections": "Osiot",
|
||||
"flyerSubtextColor": "Alatekstin väri",
|
||||
"flyerTextColor": "Tekstin väri",
|
||||
"flyerTextOverrides": "Mukautetut tekstit",
|
||||
"flyerToggleDivider": "Erotin",
|
||||
"flyerToggleFeatures": "Alaosan ominaisuudet",
|
||||
"flyerToggleSteps": "Näin se toimii -vaiheet",
|
||||
"flyerToggleSubtitle": "Alaotsikko",
|
||||
"flyerToggleTagline": "Alaosan iskulause",
|
||||
"flyerUploadLogo": "Lataa logo",
|
||||
"managePayouts": "Hallinnoi tilityksiä",
|
||||
"payoutTitle": "Tilitykset ja pankkitili",
|
||||
"tabFlyer": "Tulostettava esite",
|
||||
"tabQrCode": "QR-koodi",
|
||||
"toolsTitle": "QR-koodi- ja esite-Generator",
|
||||
"updateBankAccount": "Päivitä pankkitili",
|
||||
"connectFailed": "Jotain meni pieleen. Yritä uudelleen.",
|
||||
"flyerRemoveLogo": "Poista"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Appliqué automatiquement lors du paiement",
|
||||
"expires": "Expire le {date}",
|
||||
"referredBy": "Parrainé par {name}",
|
||||
"usingCode": "Code : {code}"
|
||||
"usingCode": "Code : {code}",
|
||||
"connectBankLoading": "Configuration en cours...",
|
||||
"connectDetailsNeeded": "Stripe a besoin d'informations supplémentaires pour activer les versements. Clique sur \"Mettre à jour le compte bancaire\" ci-dessous pour terminer la configuration.",
|
||||
"connectRefresh": "Il semble que tu n'aies pas terminé la configuration de ton compte bancaire. Clique ci-dessous pour réessayer.",
|
||||
"connectStatusActive": "Versements activés",
|
||||
"connectStatusPending": "Configuration en cours",
|
||||
"connectStripeNote": "Tu vas être redirigé vers le site sécurisé de Stripe pour entrer tes coordonnées bancaires. Cela prend généralement quelques minutes.",
|
||||
"flyerAccentColor": "Couleur d'accentuation",
|
||||
"flyerBranding": "Image de marque",
|
||||
"flyerColors": "Couleurs",
|
||||
"flyerDownloadHtml": "Télécharger HTML",
|
||||
"flyerDownloadPdf": "Télécharger PDF",
|
||||
"flyerDownloadPng": "Télécharger PNG",
|
||||
"flyerEditQr": "Modifier le style du QR",
|
||||
"flyerExporting": "Exportation en cours...",
|
||||
"flyerHeadlineGradient": "Dégradé du titre",
|
||||
"flyerHeadlineSubColor": "Couleur du sous-titre",
|
||||
"flyerMargins": "Marges de la page",
|
||||
"flyerPerPage": "Flyers par page",
|
||||
"flyerPresetCustom": "Personnalisé",
|
||||
"flyerPresetName": "Nom du préréglage",
|
||||
"flyerPresetSave": "Enregistrer le préréglage",
|
||||
"flyerPrintLayout": "Mise en page d'impression",
|
||||
"flyerSections": "Sections",
|
||||
"flyerSubtextColor": "Sous-texte",
|
||||
"flyerTextColor": "Texte",
|
||||
"flyerTextOverrides": "Textes personnalisés",
|
||||
"flyerToggleDivider": "Séparateur",
|
||||
"flyerToggleFeatures": "Fonctionnalités (bas)",
|
||||
"flyerToggleSteps": "Étapes de fonctionnement",
|
||||
"flyerToggleSubtitle": "Sous-titre",
|
||||
"flyerToggleTagline": "Slogan (bas)",
|
||||
"flyerUploadLogo": "Importer un logo",
|
||||
"managePayouts": "Gérer les versements",
|
||||
"payoutTitle": "Versements et compte bancaire",
|
||||
"tabFlyer": "Flyer imprimable",
|
||||
"tabQrCode": "Code QR",
|
||||
"toolsTitle": "Code QR & Flyer Generator",
|
||||
"updateBankAccount": "Mettre à jour le compte bancaire",
|
||||
"connectFailed": "Quelque chose s'est mal passé. Réessaie.",
|
||||
"flyerRemoveLogo": "Retirer"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "מופעל אוטומטית בקופה",
|
||||
"expires": "בתוקף עד {date}",
|
||||
"referredBy": "הפניה מאת {name}",
|
||||
"usingCode": "קוד: {code}"
|
||||
"usingCode": "קוד: {code}",
|
||||
"connectBankLoading": "מגדיר...",
|
||||
"connectDetailsNeeded": "Stripe זקוק למידע נוסף כדי לאפשר תשלומים. לחצו על \"עדכון חשבון בנק\" למטה כדי להשלים את ההגדרה.",
|
||||
"connectRefresh": "נראה שלא סיימתם להגדיר את חשבון הבנק שלכם. לחצו למטה כדי לנסות שוב.",
|
||||
"connectStatusActive": "תשלומים מופעלים",
|
||||
"connectStatusPending": "הגדרה בתהליך",
|
||||
"connectStripeNote": "תועברו לאתר המאובטח של Stripe כדי להזין את פרטי הבנק שלכם. זה בדרך כלל לוקח כמה דקות.",
|
||||
"flyerAccentColor": "צבע הדגשה",
|
||||
"flyerBranding": "מיתוג",
|
||||
"flyerColors": "צבעים",
|
||||
"flyerDownloadHtml": "הורדת HTML",
|
||||
"flyerDownloadPdf": "הורדת PDF",
|
||||
"flyerDownloadPng": "הורדת PNG",
|
||||
"flyerEditQr": "עריכת סגנון QR",
|
||||
"flyerExporting": "מייצא...",
|
||||
"flyerHeadlineGradient": "גרדיאנט כותרת",
|
||||
"flyerHeadlineSubColor": "צבע כותרת משנה",
|
||||
"flyerMargins": "שולי עמוד",
|
||||
"flyerPerPage": "פליירים לעמוד",
|
||||
"flyerPresetCustom": "מותאם אישית",
|
||||
"flyerPresetName": "שם תבנית",
|
||||
"flyerPresetSave": "שמירת תבנית",
|
||||
"flyerPrintLayout": "פריסת הדפסה",
|
||||
"flyerSections": "מקטעים",
|
||||
"flyerSubtextColor": "טקסט משנה",
|
||||
"flyerTextColor": "טקסט",
|
||||
"flyerTextOverrides": "התאמות טקסט",
|
||||
"flyerToggleDivider": "קו מפריד",
|
||||
"flyerToggleFeatures": "תכונות תחתונות",
|
||||
"flyerToggleSteps": "שלבי 'איך זה עובד'",
|
||||
"flyerToggleSubtitle": "כותרת משנה",
|
||||
"flyerToggleTagline": "סלוגן תחתון",
|
||||
"flyerUploadLogo": "העלאת לוגו",
|
||||
"managePayouts": "ניהול תשלומים",
|
||||
"payoutTitle": "תשלומים וחשבון בנק",
|
||||
"tabFlyer": "פלייר להדפסה",
|
||||
"tabQrCode": "קוד QR",
|
||||
"toolsTitle": "Generator קודי QR ופליירים",
|
||||
"updateBankAccount": "עדכון חשבון בנק",
|
||||
"connectFailed": "משהו השתבש. אנא נסה שוב.",
|
||||
"flyerRemoveLogo": "הסרה"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "चेकआउट पर अपने आप लागू",
|
||||
"expires": "{date} को समाप्त",
|
||||
"referredBy": "{name} द्वारा रेफर किया गया",
|
||||
"usingCode": "कोड: {code}"
|
||||
"usingCode": "कोड: {code}",
|
||||
"connectBankLoading": "सेटअप हो रहा है...",
|
||||
"connectDetailsNeeded": "पेआउट चालू करने के लिए Stripe को कुछ और जानकारी चाहिए। सेटअप पूरा करने के लिए नीचे \"बैंक खाता अपडेट करो\" पर क्लिक करो।",
|
||||
"connectRefresh": "लगता है तुमने अपना बैंक खाता सेटअप पूरा नहीं किया। फिर से कोशिश करने के लिए नीचे क्लिक करो।",
|
||||
"connectStatusActive": "पेआउट चालू हैं",
|
||||
"connectStatusPending": "सेटअप चल रहा है",
|
||||
"connectStripeNote": "तुम्हें अपने बैंक की जानकारी डालने के लिए Stripe की सुरक्षित साइट पर भेजा जाएगा। इसमें आमतौर पर कुछ मिनट लगते हैं।",
|
||||
"flyerAccentColor": "एक्सेंट",
|
||||
"flyerBranding": "ब्रांडिंग",
|
||||
"flyerColors": "रंग",
|
||||
"flyerDownloadHtml": "HTML डाउनलोड करो",
|
||||
"flyerDownloadPdf": "PDF डाउनलोड करो",
|
||||
"flyerDownloadPng": "PNG डाउनलोड करो",
|
||||
"flyerEditQr": "QR स्टाइल एडिट करो",
|
||||
"flyerExporting": "एक्सपोर्ट हो रहा है...",
|
||||
"flyerHeadlineGradient": "हेडलाइन ग्रेडिएंट",
|
||||
"flyerHeadlineSubColor": "हेडलाइन सब",
|
||||
"flyerMargins": "पेज मार्जिन",
|
||||
"flyerPerPage": "प्रति पेज फ्लायर",
|
||||
"flyerPresetCustom": "कस्टम",
|
||||
"flyerPresetName": "प्रीसेट का नाम",
|
||||
"flyerPresetSave": "प्रीसेट सेव करो",
|
||||
"flyerPrintLayout": "प्रिंट लेआउट",
|
||||
"flyerSections": "सेक्शन",
|
||||
"flyerSubtextColor": "सबटेक्स्ट",
|
||||
"flyerTextColor": "टेक्स्ट",
|
||||
"flyerTextOverrides": "टेक्स्ट ओवरराइड",
|
||||
"flyerToggleDivider": "डिवाइडर",
|
||||
"flyerToggleFeatures": "निचले फीचर्स",
|
||||
"flyerToggleSteps": "यह कैसे काम करता है - स्टेप्स",
|
||||
"flyerToggleSubtitle": "सबटाइटल",
|
||||
"flyerToggleTagline": "निचली टैगलाइन",
|
||||
"flyerUploadLogo": "लोगो अपलोड करो",
|
||||
"managePayouts": "पेआउट मैनेज करो",
|
||||
"payoutTitle": "पेआउट और बैंक खाता",
|
||||
"tabFlyer": "प्रिंट करने योग्य फ्लायर",
|
||||
"tabQrCode": "QR कोड",
|
||||
"toolsTitle": "QR कोड और फ्लायर Generator",
|
||||
"updateBankAccount": "बैंक खाता अपडेट करो",
|
||||
"connectFailed": "कुछ गलत हो गया। कृपया फिर से कोशिश करो।",
|
||||
"flyerRemoveLogo": "हटाओ"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Primjenjuje se automatski pri plaćanju",
|
||||
"expires": "Ističe {date}",
|
||||
"referredBy": "Preporučio/la {name}",
|
||||
"usingCode": "Kod: {code}"
|
||||
"usingCode": "Kod: {code}",
|
||||
"connectBankLoading": "Postavljanje...",
|
||||
"connectDetailsNeeded": "Stripe treba dodatne informacije kako bi omogućio isplate. Klikni \"Ažuriraj bankovni račun\" u nastavku za dovršetak postavljanja.",
|
||||
"connectRefresh": "Čini se da postavljanje tvog bankovnog računa nije dovršeno. Klikni u nastavku i pokušaj ponovno.",
|
||||
"connectStatusActive": "Isplate omogućene",
|
||||
"connectStatusPending": "Postavljanje u tijeku",
|
||||
"connectStripeNote": "Preusmjerit ćemo te na sigurnu Stripe stranicu za unos bankovnih podataka. To obično traje nekoliko minuta.",
|
||||
"flyerAccentColor": "Boja naglaska",
|
||||
"flyerBranding": "Brendiranje",
|
||||
"flyerColors": "Boje",
|
||||
"flyerDownloadHtml": "Preuzmi HTML",
|
||||
"flyerDownloadPdf": "Preuzmi PDF",
|
||||
"flyerDownloadPng": "Preuzmi PNG",
|
||||
"flyerEditQr": "Uredi stil QR koda",
|
||||
"flyerExporting": "Izvoz...",
|
||||
"flyerHeadlineGradient": "Gradijent naslova",
|
||||
"flyerHeadlineSubColor": "Boja podnaslova",
|
||||
"flyerMargins": "Margine stranice",
|
||||
"flyerPerPage": "Letaka po stranici",
|
||||
"flyerPresetCustom": "Prilagođeno",
|
||||
"flyerPresetName": "Naziv predloška",
|
||||
"flyerPresetSave": "Spremi predložak",
|
||||
"flyerPrintLayout": "Izgled za ispis",
|
||||
"flyerSections": "Sekcije",
|
||||
"flyerSubtextColor": "Podtekst",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Izmjene teksta",
|
||||
"flyerToggleDivider": "Razdjelnik",
|
||||
"flyerToggleFeatures": "Značajke na dnu",
|
||||
"flyerToggleSteps": "Koraci za korištenje",
|
||||
"flyerToggleSubtitle": "Podnaslov",
|
||||
"flyerToggleTagline": "Slogan na dnu",
|
||||
"flyerUploadLogo": "Učitaj logotip",
|
||||
"managePayouts": "Upravljaj isplatama",
|
||||
"payoutTitle": "Isplate i bankovni račun",
|
||||
"tabFlyer": "Letak za ispis",
|
||||
"tabQrCode": "QR kod",
|
||||
"toolsTitle": "Generator QR koda i letaka",
|
||||
"updateBankAccount": "Ažuriraj bankovni račun",
|
||||
"connectFailed": "Nešto je pošlo po zlu. Pokušaj ponovno.",
|
||||
"flyerRemoveLogo": "Ukloni"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Automatikusan érvényesítve a fizetésnél",
|
||||
"expires": "Lejár: {date}",
|
||||
"referredBy": "Ajánlotta: {name}",
|
||||
"usingCode": "Kód: {code}"
|
||||
"usingCode": "Kód: {code}",
|
||||
"connectBankLoading": "Beállítás folyamatban...",
|
||||
"connectDetailsNeeded": "A Stripe-nak további információkra van szüksége a kifizetések engedélyezéséhez. Kattints az alábbi \"Bankszámla frissítése\" gombra a beállítás befejezéséhez.",
|
||||
"connectRefresh": "Úgy tűnik, nem fejezted be a bankszámlád beállítását. Kattints az alábbi gombra az újrapróbálkozáshoz.",
|
||||
"connectStatusActive": "Kifizetések engedélyezve",
|
||||
"connectStatusPending": "Beállítás folyamatban",
|
||||
"connectStripeNote": "Átirányítunk a Stripe biztonságos oldalára, ahol megadhatod a banki adataidat. Ez általában csak néhány percet vesz igénybe.",
|
||||
"flyerAccentColor": "Kiemelő szín",
|
||||
"flyerBranding": "Arculat",
|
||||
"flyerColors": "Színek",
|
||||
"flyerDownloadHtml": "HTML letöltése",
|
||||
"flyerDownloadPdf": "PDF letöltése",
|
||||
"flyerDownloadPng": "PNG letöltése",
|
||||
"flyerEditQr": "QR stílus szerkesztése",
|
||||
"flyerExporting": "Exportálás...",
|
||||
"flyerHeadlineGradient": "Címsor színátmenete",
|
||||
"flyerHeadlineSubColor": "Alcím színe",
|
||||
"flyerMargins": "Oldalmargók",
|
||||
"flyerPerPage": "Szórólap oldalanként",
|
||||
"flyerPresetCustom": "Egyéni",
|
||||
"flyerPresetName": "Előbeállítás neve",
|
||||
"flyerPresetSave": "Előbeállítás mentése",
|
||||
"flyerPrintLayout": "Nyomtatási elrendezés",
|
||||
"flyerSections": "Szakaszok",
|
||||
"flyerSubtextColor": "Kiegészítő szöveg",
|
||||
"flyerTextColor": "Szöveg",
|
||||
"flyerTextOverrides": "Egyéni szövegek",
|
||||
"flyerToggleDivider": "Elválasztó",
|
||||
"flyerToggleFeatures": "Alsó funkciók",
|
||||
"flyerToggleSteps": "Működés lépései",
|
||||
"flyerToggleSubtitle": "Alcím",
|
||||
"flyerToggleTagline": "Alsó szlogen",
|
||||
"flyerUploadLogo": "Logó feltöltése",
|
||||
"managePayouts": "Kifizetések kezelése",
|
||||
"payoutTitle": "Kifizetések és bankszámla",
|
||||
"tabFlyer": "Nyomtatható szórólap",
|
||||
"tabQrCode": "QR-kód",
|
||||
"toolsTitle": "QR-kód és szórólap Generator",
|
||||
"updateBankAccount": "Bankszámla frissítése",
|
||||
"connectFailed": "Valami hiba történt. Kérlek, próbáld újra.",
|
||||
"flyerRemoveLogo": "Eltávolítás"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Diterapkan otomatis saat checkout",
|
||||
"expires": "Kedaluwarsa {date}",
|
||||
"referredBy": "Referensi dari {name}",
|
||||
"usingCode": "Kode: {code}"
|
||||
"usingCode": "Kode: {code}",
|
||||
"connectBankLoading": "Sedang menyiapkan...",
|
||||
"connectDetailsNeeded": "Stripe memerlukan informasi tambahan untuk mengaktifkan pencairan dana. Klik \"Perbarui Rekening Bank\" di bawah untuk menyelesaikan penyiapan.",
|
||||
"connectRefresh": "Sepertinya Anda belum selesai menyiapkan rekening bank Anda. Klik di bawah untuk mencoba lagi.",
|
||||
"connectStatusActive": "Pencairan dana diaktifkan",
|
||||
"connectStatusPending": "Penyiapan sedang berlangsung",
|
||||
"connectStripeNote": "Anda akan diarahkan ke situs aman Stripe untuk memasukkan detail bank Anda. Ini biasanya memakan waktu beberapa menit.",
|
||||
"flyerAccentColor": "Aksen",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Warna",
|
||||
"flyerDownloadHtml": "Unduh HTML",
|
||||
"flyerDownloadPdf": "Unduh PDF",
|
||||
"flyerDownloadPng": "Unduh PNG",
|
||||
"flyerEditQr": "Edit Gaya QR",
|
||||
"flyerExporting": "Mengekspor...",
|
||||
"flyerHeadlineGradient": "Gradien Judul",
|
||||
"flyerHeadlineSubColor": "Subjudul",
|
||||
"flyerMargins": "Margin Halaman",
|
||||
"flyerPerPage": "Brosur Per Halaman",
|
||||
"flyerPresetCustom": "Kustom",
|
||||
"flyerPresetName": "Nama Preset",
|
||||
"flyerPresetSave": "Simpan Preset",
|
||||
"flyerPrintLayout": "Tata Letak Cetak",
|
||||
"flyerSections": "Bagian",
|
||||
"flyerSubtextColor": "Subteks",
|
||||
"flyerTextColor": "Teks",
|
||||
"flyerTextOverrides": "Penggantian Teks",
|
||||
"flyerToggleDivider": "Pemisah",
|
||||
"flyerToggleFeatures": "Fitur Bagian Bawah",
|
||||
"flyerToggleSteps": "Langkah Cara Kerja",
|
||||
"flyerToggleSubtitle": "Subjudul",
|
||||
"flyerToggleTagline": "Slogan Bagian Bawah",
|
||||
"flyerUploadLogo": "Unggah Logo",
|
||||
"managePayouts": "Kelola Pencairan Dana",
|
||||
"payoutTitle": "Pencairan Dana & Rekening Bank",
|
||||
"tabFlyer": "Brosur Cetak",
|
||||
"tabQrCode": "Kode QR",
|
||||
"toolsTitle": "Generator Kode QR & Brosur",
|
||||
"updateBankAccount": "Perbarui Rekening Bank",
|
||||
"connectFailed": "Terjadi kesalahan. Silakan coba lagi.",
|
||||
"flyerRemoveLogo": "Hapus"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Applicato automaticamente al checkout",
|
||||
"expires": "Scade {date}",
|
||||
"referredBy": "Invitato da {name}",
|
||||
"usingCode": "Codice: {code}"
|
||||
"usingCode": "Codice: {code}",
|
||||
"connectBankLoading": "Configurazione in corso...",
|
||||
"connectDetailsNeeded": "Stripe ha bisogno di ulteriori informazioni per abilitare gli accrediti. Clicca su \"Aggiorna conto bancario\" qui sotto per completare la configurazione.",
|
||||
"connectRefresh": "Sembra che tu non abbia finito di configurare il tuo conto bancario. Clicca qui sotto per riprovare.",
|
||||
"connectStatusActive": "Accrediti abilitati",
|
||||
"connectStatusPending": "Configurazione in corso",
|
||||
"connectStripeNote": "Verrai reindirizzato al sito sicuro di Stripe per inserire i tuoi dati bancari. Di solito ci vogliono un paio di minuti.",
|
||||
"flyerAccentColor": "Accento",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Colori",
|
||||
"flyerDownloadHtml": "Scarica HTML",
|
||||
"flyerDownloadPdf": "Scarica PDF",
|
||||
"flyerDownloadPng": "Scarica PNG",
|
||||
"flyerEditQr": "Modifica stile QR",
|
||||
"flyerExporting": "Esportazione in corso...",
|
||||
"flyerHeadlineGradient": "Sfumatura titolo",
|
||||
"flyerHeadlineSubColor": "Sottotitolo",
|
||||
"flyerMargins": "Margini pagina",
|
||||
"flyerPerPage": "Volantini per pagina",
|
||||
"flyerPresetCustom": "Personalizzato",
|
||||
"flyerPresetName": "Nome preset",
|
||||
"flyerPresetSave": "Salva preset",
|
||||
"flyerPrintLayout": "Layout di stampa",
|
||||
"flyerSections": "Sezioni",
|
||||
"flyerSubtextColor": "Sottotesto",
|
||||
"flyerTextColor": "Testo",
|
||||
"flyerTextOverrides": "Sostituzioni testo",
|
||||
"flyerToggleDivider": "Separatore",
|
||||
"flyerToggleFeatures": "Funzionalità in basso",
|
||||
"flyerToggleSteps": "Passaggi 'Come funziona'",
|
||||
"flyerToggleSubtitle": "Sottotitolo",
|
||||
"flyerToggleTagline": "Slogan in basso",
|
||||
"flyerUploadLogo": "Carica logo",
|
||||
"managePayouts": "Gestisci accrediti",
|
||||
"payoutTitle": "Accrediti e conto bancario",
|
||||
"tabFlyer": "Volantino stampabile",
|
||||
"tabQrCode": "Codice QR",
|
||||
"toolsTitle": "Generator di codici QR e volantini",
|
||||
"updateBankAccount": "Aggiorna conto bancario",
|
||||
"connectFailed": "Qualcosa è andato storto. Riprova.",
|
||||
"flyerRemoveLogo": "Rimuovi"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "チェックアウト時に自動的に適用されます",
|
||||
"expires": "有効期限: {date}",
|
||||
"referredBy": "{name}さんからの紹介",
|
||||
"usingCode": "コード: {code}"
|
||||
"usingCode": "コード: {code}",
|
||||
"connectBankLoading": "設定中...",
|
||||
"connectDetailsNeeded": "入金を有効にするには、Stripeに追加情報を登録する必要があります。下の「銀行口座を更新」をクリックして設定を完了してください。",
|
||||
"connectRefresh": "銀行口座の設定が完了していないようです。下をクリックしてもう一度お試しください。",
|
||||
"connectStatusActive": "入金有効",
|
||||
"connectStatusPending": "設定中",
|
||||
"connectStripeNote": "銀行口座情報を入力するため、Stripeの安全なサイトに移動します。通常、数分で完了します。",
|
||||
"flyerAccentColor": "アクセント",
|
||||
"flyerBranding": "ブランディング",
|
||||
"flyerColors": "カラー",
|
||||
"flyerDownloadHtml": "HTMLをダウンロード",
|
||||
"flyerDownloadPdf": "PDFをダウンロード",
|
||||
"flyerDownloadPng": "PNGをダウンロード",
|
||||
"flyerEditQr": "QRスタイルを編集",
|
||||
"flyerExporting": "エクスポート中...",
|
||||
"flyerHeadlineGradient": "見出しのグラデーション",
|
||||
"flyerHeadlineSubColor": "見出しのサブカラー",
|
||||
"flyerMargins": "ページの余白",
|
||||
"flyerPerPage": "1ページあたりのチラシ枚数",
|
||||
"flyerPresetCustom": "カスタム",
|
||||
"flyerPresetName": "プリセット名",
|
||||
"flyerPresetSave": "プリセットを保存",
|
||||
"flyerPrintLayout": "印刷レイアウト",
|
||||
"flyerSections": "セクション",
|
||||
"flyerSubtextColor": "サブテキスト",
|
||||
"flyerTextColor": "テキスト",
|
||||
"flyerTextOverrides": "テキストの変更",
|
||||
"flyerToggleDivider": "区切り線",
|
||||
"flyerToggleFeatures": "下部の機能",
|
||||
"flyerToggleSteps": "使い方のステップ",
|
||||
"flyerToggleSubtitle": "サブタイトル",
|
||||
"flyerToggleTagline": "下部のキャッチコピー",
|
||||
"flyerUploadLogo": "ロゴをアップロード",
|
||||
"managePayouts": "入金の管理",
|
||||
"payoutTitle": "入金と銀行口座",
|
||||
"tabFlyer": "印刷用チラシ",
|
||||
"tabQrCode": "QRコード",
|
||||
"toolsTitle": "QRコード&チラシ Generator",
|
||||
"updateBankAccount": "銀行口座を更新",
|
||||
"connectFailed": "問題が発生しました。もう一度お試しください。",
|
||||
"flyerRemoveLogo": "削除"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "결제 시 자동으로 적용됩니다",
|
||||
"expires": "{date} 만료",
|
||||
"referredBy": "{name}님의 추천",
|
||||
"usingCode": "코드: {code}"
|
||||
"usingCode": "코드: {code}",
|
||||
"connectBankLoading": "설정 중...",
|
||||
"connectDetailsNeeded": "지급을 활성화하려면 Stripe에 추가 정보가 필요합니다. 설정을 완료하려면 아래의 \"은행 계좌 업데이트\"를 클릭해 주세요.",
|
||||
"connectRefresh": "은행 계좌 설정을 완료하지 않으신 것 같습니다. 다시 시도하려면 아래를 클릭해 주세요.",
|
||||
"connectStatusActive": "지급 활성화됨",
|
||||
"connectStatusPending": "설정 진행 중",
|
||||
"connectStripeNote": "은행 정보를 안전하게 입력할 수 있도록 Stripe 사이트로 이동합니다. 보통 몇 분 정도 소요됩니다.",
|
||||
"flyerAccentColor": "포인트 색상",
|
||||
"flyerBranding": "브랜딩",
|
||||
"flyerColors": "색상",
|
||||
"flyerDownloadHtml": "HTML 다운로드",
|
||||
"flyerDownloadPdf": "PDF 다운로드",
|
||||
"flyerDownloadPng": "PNG 다운로드",
|
||||
"flyerEditQr": "QR 스타일 편집",
|
||||
"flyerExporting": "내보내는 중...",
|
||||
"flyerHeadlineGradient": "헤드라인 그라데이션",
|
||||
"flyerHeadlineSubColor": "헤드라인 서브 색상",
|
||||
"flyerMargins": "페이지 여백",
|
||||
"flyerPerPage": "페이지당 전단지 수",
|
||||
"flyerPresetCustom": "사용자 지정",
|
||||
"flyerPresetName": "프리셋 이름",
|
||||
"flyerPresetSave": "프리셋 저장",
|
||||
"flyerPrintLayout": "인쇄 레이아웃",
|
||||
"flyerSections": "섹션",
|
||||
"flyerSubtextColor": "서브텍스트 색상",
|
||||
"flyerTextColor": "텍스트 색상",
|
||||
"flyerTextOverrides": "텍스트 변경",
|
||||
"flyerToggleDivider": "구분선",
|
||||
"flyerToggleFeatures": "하단 기능",
|
||||
"flyerToggleSteps": "이용 방법 단계",
|
||||
"flyerToggleSubtitle": "부제목",
|
||||
"flyerToggleTagline": "하단 태그라인",
|
||||
"flyerUploadLogo": "로고 업로드",
|
||||
"managePayouts": "지급 관리",
|
||||
"payoutTitle": "지급 및 은행 계좌",
|
||||
"tabFlyer": "인쇄용 전단지",
|
||||
"tabQrCode": "QR 코드",
|
||||
"toolsTitle": "QR 코드 및 전단지 Generator",
|
||||
"updateBankAccount": "은행 계좌 업데이트",
|
||||
"connectFailed": "문제가 발생했습니다. 다시 시도해 주세요.",
|
||||
"flyerRemoveLogo": "제거"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Digunakan secara automatik semasa pembayaran",
|
||||
"expires": "Tamat tempoh {date}",
|
||||
"referredBy": "Dirujuk oleh {name}",
|
||||
"usingCode": "Kod: {code}"
|
||||
"usingCode": "Kod: {code}",
|
||||
"connectBankLoading": "Sedang menyediakan...",
|
||||
"connectDetailsNeeded": "Stripe memerlukan maklumat tambahan untuk mengaktifkan pembayaran. Klik \"Kemas Kini Akaun Bank\" di bawah untuk melengkapkan persediaan.",
|
||||
"connectRefresh": "Nampaknya anda tidak selesai menyediakan akaun bank anda. Klik di bawah untuk cuba lagi.",
|
||||
"connectStatusActive": "Pembayaran diaktifkan",
|
||||
"connectStatusPending": "Persediaan sedang dijalankan",
|
||||
"connectStripeNote": "Anda akan dialihkan ke laman web selamat Stripe untuk memasukkan butiran bank anda. Ini biasanya mengambil masa beberapa minit.",
|
||||
"flyerAccentColor": "Aksen",
|
||||
"flyerBranding": "Penjenamaan",
|
||||
"flyerColors": "Warna",
|
||||
"flyerDownloadHtml": "Muat Turun HTML",
|
||||
"flyerDownloadPdf": "Muat Turun PDF",
|
||||
"flyerDownloadPng": "Muat Turun PNG",
|
||||
"flyerEditQr": "Edit Gaya QR",
|
||||
"flyerExporting": "Mengeksport...",
|
||||
"flyerHeadlineGradient": "Kecerunan Tajuk",
|
||||
"flyerHeadlineSubColor": "Subtajuk",
|
||||
"flyerMargins": "Margin Halaman",
|
||||
"flyerPerPage": "Risalah Setiap Halaman",
|
||||
"flyerPresetCustom": "Tersuai",
|
||||
"flyerPresetName": "Nama pratetap",
|
||||
"flyerPresetSave": "Simpan Pratetap",
|
||||
"flyerPrintLayout": "Susun Atur Cetakan",
|
||||
"flyerSections": "Bahagian",
|
||||
"flyerSubtextColor": "Subteks",
|
||||
"flyerTextColor": "Teks",
|
||||
"flyerTextOverrides": "Gantian Teks",
|
||||
"flyerToggleDivider": "Pembahagi",
|
||||
"flyerToggleFeatures": "Ciri-ciri Bawah",
|
||||
"flyerToggleSteps": "Langkah-langkah Cara Ia Berfungsi",
|
||||
"flyerToggleSubtitle": "Subtajuk",
|
||||
"flyerToggleTagline": "Slogan Bawah",
|
||||
"flyerUploadLogo": "Muat Naik Logo",
|
||||
"managePayouts": "Urus Pembayaran",
|
||||
"payoutTitle": "Pembayaran & Akaun Bank",
|
||||
"tabFlyer": "Risalah Boleh Dicetak",
|
||||
"tabQrCode": "Kod QR",
|
||||
"toolsTitle": "Generator Kod QR & Risalah",
|
||||
"updateBankAccount": "Kemas Kini Akaun Bank",
|
||||
"connectFailed": "Sesuatu yang tidak kena berlaku. Sila cuba lagi.",
|
||||
"flyerRemoveLogo": "Alih keluar"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Legges til automatisk i kassen",
|
||||
"expires": "Utløper {date}",
|
||||
"referredBy": "Vervet av {name}",
|
||||
"usingCode": "Kode: {code}"
|
||||
"usingCode": "Kode: {code}",
|
||||
"connectBankLoading": "Setter opp...",
|
||||
"connectDetailsNeeded": "Stripe trenger mer informasjon for å aktivere utbetalinger. Klikk på \"Oppdater bankkonto\" nedenfor for å fullføre oppsettet.",
|
||||
"connectRefresh": "Det ser ut til at du ikke ble ferdig med å sette opp bankkontoen din. Klikk nedenfor for å prøve igjen.",
|
||||
"connectStatusActive": "Utbetalinger aktivert",
|
||||
"connectStatusPending": "Oppsett pågår",
|
||||
"connectStripeNote": "Du vil bli omdirigert til Stripes sikre nettsted for å legge inn bankdetaljene dine. Dette tar vanligvis et par minutter.",
|
||||
"flyerAccentColor": "Aksent",
|
||||
"flyerBranding": "Profilering",
|
||||
"flyerColors": "Farger",
|
||||
"flyerDownloadHtml": "Last ned HTML",
|
||||
"flyerDownloadPdf": "Last ned PDF",
|
||||
"flyerDownloadPng": "Last ned PNG",
|
||||
"flyerEditQr": "Rediger QR-stil",
|
||||
"flyerExporting": "Eksporterer...",
|
||||
"flyerHeadlineGradient": "Overskriftsgradient",
|
||||
"flyerHeadlineSubColor": "Underoverskrift",
|
||||
"flyerMargins": "Sidemarginer",
|
||||
"flyerPerPage": "Flyere per side",
|
||||
"flyerPresetCustom": "Tilpasset",
|
||||
"flyerPresetName": "Navn på forhåndsinnstilling",
|
||||
"flyerPresetSave": "Lagre forhåndsinnstilling",
|
||||
"flyerPrintLayout": "Utskriftsoppsett",
|
||||
"flyerSections": "Seksjoner",
|
||||
"flyerSubtextColor": "Undertekst",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Tekstoverstyringer",
|
||||
"flyerToggleDivider": "Skillelinje",
|
||||
"flyerToggleFeatures": "Funksjoner nederst",
|
||||
"flyerToggleSteps": "Slik fungerer det-trinn",
|
||||
"flyerToggleSubtitle": "Undertittel",
|
||||
"flyerToggleTagline": "Slagord nederst",
|
||||
"flyerUploadLogo": "Last opp logo",
|
||||
"managePayouts": "Administrer utbetalinger",
|
||||
"payoutTitle": "Utbetalinger og bankkonto",
|
||||
"tabFlyer": "Utskriftsvennlig flyer",
|
||||
"tabQrCode": "QR-kode",
|
||||
"toolsTitle": "Generator for QR-kode og flyer",
|
||||
"updateBankAccount": "Oppdater bankkonto",
|
||||
"connectFailed": "Noe gikk galt. Vennligst prøv igjen.",
|
||||
"flyerRemoveLogo": "Fjern"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Wordt automatisch toegepast bij het afrekenen",
|
||||
"expires": "Verloopt op {date}",
|
||||
"referredBy": "Doorverwezen door {name}",
|
||||
"usingCode": "Code: {code}"
|
||||
"usingCode": "Code: {code}",
|
||||
"connectBankLoading": "Bezig met instellen...",
|
||||
"connectDetailsNeeded": "Stripe heeft aanvullende informatie nodig om uitbetalingen in te schakelen. Klik hieronder op \"Bankrekening bijwerken\" om het instellen te voltooien.",
|
||||
"connectRefresh": "Het lijkt erop dat je het instellen van je bankrekening niet hebt voltooid. Klik hieronder om het opnieuw te proberen.",
|
||||
"connectStatusActive": "Uitbetalingen ingeschakeld",
|
||||
"connectStatusPending": "Bezig met instellen",
|
||||
"connectStripeNote": "Je wordt doorgestuurd naar de beveiligde site van Stripe om je bankgegevens in te voeren. Dit duurt meestal een paar minuten.",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Kleuren",
|
||||
"flyerDownloadHtml": "HTML downloaden",
|
||||
"flyerDownloadPdf": "PDF downloaden",
|
||||
"flyerDownloadPng": "PNG downloaden",
|
||||
"flyerEditQr": "QR-stijl bewerken",
|
||||
"flyerExporting": "Bezig met exporteren...",
|
||||
"flyerHeadlineGradient": "Kleurverloop koptekst",
|
||||
"flyerHeadlineSubColor": "Subkoptekst",
|
||||
"flyerMargins": "Paginamarges",
|
||||
"flyerPerPage": "Flyers per pagina",
|
||||
"flyerPresetCustom": "Aangepast",
|
||||
"flyerPresetName": "Preset-naam",
|
||||
"flyerPresetSave": "Preset opslaan",
|
||||
"flyerPrintLayout": "Afdruklay-out",
|
||||
"flyerSections": "Secties",
|
||||
"flyerSubtextColor": "Subtekst",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Tekstaanpassingen",
|
||||
"flyerToggleDivider": "Scheidingslijn",
|
||||
"flyerToggleFeatures": "Functies onderaan",
|
||||
"flyerToggleSteps": "Stappen 'Hoe het werkt'",
|
||||
"flyerToggleSubtitle": "Ondertitel",
|
||||
"flyerToggleTagline": "Slogan onderaan",
|
||||
"flyerUploadLogo": "Logo uploaden",
|
||||
"managePayouts": "Uitbetalingen beheren",
|
||||
"payoutTitle": "Uitbetalingen & bankrekening",
|
||||
"tabFlyer": "Afdrukbare flyer",
|
||||
"tabQrCode": "QR-code",
|
||||
"toolsTitle": "QR-code & Flyer Generator",
|
||||
"updateBankAccount": "Bankrekening bijwerken",
|
||||
"connectFailed": "Er is iets misgegaan. Probeer het opnieuw.",
|
||||
"flyerRemoveLogo": "Verwijderen"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Zastosowano automatycznie przy płatności",
|
||||
"expires": "Wygasa {date}",
|
||||
"referredBy": "Z polecenia {name}",
|
||||
"usingCode": "Kod: {code}"
|
||||
"usingCode": "Kod: {code}",
|
||||
"connectBankLoading": "Konfigurowanie...",
|
||||
"connectDetailsNeeded": "Stripe potrzebuje dodatkowych informacji, aby włączyć wypłaty. Kliknij \"Zaktualizuj konto bankowe\" poniżej, aby dokończyć konfigurację.",
|
||||
"connectRefresh": "Wygląda na to, że nie udało Ci się dokończyć konfiguracji konta bankowego. Kliknij poniżej, aby spróbować ponownie.",
|
||||
"connectStatusActive": "Wypłaty włączone",
|
||||
"connectStatusPending": "Konfiguracja w toku",
|
||||
"connectStripeNote": "Przekierujemy Cię na bezpieczną stronę Stripe, gdzie podasz swoje dane bankowe. Zazwyczaj zajmuje to kilka minut.",
|
||||
"flyerAccentColor": "Akcent",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Kolory",
|
||||
"flyerDownloadHtml": "Pobierz HTML",
|
||||
"flyerDownloadPdf": "Pobierz PDF",
|
||||
"flyerDownloadPng": "Pobierz PNG",
|
||||
"flyerEditQr": "Edytuj styl QR",
|
||||
"flyerExporting": "Eksportowanie...",
|
||||
"flyerHeadlineGradient": "Gradient nagłówka",
|
||||
"flyerHeadlineSubColor": "Podnagłówek",
|
||||
"flyerMargins": "Marginesy strony",
|
||||
"flyerPerPage": "Ulotek na stronę",
|
||||
"flyerPresetCustom": "Niestandardowe",
|
||||
"flyerPresetName": "Nazwa ustawienia",
|
||||
"flyerPresetSave": "Zapisz ustawienie",
|
||||
"flyerPrintLayout": "Układ wydruku",
|
||||
"flyerSections": "Sekcje",
|
||||
"flyerSubtextColor": "Tekst dodatkowy",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Nadpisywanie tekstu",
|
||||
"flyerToggleDivider": "Separator",
|
||||
"flyerToggleFeatures": "Dolne funkcje",
|
||||
"flyerToggleSteps": "Kroki „Jak to działa”",
|
||||
"flyerToggleSubtitle": "Podtytuł",
|
||||
"flyerToggleTagline": "Dolny slogan",
|
||||
"flyerUploadLogo": "Prześlij logo",
|
||||
"managePayouts": "Zarządzaj wypłatami",
|
||||
"payoutTitle": "Wypłaty i konto bankowe",
|
||||
"tabFlyer": "Ulotka do druku",
|
||||
"tabQrCode": "Kod QR",
|
||||
"toolsTitle": "Generator kodów QR i ulotek",
|
||||
"updateBankAccount": "Zaktualizuj konto bankowe",
|
||||
"connectFailed": "Coś poszło nie tak. Spróbuj ponownie.",
|
||||
"flyerRemoveLogo": "Usuń"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Aplicado automaticamente no checkout",
|
||||
"expires": "Expira em {date}",
|
||||
"referredBy": "Indicado por {name}",
|
||||
"usingCode": "Código: {code}"
|
||||
"usingCode": "Código: {code}",
|
||||
"connectBankLoading": "Configurando...",
|
||||
"connectDetailsNeeded": "O Stripe precisa de informações adicionais para habilitar os repasses. Clique em \"Atualizar conta bancária\" abaixo para concluir a configuração.",
|
||||
"connectRefresh": "Parece que você não terminou de configurar sua conta bancária. Clique abaixo para tentar novamente.",
|
||||
"connectStatusActive": "Repasses habilitados",
|
||||
"connectStatusPending": "Configuração em andamento",
|
||||
"connectStripeNote": "Você será redirecionado para o site seguro do Stripe para inserir seus dados bancários. Isso geralmente leva alguns minutos.",
|
||||
"flyerAccentColor": "Destaque",
|
||||
"flyerBranding": "Marca",
|
||||
"flyerColors": "Cores",
|
||||
"flyerDownloadHtml": "Baixar HTML",
|
||||
"flyerDownloadPdf": "Baixar PDF",
|
||||
"flyerDownloadPng": "Baixar PNG",
|
||||
"flyerEditQr": "Editar estilo do QR",
|
||||
"flyerExporting": "Exportando...",
|
||||
"flyerHeadlineGradient": "Gradiente do título",
|
||||
"flyerHeadlineSubColor": "Cor do subtítulo",
|
||||
"flyerMargins": "Margens da página",
|
||||
"flyerPerPage": "Panfletos por página",
|
||||
"flyerPresetCustom": "Personalizado",
|
||||
"flyerPresetName": "Nome da predefinição",
|
||||
"flyerPresetSave": "Salvar predefinição",
|
||||
"flyerPrintLayout": "Layout de impressão",
|
||||
"flyerSections": "Seções",
|
||||
"flyerSubtextColor": "Subtexto",
|
||||
"flyerTextColor": "Texto",
|
||||
"flyerTextOverrides": "Substituições de texto",
|
||||
"flyerToggleDivider": "Divisória",
|
||||
"flyerToggleFeatures": "Recursos inferiores",
|
||||
"flyerToggleSteps": "Etapas de 'Como funciona'",
|
||||
"flyerToggleSubtitle": "Subtítulo",
|
||||
"flyerToggleTagline": "Slogan inferior",
|
||||
"flyerUploadLogo": "Enviar logotipo",
|
||||
"managePayouts": "Gerenciar repasses",
|
||||
"payoutTitle": "Repasses e conta bancária",
|
||||
"tabFlyer": "Panfleto imprimível",
|
||||
"tabQrCode": "QR Code",
|
||||
"toolsTitle": "Generator de QR Code e Panfleto",
|
||||
"updateBankAccount": "Atualizar conta bancária",
|
||||
"connectFailed": "Algo deu errado. Tente novamente.",
|
||||
"flyerRemoveLogo": "Remover"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Aplicat automat la finalizarea comenzii",
|
||||
"expires": "Expiră la {date}",
|
||||
"referredBy": "Recomandat de {name}",
|
||||
"usingCode": "Cod: {code}"
|
||||
"usingCode": "Cod: {code}",
|
||||
"connectBankLoading": "Se configurează...",
|
||||
"connectDetailsNeeded": "Stripe are nevoie de informații suplimentare pentru a activa plățile. Fă clic pe \"Actualizează contul bancar\" mai jos pentru a finaliza configurarea.",
|
||||
"connectRefresh": "Se pare că nu ai terminat de configurat contul bancar. Fă clic mai jos pentru a încerca din nou.",
|
||||
"connectStatusActive": "Plăți activate",
|
||||
"connectStatusPending": "Configurare în curs",
|
||||
"connectStripeNote": "Vei fi redirecționat către site-ul securizat Stripe pentru a introduce detaliile bancare. Acest lucru durează de obicei câteva minute.",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Culori",
|
||||
"flyerDownloadHtml": "Descarcă HTML",
|
||||
"flyerDownloadPdf": "Descarcă PDF",
|
||||
"flyerDownloadPng": "Descarcă PNG",
|
||||
"flyerEditQr": "Editează stilul QR",
|
||||
"flyerExporting": "Se exportă...",
|
||||
"flyerHeadlineGradient": "Gradient titlu",
|
||||
"flyerHeadlineSubColor": "Subtitlu",
|
||||
"flyerMargins": "Margini pagină",
|
||||
"flyerPerPage": "Flyere pe pagină",
|
||||
"flyerPresetCustom": "Personalizat",
|
||||
"flyerPresetName": "Nume presetare",
|
||||
"flyerPresetSave": "Salvează presetarea",
|
||||
"flyerPrintLayout": "Aspect imprimare",
|
||||
"flyerSections": "Secțiuni",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Suprascrieri de text",
|
||||
"flyerToggleDivider": "Separator",
|
||||
"flyerToggleFeatures": "Funcții în partea de jos",
|
||||
"flyerToggleSteps": "Pașii „Cum funcționează”",
|
||||
"flyerToggleSubtitle": "Subtitlu",
|
||||
"flyerToggleTagline": "Slogan în partea de jos",
|
||||
"flyerUploadLogo": "Încarcă logo",
|
||||
"managePayouts": "Gestionează plățile",
|
||||
"payoutTitle": "Plăți și cont bancar",
|
||||
"tabFlyer": "Flyer imprimabil",
|
||||
"tabQrCode": "Cod QR",
|
||||
"toolsTitle": "Generator de coduri QR și flyere",
|
||||
"updateBankAccount": "Actualizează contul bancar",
|
||||
"connectFailed": "Ceva nu a mers bine. Te rog să încerci din nou.",
|
||||
"flyerRemoveLogo": "Elimină"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Применяется автоматически при оплате",
|
||||
"expires": "Действует до {date}",
|
||||
"referredBy": "Пригласил(а) {name}",
|
||||
"usingCode": "Код: {code}"
|
||||
"usingCode": "Код: {code}",
|
||||
"connectBankLoading": "Настройка...",
|
||||
"connectDetailsNeeded": "Для Stripe нужна дополнительная информация, чтобы включить выплаты. Нажми \"Обновить банковский счет\" ниже, чтобы завершить настройку.",
|
||||
"connectRefresh": "Похоже, настройка банковского счета не завершена. Нажми ниже, чтобы попробовать снова.",
|
||||
"connectStatusActive": "Выплаты включены",
|
||||
"connectStatusPending": "Настройка в процессе",
|
||||
"connectStripeNote": "Тебя перенаправят на безопасный сайт Stripe для ввода банковских реквизитов. Обычно это занимает пару минут.",
|
||||
"flyerAccentColor": "Акцент",
|
||||
"flyerBranding": "Брендинг",
|
||||
"flyerColors": "Цвета",
|
||||
"flyerDownloadHtml": "Скачать HTML",
|
||||
"flyerDownloadPdf": "Скачать PDF",
|
||||
"flyerDownloadPng": "Скачать PNG",
|
||||
"flyerEditQr": "Изменить стиль QR",
|
||||
"flyerExporting": "Экспорт...",
|
||||
"flyerHeadlineGradient": "Градиент заголовка",
|
||||
"flyerHeadlineSubColor": "Подзаголовок",
|
||||
"flyerMargins": "Поля страницы",
|
||||
"flyerPerPage": "Флаеров на странице",
|
||||
"flyerPresetCustom": "Пользовательский",
|
||||
"flyerPresetName": "Название пресета",
|
||||
"flyerPresetSave": "Сохранить пресет",
|
||||
"flyerPrintLayout": "Макет для печати",
|
||||
"flyerSections": "Разделы",
|
||||
"flyerSubtextColor": "Дополнительный текст",
|
||||
"flyerTextColor": "Текст",
|
||||
"flyerTextOverrides": "Замена текста",
|
||||
"flyerToggleDivider": "Разделитель",
|
||||
"flyerToggleFeatures": "Функции внизу",
|
||||
"flyerToggleSteps": "Шаги \"Как это работает\"",
|
||||
"flyerToggleSubtitle": "Подзаголовок",
|
||||
"flyerToggleTagline": "Нижний слоган",
|
||||
"flyerUploadLogo": "Загрузить логотип",
|
||||
"managePayouts": "Управление выплатами",
|
||||
"payoutTitle": "Выплаты и банковский счет",
|
||||
"tabFlyer": "Флаер для печати",
|
||||
"tabQrCode": "QR-код",
|
||||
"toolsTitle": "Generator QR-кодов и флаеров",
|
||||
"updateBankAccount": "Обновить банковский счет",
|
||||
"connectFailed": "Что-то пошло не так. Пожалуйста, попробуй еще раз.",
|
||||
"flyerRemoveLogo": "Удалить"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Automaticky uplatnené pri platbe",
|
||||
"expires": "Platnosť do {date}",
|
||||
"referredBy": "Odporučil/a {name}",
|
||||
"usingCode": "Kód: {code}"
|
||||
"usingCode": "Kód: {code}",
|
||||
"connectBankLoading": "Nastavuje sa...",
|
||||
"connectDetailsNeeded": "Stripe potrebuje ďalšie informácie na povolenie výplat. Pre dokončenie nastavenia klikni nižšie na „Aktualizovať bankový účet“.",
|
||||
"connectRefresh": "Zdá sa, že si nedokončil nastavenie svojho bankového účtu. Klikni nižšie a skús to znova.",
|
||||
"connectStatusActive": "Výplaty povolené",
|
||||
"connectStatusPending": "Prebieha nastavenie",
|
||||
"connectStripeNote": "Budeš presmerovaný na zabezpečenú stránku Stripe, kde zadáš svoje bankové údaje. Zvyčajne to trvá len pár minút.",
|
||||
"flyerAccentColor": "Akcent",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Farby",
|
||||
"flyerDownloadHtml": "Stiahnuť HTML",
|
||||
"flyerDownloadPdf": "Stiahnuť PDF",
|
||||
"flyerDownloadPng": "Stiahnuť PNG",
|
||||
"flyerEditQr": "Upraviť štýl QR",
|
||||
"flyerExporting": "Exportuje sa...",
|
||||
"flyerHeadlineGradient": "Prechod nadpisu",
|
||||
"flyerHeadlineSubColor": "Podnadpis",
|
||||
"flyerMargins": "Okraje strany",
|
||||
"flyerPerPage": "Letákov na stranu",
|
||||
"flyerPresetCustom": "Vlastné",
|
||||
"flyerPresetName": "Názov predvoľby",
|
||||
"flyerPresetSave": "Uložiť predvoľbu",
|
||||
"flyerPrintLayout": "Rozloženie tlače",
|
||||
"flyerSections": "Sekcie",
|
||||
"flyerSubtextColor": "Podtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Prepísanie textu",
|
||||
"flyerToggleDivider": "Oddeľovač",
|
||||
"flyerToggleFeatures": "Spodné funkcie",
|
||||
"flyerToggleSteps": "Kroky „Ako to funguje“",
|
||||
"flyerToggleSubtitle": "Podnadpis",
|
||||
"flyerToggleTagline": "Spodný slogan",
|
||||
"flyerUploadLogo": "Nahrať logo",
|
||||
"managePayouts": "Spravovať výplaty",
|
||||
"payoutTitle": "Výplaty a bankový účet",
|
||||
"tabFlyer": "Leták na tlač",
|
||||
"tabQrCode": "QR kód",
|
||||
"toolsTitle": "Generator QR kódov a letákov",
|
||||
"updateBankAccount": "Aktualizovať bankový účet",
|
||||
"connectFailed": "Niečo sa pokazilo. Skús to znova.",
|
||||
"flyerRemoveLogo": "Odstrániť"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Tillämpas automatiskt i kassan",
|
||||
"expires": "Går ut {date}",
|
||||
"referredBy": "Tipsad av {name}",
|
||||
"usingCode": "Kod: {code}"
|
||||
"usingCode": "Kod: {code}",
|
||||
"connectBankLoading": "Konfigurerar...",
|
||||
"connectDetailsNeeded": "Stripe behöver ytterligare information för att aktivera utbetalningar. Klicka på \"Uppdatera bankkonto\" nedan för att slutföra konfigurationen.",
|
||||
"connectRefresh": "Det verkar som att du inte blev klar med konfigurationen av ditt bankkonto. Klicka nedan för att försöka igen.",
|
||||
"connectStatusActive": "Utbetalningar aktiverade",
|
||||
"connectStatusPending": "Konfiguration pågår",
|
||||
"connectStripeNote": "Du kommer att omdirigeras till Stripes säkra webbplats för att ange dina bankuppgifter. Detta tar vanligtvis ett par minuter.",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerBranding": "Profilering",
|
||||
"flyerColors": "Färger",
|
||||
"flyerDownloadHtml": "Ladda ner HTML",
|
||||
"flyerDownloadPdf": "Ladda ner PDF",
|
||||
"flyerDownloadPng": "Ladda ner PNG",
|
||||
"flyerEditQr": "Redigera QR-stil",
|
||||
"flyerExporting": "Exporterar...",
|
||||
"flyerHeadlineGradient": "Rubrikövertoning",
|
||||
"flyerHeadlineSubColor": "Underrubrik",
|
||||
"flyerMargins": "Sidmarginaler",
|
||||
"flyerPerPage": "Flyers per sida",
|
||||
"flyerPresetCustom": "Anpassad",
|
||||
"flyerPresetName": "Namn på förinställning",
|
||||
"flyerPresetSave": "Spara förinställning",
|
||||
"flyerPrintLayout": "Utskriftslayout",
|
||||
"flyerSections": "Sektioner",
|
||||
"flyerSubtextColor": "Undertext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Anpassad text",
|
||||
"flyerToggleDivider": "Avdelare",
|
||||
"flyerToggleFeatures": "Funktioner längst ner",
|
||||
"flyerToggleSteps": "Steg för \"Så här fungerar det\"",
|
||||
"flyerToggleSubtitle": "Underrubrik",
|
||||
"flyerToggleTagline": "Slogan längst ner",
|
||||
"flyerUploadLogo": "Ladda upp logotyp",
|
||||
"managePayouts": "Hantera utbetalningar",
|
||||
"payoutTitle": "Utbetalningar & bankkonto",
|
||||
"tabFlyer": "Utskriftsvänlig flyer",
|
||||
"tabQrCode": "QR-kod",
|
||||
"toolsTitle": "QR-kod & Flyer Generator",
|
||||
"updateBankAccount": "Uppdatera bankkonto",
|
||||
"connectFailed": "Något gick fel. Försök igen.",
|
||||
"flyerRemoveLogo": "Ta bort"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "ใช้งานอัตโนมัติเมื่อชำระเงิน",
|
||||
"expires": "หมดอายุ {date}",
|
||||
"referredBy": "แนะนำโดย {name}",
|
||||
"usingCode": "รหัส: {code}"
|
||||
"usingCode": "รหัส: {code}",
|
||||
"connectBankLoading": "กำลังตั้งค่า...",
|
||||
"connectDetailsNeeded": "Stripe ต้องการข้อมูลเพิ่มเติมเพื่อเปิดใช้งานการรับเงิน คลิก \"อัปเดตบัญชีธนาคาร\" ด้านล่างเพื่อตั้งค่าให้เสร็จสมบูรณ์",
|
||||
"connectRefresh": "ดูเหมือนว่าคุณยังตั้งค่าบัญชีธนาคารไม่เสร็จสมบูรณ์ คลิกด้านล่างเพื่อลองอีกครั้ง",
|
||||
"connectStatusActive": "เปิดใช้งานการรับเงินแล้ว",
|
||||
"connectStatusPending": "กำลังดำเนินการตั้งค่า",
|
||||
"connectStripeNote": "คุณจะถูกเปลี่ยนหน้าไปยังเว็บไซต์ที่ปลอดภัยของ Stripe เพื่อกรอกข้อมูลธนาคารของคุณ ซึ่งมักจะใช้เวลาเพียงไม่กี่นาที",
|
||||
"flyerAccentColor": "สีเน้น",
|
||||
"flyerBranding": "แบรนด์",
|
||||
"flyerColors": "สี",
|
||||
"flyerDownloadHtml": "ดาวน์โหลด HTML",
|
||||
"flyerDownloadPdf": "ดาวน์โหลด PDF",
|
||||
"flyerDownloadPng": "ดาวน์โหลด PNG",
|
||||
"flyerEditQr": "แก้ไขสไตล์ QR",
|
||||
"flyerExporting": "กำลังส่งออก...",
|
||||
"flyerHeadlineGradient": "การไล่สีหัวข้อ",
|
||||
"flyerHeadlineSubColor": "สีหัวข้อรอง",
|
||||
"flyerMargins": "ระยะขอบหน้ากระดาษ",
|
||||
"flyerPerPage": "จำนวนใบปลิวต่อหน้า",
|
||||
"flyerPresetCustom": "กำหนดเอง",
|
||||
"flyerPresetName": "ชื่อพรีเซ็ต",
|
||||
"flyerPresetSave": "บันทึกพรีเซ็ต",
|
||||
"flyerPrintLayout": "เค้าโครงสำหรับพิมพ์",
|
||||
"flyerSections": "ส่วนต่างๆ",
|
||||
"flyerSubtextColor": "ข้อความรอง",
|
||||
"flyerTextColor": "ข้อความ",
|
||||
"flyerTextOverrides": "กำหนดข้อความเอง",
|
||||
"flyerToggleDivider": "เส้นคั่น",
|
||||
"flyerToggleFeatures": "ฟีเจอร์ด้านล่าง",
|
||||
"flyerToggleSteps": "ขั้นตอนการทำงาน",
|
||||
"flyerToggleSubtitle": "คำบรรยาย",
|
||||
"flyerToggleTagline": "สโลแกนด้านล่าง",
|
||||
"flyerUploadLogo": "อัปโหลดโลโก้",
|
||||
"managePayouts": "จัดการการรับเงิน",
|
||||
"payoutTitle": "การรับเงินและบัญชีธนาคาร",
|
||||
"tabFlyer": "ใบปลิวสำหรับพิมพ์",
|
||||
"tabQrCode": "QR Code",
|
||||
"toolsTitle": "QR Code & Flyer Generator",
|
||||
"updateBankAccount": "อัปเดตบัญชีธนาคาร",
|
||||
"connectFailed": "เกิดข้อผิดพลาดบางอย่าง โปรดลองอีกครั้ง",
|
||||
"flyerRemoveLogo": "นำออก"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Awtomatikong ia-apply sa checkout",
|
||||
"expires": "Mag-e-expire sa {date}",
|
||||
"referredBy": "Ni-refer ni {name}",
|
||||
"usingCode": "Code: {code}"
|
||||
"usingCode": "Code: {code}",
|
||||
"connectBankLoading": "Inihahanda...",
|
||||
"connectDetailsNeeded": "Kailangan ng Stripe ng karagdagang impormasyon para paganahin ang mga payout. I-click ang \"I-update ang Bank Account\" sa ibaba para makumpleto ang setup.",
|
||||
"connectRefresh": "Mukhang hindi mo natapos i-set up ang iyong bank account. I-click sa ibaba para subukang muli.",
|
||||
"connectStatusActive": "Aktibo ang mga payout",
|
||||
"connectStatusPending": "Kasalukuyang sini-set up",
|
||||
"connectStripeNote": "Ire-redirect ka sa secure na site ng Stripe para ilagay ang mga detalye ng iyong bangko. Karaniwang tumatagal ito ng ilang minuto.",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Mga Kulay",
|
||||
"flyerDownloadHtml": "I-download ang HTML",
|
||||
"flyerDownloadPdf": "I-download ang PDF",
|
||||
"flyerDownloadPng": "I-download ang PNG",
|
||||
"flyerEditQr": "I-edit ang Estilo ng QR",
|
||||
"flyerExporting": "Ini-export...",
|
||||
"flyerHeadlineGradient": "Gradient ng Headline",
|
||||
"flyerHeadlineSubColor": "Sub-color ng Headline",
|
||||
"flyerMargins": "Mga Margin ng Pahina",
|
||||
"flyerPerPage": "Mga Flyer Bawat Pahina",
|
||||
"flyerPresetCustom": "Custom",
|
||||
"flyerPresetName": "Pangalan ng preset",
|
||||
"flyerPresetSave": "I-save ang Preset",
|
||||
"flyerPrintLayout": "Layout ng Print",
|
||||
"flyerSections": "Mga Seksyon",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerTextColor": "Teksto",
|
||||
"flyerTextOverrides": "Mga Text Override",
|
||||
"flyerToggleDivider": "Divider",
|
||||
"flyerToggleFeatures": "Mga Feature sa Ibaba",
|
||||
"flyerToggleSteps": "Mga Hakbang Kung Paano Ito Gumagana",
|
||||
"flyerToggleSubtitle": "Subtitle",
|
||||
"flyerToggleTagline": "Tagline sa Ibaba",
|
||||
"flyerUploadLogo": "I-upload ang Logo",
|
||||
"managePayouts": "Pamahalaan ang mga Payout",
|
||||
"payoutTitle": "Mga Payout at Bank Account",
|
||||
"tabFlyer": "Napi-print na Flyer",
|
||||
"tabQrCode": "QR Code",
|
||||
"toolsTitle": "QR Code at Flyer Generator",
|
||||
"updateBankAccount": "I-update ang Bank Account",
|
||||
"connectFailed": "May nangyaring mali. Pakisubukan muli.",
|
||||
"flyerRemoveLogo": "Alisin"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Ödeme sırasında otomatik olarak uygulanır",
|
||||
"expires": "{date} tarihinde sona eriyor",
|
||||
"referredBy": "Öneren: {name}",
|
||||
"usingCode": "Kod: {code}"
|
||||
"usingCode": "Kod: {code}",
|
||||
"connectBankLoading": "Ayarlanıyor...",
|
||||
"connectDetailsNeeded": "Stripe'ın ödemeleri etkinleştirmek için ek bilgilere ihtiyacı var. Kurulumu tamamlamak için aşağıdaki \"Banka Hesabını Güncelle\"ye tıkla.",
|
||||
"connectRefresh": "Görünüşe göre banka hesabının kurulumunu tamamlamadın. Tekrar denemek için aşağıya tıkla.",
|
||||
"connectStatusActive": "Ödemeler etkinleştirildi",
|
||||
"connectStatusPending": "Kurulum devam ediyor",
|
||||
"connectStripeNote": "Banka bilgilerini girmek için Stripe'ın güvenli sitesine yönlendirileceksin. Bu genellikle birkaç dakika sürer.",
|
||||
"flyerAccentColor": "Vurgu",
|
||||
"flyerBranding": "Markalama",
|
||||
"flyerColors": "Renkler",
|
||||
"flyerDownloadHtml": "HTML İndir",
|
||||
"flyerDownloadPdf": "PDF İndir",
|
||||
"flyerDownloadPng": "PNG İndir",
|
||||
"flyerEditQr": "QR Stilini Düzenle",
|
||||
"flyerExporting": "Dışa aktarılıyor...",
|
||||
"flyerHeadlineGradient": "Başlık Degradesi",
|
||||
"flyerHeadlineSubColor": "Alt Başlık",
|
||||
"flyerMargins": "Sayfa Kenar Boşlukları",
|
||||
"flyerPerPage": "Sayfa Başına El İlanı",
|
||||
"flyerPresetCustom": "Özel",
|
||||
"flyerPresetName": "Ön ayar adı",
|
||||
"flyerPresetSave": "Ön Ayarı Kaydet",
|
||||
"flyerPrintLayout": "Yazdırma Düzeni",
|
||||
"flyerSections": "Bölümler",
|
||||
"flyerSubtextColor": "Alt Metin",
|
||||
"flyerTextColor": "Metin",
|
||||
"flyerTextOverrides": "Metin Değişiklikleri",
|
||||
"flyerToggleDivider": "Ayırıcı",
|
||||
"flyerToggleFeatures": "Alt Özellikler",
|
||||
"flyerToggleSteps": "Nasıl Çalışır Adımları",
|
||||
"flyerToggleSubtitle": "Alt Başlık",
|
||||
"flyerToggleTagline": "Alt Slogan",
|
||||
"flyerUploadLogo": "Logo Yükle",
|
||||
"managePayouts": "Ödemeleri Yönet",
|
||||
"payoutTitle": "Ödemeler ve Banka Hesabı",
|
||||
"tabFlyer": "Yazdırılabilir El İlanı",
|
||||
"tabQrCode": "QR Kodu",
|
||||
"toolsTitle": "QR Kodu ve El İlanı Generator",
|
||||
"updateBankAccount": "Banka Hesabını Güncelle",
|
||||
"connectFailed": "Bir şeyler ters gitti. Lütfen tekrar dene.",
|
||||
"flyerRemoveLogo": "Kaldır"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Застосовується автоматично під час оплати",
|
||||
"expires": "Діє до {date}",
|
||||
"referredBy": "За рекомендацією {name}",
|
||||
"usingCode": "Код: {code}"
|
||||
"usingCode": "Код: {code}",
|
||||
"connectBankLoading": "Налаштування...",
|
||||
"connectDetailsNeeded": "Для увімкнення виплат Stripe потрібна додаткова інформація. Натисни \"Оновити банківський рахунок\" нижче, щоб завершити налаштування.",
|
||||
"connectRefresh": "Схоже, налаштування банківського рахунку не завершено. Натисни нижче, щоб спробувати ще раз.",
|
||||
"connectStatusActive": "Виплати увімкнено",
|
||||
"connectStatusPending": "Налаштування в процесі",
|
||||
"connectStripeNote": "Тебе буде перенаправлено на безпечний сайт Stripe для введення банківських реквізитів. Зазвичай це займає кілька хвилин.",
|
||||
"flyerAccentColor": "Акцент",
|
||||
"flyerBranding": "Брендинг",
|
||||
"flyerColors": "Кольори",
|
||||
"flyerDownloadHtml": "Завантажити HTML",
|
||||
"flyerDownloadPdf": "Завантажити PDF",
|
||||
"flyerDownloadPng": "Завантажити PNG",
|
||||
"flyerEditQr": "Редагувати стиль QR",
|
||||
"flyerExporting": "Експорт...",
|
||||
"flyerHeadlineGradient": "Градієнт заголовка",
|
||||
"flyerHeadlineSubColor": "Підзаголовок",
|
||||
"flyerMargins": "Поля сторінки",
|
||||
"flyerPerPage": "Флаєрів на сторінку",
|
||||
"flyerPresetCustom": "Власний",
|
||||
"flyerPresetName": "Назва пресету",
|
||||
"flyerPresetSave": "Зберегти пресет",
|
||||
"flyerPrintLayout": "Макет для друку",
|
||||
"flyerSections": "Розділи",
|
||||
"flyerSubtextColor": "Додатковий текст",
|
||||
"flyerTextColor": "Текст",
|
||||
"flyerTextOverrides": "Заміна тексту",
|
||||
"flyerToggleDivider": "Розділювач",
|
||||
"flyerToggleFeatures": "Функції внизу",
|
||||
"flyerToggleSteps": "Кроки \"Як це працює\"",
|
||||
"flyerToggleSubtitle": "Підзаголовок",
|
||||
"flyerToggleTagline": "Нижній слоган",
|
||||
"flyerUploadLogo": "Завантажити логотип",
|
||||
"managePayouts": "Керування виплатами",
|
||||
"payoutTitle": "Виплати та банківський рахунок",
|
||||
"tabFlyer": "Флаєр для друку",
|
||||
"tabQrCode": "QR-код",
|
||||
"toolsTitle": "Generator QR-кодів та флаєрів",
|
||||
"updateBankAccount": "Оновити банківський рахунок",
|
||||
"connectFailed": "Щось пішло не так. Будь ласка, спробуй ще раз.",
|
||||
"flyerRemoveLogo": "Видалити"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "Tự động áp dụng khi thanh toán",
|
||||
"expires": "Hết hạn {date}",
|
||||
"referredBy": "Được giới thiệu bởi {name}",
|
||||
"usingCode": "Mã: {code}"
|
||||
"usingCode": "Mã: {code}",
|
||||
"connectBankLoading": "Đang thiết lập...",
|
||||
"connectDetailsNeeded": "Stripe cần thêm thông tin để bật tính năng nhận thanh toán. Nhấp vào \"Cập nhật tài khoản ngân hàng\" bên dưới để hoàn tất thiết lập.",
|
||||
"connectRefresh": "Có vẻ như bạn chưa hoàn tất việc thiết lập tài khoản ngân hàng của mình. Nhấp vào bên dưới để thử lại.",
|
||||
"connectStatusActive": "Đã bật nhận thanh toán",
|
||||
"connectStatusPending": "Đang thiết lập",
|
||||
"connectStripeNote": "Bạn sẽ được chuyển hướng đến trang web an toàn của Stripe để nhập thông tin ngân hàng của mình. Quá trình này thường mất vài phút.",
|
||||
"flyerAccentColor": "Màu nhấn",
|
||||
"flyerBranding": "Thương hiệu",
|
||||
"flyerColors": "Màu sắc",
|
||||
"flyerDownloadHtml": "Tải xuống HTML",
|
||||
"flyerDownloadPdf": "Tải xuống PDF",
|
||||
"flyerDownloadPng": "Tải xuống PNG",
|
||||
"flyerEditQr": "Chỉnh sửa kiểu QR",
|
||||
"flyerExporting": "Đang xuất...",
|
||||
"flyerHeadlineGradient": "Màu gradient tiêu đề",
|
||||
"flyerHeadlineSubColor": "Màu tiêu đề phụ",
|
||||
"flyerMargins": "Lề trang",
|
||||
"flyerPerPage": "Số tờ rơi mỗi trang",
|
||||
"flyerPresetCustom": "Tùy chỉnh",
|
||||
"flyerPresetName": "Tên thiết lập sẵn",
|
||||
"flyerPresetSave": "Lưu thiết lập sẵn",
|
||||
"flyerPrintLayout": "Bố cục in",
|
||||
"flyerSections": "Các phần",
|
||||
"flyerSubtextColor": "Văn bản phụ",
|
||||
"flyerTextColor": "Văn bản",
|
||||
"flyerTextOverrides": "Tùy chỉnh văn bản",
|
||||
"flyerToggleDivider": "Đường phân cách",
|
||||
"flyerToggleFeatures": "Tính năng bên dưới",
|
||||
"flyerToggleSteps": "Các bước thực hiện",
|
||||
"flyerToggleSubtitle": "Tiêu đề phụ",
|
||||
"flyerToggleTagline": "Khẩu hiệu bên dưới",
|
||||
"flyerUploadLogo": "Tải logo lên",
|
||||
"managePayouts": "Quản lý nhận thanh toán",
|
||||
"payoutTitle": "Nhận thanh toán & Tài khoản ngân hàng",
|
||||
"tabFlyer": "Tờ rơi để in",
|
||||
"tabQrCode": "Mã QR",
|
||||
"toolsTitle": "Generator Mã QR & Tờ rơi",
|
||||
"updateBankAccount": "Cập nhật tài khoản ngân hàng",
|
||||
"connectFailed": "Đã xảy ra lỗi. Vui lòng thử lại.",
|
||||
"flyerRemoveLogo": "Xóa"
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,46 @@
|
||||
"appliedAtCheckout": "结账时自动应用",
|
||||
"expires": "有效期至 {date}",
|
||||
"referredBy": "由 {name} 推荐",
|
||||
"usingCode": "优惠码:{code}"
|
||||
"usingCode": "优惠码:{code}",
|
||||
"connectBankLoading": "设置中...",
|
||||
"connectDetailsNeeded": "Stripe 需要更多信息才能启用提现。请点击下方的“更新银行账户”以完成设置。",
|
||||
"connectRefresh": "看来您尚未完成银行账户的设置。请点击下方重试。",
|
||||
"connectStatusActive": "提现已启用",
|
||||
"connectStatusPending": "设置进行中",
|
||||
"connectStripeNote": "您将被重定向到 Stripe 的安全网站以输入您的银行信息。这通常需要几分钟时间。",
|
||||
"flyerAccentColor": "强调色",
|
||||
"flyerBranding": "品牌",
|
||||
"flyerColors": "颜色",
|
||||
"flyerDownloadHtml": "下载 HTML",
|
||||
"flyerDownloadPdf": "下载 PDF",
|
||||
"flyerDownloadPng": "下载 PNG",
|
||||
"flyerEditQr": "编辑二维码样式",
|
||||
"flyerExporting": "导出中...",
|
||||
"flyerHeadlineGradient": "标题渐变色",
|
||||
"flyerHeadlineSubColor": "副标题颜色",
|
||||
"flyerMargins": "页面边距",
|
||||
"flyerPerPage": "每页传单数",
|
||||
"flyerPresetCustom": "自定义",
|
||||
"flyerPresetName": "预设名称",
|
||||
"flyerPresetSave": "保存预设",
|
||||
"flyerPrintLayout": "打印布局",
|
||||
"flyerSections": "版块",
|
||||
"flyerSubtextColor": "次要文本",
|
||||
"flyerTextColor": "文本",
|
||||
"flyerTextOverrides": "自定义文本",
|
||||
"flyerToggleDivider": "分隔线",
|
||||
"flyerToggleFeatures": "底部功能",
|
||||
"flyerToggleSteps": "使用步骤",
|
||||
"flyerToggleSubtitle": "副标题",
|
||||
"flyerToggleTagline": "底部标语",
|
||||
"flyerUploadLogo": "上传 Logo",
|
||||
"managePayouts": "管理提现",
|
||||
"payoutTitle": "提现与银行账户",
|
||||
"tabFlyer": "可打印传单",
|
||||
"tabQrCode": "二维码",
|
||||
"toolsTitle": "二维码与传单 Generator",
|
||||
"updateBankAccount": "更新银行账户",
|
||||
"connectFailed": "出了点问题,请重试。",
|
||||
"flyerRemoveLogo": "移除"
|
||||
}
|
||||
}
|
||||
Generated
+216
-3
@@ -45,8 +45,10 @@
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"embla-carousel-react": "8.5.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
"immer": "latest",
|
||||
"input-otp": "1.4.1",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^0.454.0",
|
||||
"next": "16.0.7",
|
||||
"next-intl": "^4.9.0",
|
||||
@@ -571,9 +573,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.28.4",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
|
||||
"integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
|
||||
"version": "7.29.2",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
|
||||
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
@@ -4696,6 +4698,19 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/pako": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
|
||||
"integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/raf": {
|
||||
"version": "3.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
|
||||
"integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz",
|
||||
@@ -4730,6 +4745,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@types/yargs": {
|
||||
"version": "17.0.35",
|
||||
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
|
||||
@@ -5879,6 +5901,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/base64-arraybuffer": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
|
||||
"integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.4.tgz",
|
||||
@@ -6052,6 +6083,26 @@
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/canvg": {
|
||||
"version": "3.0.11",
|
||||
"resolved": "https://registry.npmjs.org/canvg/-/canvg-3.0.11.tgz",
|
||||
"integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@types/raf": "^3.4.0",
|
||||
"core-js": "^3.8.3",
|
||||
"raf": "^3.4.1",
|
||||
"regenerator-runtime": "^0.13.7",
|
||||
"rgbcolor": "^1.0.1",
|
||||
"stackblur-canvas": "^2.0.0",
|
||||
"svg-pathdata": "^6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
@@ -6266,6 +6317,18 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/core-js": {
|
||||
"version": "3.49.0",
|
||||
"resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz",
|
||||
"integrity": "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/core-js"
|
||||
}
|
||||
},
|
||||
"node_modules/create-jest": {
|
||||
"version": "29.7.0",
|
||||
"resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz",
|
||||
@@ -6310,6 +6373,15 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/css-line-break": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz",
|
||||
"integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"utrie": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/css.escape": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
|
||||
@@ -6770,6 +6842,16 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.3.tgz",
|
||||
"integrity": "sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optional": true,
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
@@ -7718,6 +7800,17 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-png": {
|
||||
"version": "6.4.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz",
|
||||
"integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/pako": "^2.0.3",
|
||||
"iobuffer": "^5.3.2",
|
||||
"pako": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fastq": {
|
||||
"version": "1.20.1",
|
||||
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
|
||||
@@ -7738,6 +7831,12 @@
|
||||
"bser": "2.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.2",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
|
||||
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/file-entry-cache": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
||||
@@ -8239,6 +8338,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/html2canvas": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",
|
||||
"integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"css-line-break": "^2.1.0",
|
||||
"text-segmentation": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/http-proxy-agent": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz",
|
||||
@@ -8457,6 +8569,12 @@
|
||||
"@formatjs/icu-messageformat-parser": "3.5.3"
|
||||
}
|
||||
},
|
||||
"node_modules/iobuffer": {
|
||||
"version": "5.4.0",
|
||||
"resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz",
|
||||
"integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-array-buffer": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
|
||||
@@ -10000,6 +10118,23 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jspdf": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.1.tgz",
|
||||
"integrity": "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"fast-png": "^6.2.0",
|
||||
"fflate": "^0.8.1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"canvg": "^3.0.11",
|
||||
"core-js": "^3.6.0",
|
||||
"dompurify": "^3.3.1",
|
||||
"html2canvas": "^1.0.0-rc.5"
|
||||
}
|
||||
},
|
||||
"node_modules/jsx-ast-utils": {
|
||||
"version": "3.3.5",
|
||||
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
|
||||
@@ -11096,6 +11231,12 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
|
||||
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
|
||||
"license": "(MIT AND Zlib)"
|
||||
},
|
||||
"node_modules/parent-module": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
|
||||
@@ -11178,6 +11319,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/performance-now": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
|
||||
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -11476,6 +11624,16 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/raf": {
|
||||
"version": "3.4.1",
|
||||
"resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
|
||||
"integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"performance-now": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "19.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
|
||||
@@ -11719,6 +11877,13 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/regenerator-runtime": {
|
||||
"version": "0.13.11",
|
||||
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
|
||||
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/regexp.prototype.flags": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
|
||||
@@ -11832,6 +11997,16 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rgbcolor": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz",
|
||||
"integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==",
|
||||
"license": "MIT OR SEE LICENSE IN FEEL-FREE.md",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">= 0.8.15"
|
||||
}
|
||||
},
|
||||
"node_modules/run-parallel": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||
@@ -12257,6 +12432,16 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/stackblur-canvas": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz",
|
||||
"integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=0.1.14"
|
||||
}
|
||||
},
|
||||
"node_modules/stop-iteration-iterator": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
|
||||
@@ -12521,6 +12706,16 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/svg-pathdata": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz",
|
||||
"integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
@@ -12582,6 +12777,15 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/text-segmentation": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz",
|
||||
"integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"utrie": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/tiny-invariant": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
|
||||
@@ -13127,6 +13331,15 @@
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/utrie": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz",
|
||||
"integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-arraybuffer": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
|
||||
|
||||
@@ -67,8 +67,10 @@
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"embla-carousel-react": "8.5.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
"immer": "latest",
|
||||
"input-otp": "1.4.1",
|
||||
"jspdf": "^4.2.1",
|
||||
"lucide-react": "^0.454.0",
|
||||
"next": "16.0.7",
|
||||
"next-intl": "^4.9.0",
|
||||
|
||||
@@ -42,6 +42,7 @@ from modules import divebar_mirror, kn_data_sync, divebar_lookup, backup
|
||||
from modules import audio_separator_service
|
||||
from modules import gpu_artifact_registry
|
||||
from modules import encoding_worker_manager
|
||||
from modules import error_monitor as error_monitor_module
|
||||
from modules.iam import backend_sa, github_actions_sa, claude_automation_sa, claude_readonly_sa, worker_sas
|
||||
from compute import encoding_worker_vm, github_runners, divebar_sync_vm
|
||||
|
||||
@@ -181,6 +182,14 @@ lyrics_transcription_job = cloud_run.create_lyrics_transcription_job(bucket, bac
|
||||
audio_separation_job = cloud_run.create_audio_separation_job(bucket, backend_service_account)
|
||||
audio_download_job = cloud_run.create_audio_download_job(bucket, backend_service_account, vpc_connector)
|
||||
|
||||
# ==================== Error Monitor ====================
|
||||
|
||||
# Cloud Run Job + Cloud Scheduler for automated error detection and digest reports
|
||||
error_monitor_resources = error_monitor_module.create_error_monitor(
|
||||
backend_image=f"{REGION}-docker.pkg.dev/{PROJECT_ID}/karaoke-repo/karaoke-backend:latest",
|
||||
backend_sa_email=backend_service_account.email,
|
||||
)
|
||||
|
||||
# ==================== Monitoring ====================
|
||||
|
||||
# Alert policies
|
||||
@@ -668,3 +677,9 @@ pulumi.export("backup_function_url", backup_resources["function"].url)
|
||||
pulumi.export("backup_staging_bucket", backup_resources["staging_bucket"].name)
|
||||
pulumi.export("backup_scheduler_name", backup_resources["scheduler"].name)
|
||||
pulumi.export("backup_service_account", backup_resources["service_account"].email)
|
||||
|
||||
# Error Monitor
|
||||
pulumi.export("error_monitor_job_name", error_monitor_resources["job"].name)
|
||||
pulumi.export("error_monitor_scheduler_sa", error_monitor_resources["scheduler_sa"].email)
|
||||
pulumi.export("error_monitor_scheduler_name", error_monitor_resources["monitor_scheduler"].name)
|
||||
pulumi.export("error_monitor_digest_scheduler_name", error_monitor_resources["digest_scheduler"].name)
|
||||
@@ -133,3 +133,15 @@ class EncodingWorkerConfig:
|
||||
FUNCTION_NAME = "encoding-worker-idle-shutdown"
|
||||
FUNCTION_MEMORY = "256M"
|
||||
FUNCTION_TIMEOUT = 120 # 2 minutes
|
||||
|
||||
|
||||
class ErrorMonitorConfig:
|
||||
"""Configuration for the error monitor Cloud Run Job."""
|
||||
JOB_NAME = "nomad-error-monitor"
|
||||
MEMORY = "512Mi"
|
||||
CPU = "1"
|
||||
TIMEOUT = "300s"
|
||||
MAX_RETRIES = 0
|
||||
MONITOR_SCHEDULE = "*/15 * * * *" # Every 15 minutes UTC
|
||||
DIGEST_SCHEDULE = "0 8 * * *" # 08:00 UTC daily
|
||||
SCHEDULER_SA_NAME = "error-monitor-scheduler"
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Error Monitor Cloud Run Job and Cloud Scheduler resources.
|
||||
|
||||
Deploys the error monitor as a Cloud Run Job triggered by Cloud Scheduler
|
||||
every 15 minutes (error checks) and daily at 08:00 UTC (digest report).
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pulumi
|
||||
import pulumi_gcp as gcp
|
||||
from pulumi_gcp import cloudrunv2, cloudscheduler, serviceaccount
|
||||
|
||||
from config import PROJECT_ID, REGION, ErrorMonitorConfig
|
||||
|
||||
# Empty body for the monitor trigger (Cloud Run Jobs API requires POST body)
|
||||
_EMPTY_BODY_B64 = base64.b64encode(b"{}").decode()
|
||||
|
||||
# Digest trigger body — sets DIGEST_MODE=true via Cloud Run Job override
|
||||
_DIGEST_BODY_B64 = base64.b64encode(
|
||||
json.dumps({
|
||||
"overrides": {
|
||||
"containerOverrides": [
|
||||
{
|
||||
"env": [
|
||||
{"name": "DIGEST_MODE", "value": "true"},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}).encode()
|
||||
).decode()
|
||||
|
||||
|
||||
def create_error_monitor(
|
||||
backend_image: pulumi.Input[str],
|
||||
backend_sa_email: pulumi.Input[str],
|
||||
depends_on: list = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Create the error monitor Cloud Run Job and Cloud Scheduler triggers.
|
||||
|
||||
The error monitor runs as the backend SA (same permissions: Firestore,
|
||||
Secrets, Logging). A dedicated scheduler SA is created for Cloud Scheduler
|
||||
OAuth authentication.
|
||||
|
||||
Args:
|
||||
backend_image: Docker image URL for the backend (Artifact Registry).
|
||||
backend_sa_email: Email of the backend service account (runs the job).
|
||||
depends_on: Optional list of Pulumi resources to depend on.
|
||||
|
||||
Returns:
|
||||
dict with keys: 'job', 'scheduler_sa', 'monitor_scheduler', 'digest_scheduler'.
|
||||
"""
|
||||
job_opts = pulumi.ResourceOptions(depends_on=depends_on) if depends_on else None
|
||||
|
||||
# ---- Service Account for Cloud Scheduler ----
|
||||
# Scheduler SA authenticates when invoking the Cloud Run Job via OAuth token.
|
||||
scheduler_sa = serviceaccount.Account(
|
||||
"error-monitor-scheduler-sa",
|
||||
account_id=ErrorMonitorConfig.SCHEDULER_SA_NAME,
|
||||
display_name="Error Monitor Scheduler Service Account",
|
||||
)
|
||||
|
||||
# ---- Cloud Run Job ----
|
||||
error_monitor_job = cloudrunv2.Job(
|
||||
"error-monitor-job",
|
||||
name=ErrorMonitorConfig.JOB_NAME,
|
||||
location=REGION,
|
||||
template=cloudrunv2.JobTemplateArgs(
|
||||
template=cloudrunv2.JobTemplateTemplateArgs(
|
||||
containers=[
|
||||
cloudrunv2.JobTemplateTemplateContainerArgs(
|
||||
image=backend_image,
|
||||
args=["python", "-m", "backend.services.error_monitor.monitor"],
|
||||
resources=cloudrunv2.JobTemplateTemplateContainerResourcesArgs(
|
||||
limits={
|
||||
"cpu": ErrorMonitorConfig.CPU,
|
||||
"memory": ErrorMonitorConfig.MEMORY,
|
||||
},
|
||||
),
|
||||
envs=[
|
||||
# GCP project for Firestore, Logging, etc.
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="GCP_PROJECT_ID",
|
||||
value=PROJECT_ID,
|
||||
),
|
||||
# Environment tag for log filtering
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="ENVIRONMENT",
|
||||
value="production",
|
||||
),
|
||||
# Discord webhook for alert notifications
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="DISCORD_WEBHOOK_URL",
|
||||
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
|
||||
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
|
||||
secret=f"projects/{PROJECT_ID}/secrets/discord-alert-webhook",
|
||||
version="latest",
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
service_account=backend_sa_email,
|
||||
timeout=ErrorMonitorConfig.TIMEOUT,
|
||||
max_retries=ErrorMonitorConfig.MAX_RETRIES,
|
||||
),
|
||||
),
|
||||
opts=job_opts,
|
||||
)
|
||||
|
||||
# ---- IAM: grant scheduler SA permission to invoke (run) the job ----
|
||||
error_monitor_job_invoker = cloudrunv2.JobIamMember(
|
||||
"error-monitor-scheduler-invoker",
|
||||
project=PROJECT_ID,
|
||||
location=REGION,
|
||||
name=error_monitor_job.name,
|
||||
role="roles/run.invoker",
|
||||
member=scheduler_sa.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Cloud Run Jobs API endpoint — Cloud Scheduler calls this to trigger a run.
|
||||
# Format: https://run.googleapis.com/v2/projects/{project}/locations/{region}/jobs/{job}:run
|
||||
job_run_uri = error_monitor_job.name.apply(
|
||||
lambda name: (
|
||||
f"https://run.googleapis.com/v2/projects/{PROJECT_ID}"
|
||||
f"/locations/{REGION}/jobs/{name}:run"
|
||||
)
|
||||
)
|
||||
|
||||
# Shared opts: schedulers depend on IAM binding being in place first
|
||||
scheduler_opts = pulumi.ResourceOptions(depends_on=[error_monitor_job_invoker])
|
||||
|
||||
# ---- Cloud Scheduler: every-15-min monitor ----
|
||||
monitor_scheduler = cloudscheduler.Job(
|
||||
"error-monitor-scheduler",
|
||||
name="error-monitor-trigger",
|
||||
description="Trigger error monitor Cloud Run Job every 15 minutes",
|
||||
region=REGION,
|
||||
schedule=ErrorMonitorConfig.MONITOR_SCHEDULE,
|
||||
time_zone="UTC",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri=job_run_uri,
|
||||
http_method="POST",
|
||||
body=_EMPTY_BODY_B64,
|
||||
oauth_token=cloudscheduler.JobHttpTargetOauthTokenArgs(
|
||||
service_account_email=scheduler_sa.email,
|
||||
),
|
||||
),
|
||||
retry_config=cloudscheduler.JobRetryConfigArgs(
|
||||
retry_count=0,
|
||||
),
|
||||
opts=scheduler_opts,
|
||||
)
|
||||
|
||||
# ---- Cloud Scheduler: daily digest at 08:00 UTC ----
|
||||
# Passes DIGEST_MODE=true in the request body as a Cloud Run Job override.
|
||||
digest_scheduler = cloudscheduler.Job(
|
||||
"error-monitor-digest-scheduler",
|
||||
name="error-monitor-daily-digest",
|
||||
description="Trigger error monitor Cloud Run Job daily at 08:00 UTC for digest report",
|
||||
region=REGION,
|
||||
schedule=ErrorMonitorConfig.DIGEST_SCHEDULE,
|
||||
time_zone="UTC",
|
||||
http_target=cloudscheduler.JobHttpTargetArgs(
|
||||
uri=job_run_uri,
|
||||
http_method="POST",
|
||||
body=_DIGEST_BODY_B64,
|
||||
oauth_token=cloudscheduler.JobHttpTargetOauthTokenArgs(
|
||||
service_account_email=scheduler_sa.email,
|
||||
),
|
||||
),
|
||||
retry_config=cloudscheduler.JobRetryConfigArgs(
|
||||
retry_count=0,
|
||||
),
|
||||
opts=scheduler_opts,
|
||||
)
|
||||
|
||||
return {
|
||||
"job": error_monitor_job,
|
||||
"scheduler_sa": scheduler_sa,
|
||||
"monitor_scheduler": monitor_scheduler,
|
||||
"digest_scheduler": digest_scheduler,
|
||||
}
|
||||
@@ -120,6 +120,14 @@ def grant_backend_permissions(
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
# Cloud Logging Viewer - error monitor reads Cloud Logging for error detection
|
||||
bindings["logging_viewer"] = gcp.projects.IAMMember(
|
||||
"karaoke-backend-logging-viewer",
|
||||
project=PROJECT_ID,
|
||||
role="roles/logging.viewer",
|
||||
member=service_account.email.apply(lambda email: f"serviceAccount:{email}"),
|
||||
)
|
||||
|
||||
return bindings
|
||||
|
||||
|
||||
|
||||
Generated
+66
-1
@@ -2546,6 +2546,44 @@ requests-oauthlib = ">=0.7.0"
|
||||
[package.extras]
|
||||
tool = ["click (>=6.0.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-appengine-logging"
|
||||
version = "1.9.0"
|
||||
description = "Google Cloud Appengine Logging API client library"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "google_cloud_appengine_logging-1.9.0-py3-none-any.whl", hash = "sha256:bbf3a7e4dc171678f7f481259d1f68c3ae7d337530f1f2361f8a0b214dbcfe36"},
|
||||
{file = "google_cloud_appengine_logging-1.9.0.tar.gz", hash = "sha256:ff397f0bbc1485f979ab45767c38e0f676c9598c97c384f7412216e6ea22f805"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
google-api-core = {version = ">=2.11.0,<3.0.0", extras = ["grpc"]}
|
||||
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
|
||||
grpcio = ">=1.33.2,<2.0.0"
|
||||
proto-plus = [
|
||||
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
|
||||
{version = ">=1.22.3,<2.0.0"},
|
||||
]
|
||||
protobuf = ">=4.25.8,<8.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-audit-log"
|
||||
version = "0.5.0"
|
||||
description = "Google Cloud Audit Protos"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "google_cloud_audit_log-0.5.0-py3-none-any.whl", hash = "sha256:3f4632f25bf67446fa9085c52868f3cb42fb1afbab9489ba8978e30991afc79f"},
|
||||
{file = "google_cloud_audit_log-0.5.0.tar.gz", hash = "sha256:3b32d5e77db634c46fbd6c5e01f5bda836f420dfbb21d730501c75e9fab4e4a4"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
googleapis-common-protos = ">=1.56.2,<2.0.0"
|
||||
protobuf = ">=4.25.8,<8.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-compute"
|
||||
version = "1.46.0"
|
||||
@@ -2610,6 +2648,33 @@ proto-plus = [
|
||||
]
|
||||
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-logging"
|
||||
version = "3.15.0"
|
||||
description = "Google Cloud Logging API client library"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "google_cloud_logging-3.15.0-py3-none-any.whl", hash = "sha256:7dcc67434c4e7181510c133d5ac8fd4ce60c23fa4158661f67e54bf440c32450"},
|
||||
{file = "google_cloud_logging-3.15.0.tar.gz", hash = "sha256:72168a1e98bbfc27c75f0b8f630a7f5d786065f3f1f7e9e53d2d787a03693a4a"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
google-api-core = {version = ">=2.11.0,<3.0.0", extras = ["grpc"]}
|
||||
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
|
||||
google-cloud-appengine-logging = ">=0.1.3,<2.0.0"
|
||||
google-cloud-audit-log = ">=0.3.1,<1.0.0"
|
||||
google-cloud-core = ">=2.0.0,<3.0.0"
|
||||
grpc-google-iam-v1 = ">=0.12.4,<1.0.0"
|
||||
grpcio = ">=1.33.2,<2.0.0"
|
||||
opentelemetry-api = ">=1.9.0"
|
||||
proto-plus = [
|
||||
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
|
||||
{version = ">=1.22.3,<2.0.0"},
|
||||
]
|
||||
protobuf = ">=4.25.8,<8.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "google-cloud-monitoring"
|
||||
version = "2.29.1"
|
||||
@@ -10702,4 +10767,4 @@ local-whisper = ["whisper-timestamped"]
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.10,<3.14"
|
||||
content-hash = "fd26762a0d3f754ddc150bb24dc6d1ee1a15cb8154584950b213029751315ed2"
|
||||
content-hash = "7b0bb0bf110afca09d3d7e7c7b829777091be76916b4a29add8ecbcf50372eef"
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.166.3"
|
||||
version = "0.169.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
@@ -94,10 +94,11 @@ google-cloud-secret-manager = "2.26.0"
|
||||
google-cloud-monitoring = "2.29.1" # Cloud Monitoring for YouTube API quota metrics
|
||||
google-cloud-tasks = "2.21.0" # Cloud Tasks for worker coordination (Phase 1 scalability)
|
||||
google-cloud-run = "0.15.0" # Cloud Run Jobs for long-running video encoding (Phase 2 scalability)
|
||||
google-cloud-logging = ">=3.9.0" # Cloud Logging for error monitoring
|
||||
python-dotenv = ">=1.0.0"
|
||||
pydub = ">=0.25.1"
|
||||
# Payment and email services
|
||||
stripe = ">=7.0.0"
|
||||
stripe = "^14.1.0"
|
||||
sendgrid = ">=6.10.0"
|
||||
email-validator = ">=2.0.0" # For Pydantic EmailStr validation
|
||||
# Web Push notifications
|
||||
|
||||
Executable
+193
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Query error patterns from Firestore.
|
||||
|
||||
Usage:
|
||||
python scripts/query-error-patterns.py # All active
|
||||
python scripts/query-error-patterns.py --status new # Only new
|
||||
python scripts/query-error-patterns.py --service karaoke-backend
|
||||
python scripts/query-error-patterns.py --hours 24 # Last 24h
|
||||
python scripts/query-error-patterns.py --json # JSON output
|
||||
|
||||
Requires:
|
||||
- google-cloud-firestore
|
||||
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
|
||||
ACTIVE_STATUSES = ["new", "acknowledged", "known"]
|
||||
|
||||
|
||||
def query_error_patterns(
|
||||
status: Optional[str] = None,
|
||||
service: Optional[str] = None,
|
||||
hours: Optional[int] = None,
|
||||
output_json: bool = False,
|
||||
project: str = "nomadkaraoke",
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Query error patterns from Firestore.
|
||||
|
||||
Args:
|
||||
status: Filter by status (new/acknowledged/known/fixed). Default: active (new/acknowledged/known).
|
||||
service: Filter by service name.
|
||||
hours: Only return patterns last seen within this many hours.
|
||||
output_json: Print JSON output instead of a table.
|
||||
project: GCP project ID.
|
||||
|
||||
Returns:
|
||||
List of pattern dicts.
|
||||
"""
|
||||
db = firestore.Client(project=project)
|
||||
query = db.collection("error_patterns")
|
||||
|
||||
# Status filter
|
||||
if status:
|
||||
query = query.where(filter=FieldFilter("status", "==", status))
|
||||
else:
|
||||
query = query.where(filter=FieldFilter("status", "in", ACTIVE_STATUSES))
|
||||
|
||||
# Service filter
|
||||
if service:
|
||||
query = query.where(filter=FieldFilter("service", "==", service))
|
||||
|
||||
# Fetch all matching docs (streaming)
|
||||
patterns = []
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
data["_id"] = doc.id
|
||||
patterns.append(data)
|
||||
|
||||
# Hours filter (applied in Python — Firestore requires composite index for multi-field filters)
|
||||
if hours is not None:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||
filtered = []
|
||||
for p in patterns:
|
||||
last_seen = p.get("last_seen")
|
||||
if last_seen is not None:
|
||||
# Firestore Timestamps have a .timestamp() method
|
||||
ts = last_seen.timestamp() if hasattr(last_seen, "timestamp") else float(last_seen)
|
||||
if ts >= cutoff.timestamp():
|
||||
filtered.append(p)
|
||||
patterns = filtered
|
||||
|
||||
# Sort by last_seen descending (most recent first)
|
||||
def sort_key(p):
|
||||
ls = p.get("last_seen")
|
||||
if ls is None:
|
||||
return 0.0
|
||||
return ls.timestamp() if hasattr(ls, "timestamp") else float(ls)
|
||||
|
||||
patterns.sort(key=sort_key, reverse=True)
|
||||
|
||||
if output_json:
|
||||
print(json.dumps(patterns, indent=2, default=str))
|
||||
else:
|
||||
_print_table(patterns)
|
||||
|
||||
return patterns
|
||||
|
||||
|
||||
def _fmt_last_seen(value) -> str:
|
||||
"""Return first 19 chars of ISO timestamp, or empty string."""
|
||||
if value is None:
|
||||
return ""
|
||||
if hasattr(value, "isoformat"):
|
||||
return value.isoformat()[:19]
|
||||
return str(value)[:19]
|
||||
|
||||
|
||||
def _print_table(patterns: list[dict[str, Any]]) -> None:
|
||||
"""Print patterns as a human-readable table."""
|
||||
if not patterns:
|
||||
print("No error patterns found.")
|
||||
return
|
||||
|
||||
# Column widths
|
||||
col_status = 14
|
||||
col_service = 24
|
||||
col_count = 6
|
||||
col_last_seen = 19
|
||||
col_message = 50
|
||||
|
||||
header = (
|
||||
f"{'Status':<{col_status}} "
|
||||
f"{'Service':<{col_service}} "
|
||||
f"{'Count':>{col_count}} "
|
||||
f"{'Last Seen':<{col_last_seen}} "
|
||||
f"{'Message':<{col_message}}"
|
||||
)
|
||||
separator = "-" * len(header)
|
||||
|
||||
print(separator)
|
||||
print(header)
|
||||
print(separator)
|
||||
|
||||
for p in patterns:
|
||||
status = str(p.get("status", ""))[:col_status]
|
||||
service = str(p.get("service", ""))[:col_service]
|
||||
count = p.get("total_count", p.get("occurrence_count", p.get("count", 0)))
|
||||
last_seen = _fmt_last_seen(p.get("last_seen"))
|
||||
message = str(p.get("normalized_message", p.get("error_message", p.get("message", ""))))[:col_message]
|
||||
|
||||
print(
|
||||
f"{status:<{col_status}} "
|
||||
f"{service:<{col_service}} "
|
||||
f"{count:>{col_count}} "
|
||||
f"{last_seen:<{col_last_seen}} "
|
||||
f"{message:<{col_message}}"
|
||||
)
|
||||
|
||||
print(separator)
|
||||
print(f"Total: {len(patterns)} pattern(s)")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Query error patterns from Firestore"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--status",
|
||||
help="Filter by status (new/acknowledged/known/fixed). Default: active patterns.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--service",
|
||||
help="Filter by service name (e.g. karaoke-backend).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--hours",
|
||||
type=int,
|
||||
help="Only show patterns last seen within this many hours.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
dest="output_json",
|
||||
help="Output as JSON.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--project",
|
||||
default="nomadkaraoke",
|
||||
help="GCP project ID (default: nomadkaraoke).",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
query_error_patterns(
|
||||
status=args.status,
|
||||
service=args.service,
|
||||
hours=args.hours,
|
||||
output_json=args.output_json,
|
||||
project=args.project,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Resolve an error pattern by marking it as fixed.
|
||||
|
||||
Usage:
|
||||
python scripts/resolve-error-pattern.py <pattern_prefix> --pr 42 --note "Fixed timeout"
|
||||
python scripts/resolve-error-pattern.py <pattern_prefix> --note "Added retry logic"
|
||||
|
||||
Requires:
|
||||
- google-cloud-firestore
|
||||
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
|
||||
def resolve_error_pattern(
|
||||
pattern_prefix: str,
|
||||
note: str,
|
||||
pr: Optional[int] = None,
|
||||
repo: str = "nomadkaraoke/karaoke-gen",
|
||||
project: str = "nomadkaraoke",
|
||||
) -> bool:
|
||||
"""
|
||||
Find an error pattern by ID prefix and mark it as fixed.
|
||||
|
||||
Args:
|
||||
pattern_prefix: Prefix of the pattern document ID.
|
||||
note: Resolution note explaining how it was fixed.
|
||||
pr: Optional PR number that fixed the issue.
|
||||
repo: GitHub repo slug used to build the PR URL.
|
||||
project: GCP project ID.
|
||||
|
||||
Returns:
|
||||
True if the pattern was resolved, False otherwise.
|
||||
"""
|
||||
try:
|
||||
db = firestore.Client(project=project)
|
||||
collection = db.collection("error_patterns")
|
||||
except Exception as exc:
|
||||
print(f"Error: Could not connect to Firestore (project={project}): {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
# Stream all docs and find those whose ID starts with the prefix
|
||||
matches = []
|
||||
try:
|
||||
for doc in collection.stream():
|
||||
if doc.id.startswith(pattern_prefix):
|
||||
matches.append(doc)
|
||||
except Exception as exc:
|
||||
print(f"Error: Could not query error_patterns: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
if len(matches) == 0:
|
||||
print(f"Error: No pattern found with ID prefix '{pattern_prefix}'", file=sys.stderr)
|
||||
return False
|
||||
|
||||
if len(matches) > 1:
|
||||
print(
|
||||
f"Ambiguous prefix '{pattern_prefix}' — matches {len(matches)} pattern(s). "
|
||||
"Please provide a longer prefix.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print("\nFirst 5 matches:", file=sys.stderr)
|
||||
for doc in matches[:5]:
|
||||
data = doc.to_dict()
|
||||
service = data.get("service", "")
|
||||
message = str(data.get("error_message", data.get("message", "")))[:60]
|
||||
print(f" {doc.id} [{service}] {message}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
doc = matches[0]
|
||||
data = doc.to_dict()
|
||||
resolved_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
fixed_by: dict = {
|
||||
"resolved_at": resolved_at,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
if pr is not None:
|
||||
pr_url = f"https://github.com/{repo}/pull/{pr}"
|
||||
fixed_by["pr_url"] = pr_url
|
||||
fixed_by["pr_display"] = f"#{pr}"
|
||||
|
||||
update_payload = {
|
||||
"status": "fixed",
|
||||
"fixed_by": fixed_by,
|
||||
}
|
||||
|
||||
try:
|
||||
doc.reference.update(update_payload)
|
||||
except Exception as exc:
|
||||
print(f"Error: Could not update pattern {doc.id}: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
# Confirmation output
|
||||
service = data.get("service", "")
|
||||
message = str(data.get("error_message", data.get("message", "")))[:80]
|
||||
print(f"Resolved pattern: {doc.id}")
|
||||
print(f" Service: {service}")
|
||||
print(f" Message: {message}")
|
||||
print(f" Status: fixed")
|
||||
print(f" Note: {note}")
|
||||
if pr is not None:
|
||||
print(f" PR: {fixed_by['pr_url']}")
|
||||
print(f" Resolved: {resolved_at}")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Resolve an error pattern by marking it as fixed"
|
||||
)
|
||||
parser.add_argument(
|
||||
"pattern_prefix",
|
||||
help="Prefix of the error pattern document ID.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--note",
|
||||
required=True,
|
||||
help="Resolution note (e.g. 'Fixed timeout in encoding worker').",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--pr",
|
||||
type=int,
|
||||
help="PR number that fixed the issue (optional).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--repo",
|
||||
default="nomadkaraoke/karaoke-gen",
|
||||
help="GitHub repo slug for PR URL (default: nomadkaraoke/karaoke-gen).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--project",
|
||||
default="nomadkaraoke",
|
||||
help="GCP project ID (default: nomadkaraoke).",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
success = resolve_error_pattern(
|
||||
pattern_prefix=args.pattern_prefix,
|
||||
note=args.note,
|
||||
pr=args.pr,
|
||||
repo=args.repo,
|
||||
project=args.project,
|
||||
)
|
||||
|
||||
if not success:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Whitespace-only changes.
@@ -0,0 +1,269 @@
|
||||
"""Tests for error_monitor.config module."""
|
||||
|
||||
import os
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestMonitoredServiceLists:
|
||||
"""Tests that all monitored service lists have the expected entries."""
|
||||
|
||||
def test_cloud_run_services_count(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert len(config.MONITORED_CLOUD_RUN_SERVICES) == 3
|
||||
|
||||
def test_cloud_run_services_contains_expected(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert "karaoke-backend" in config.MONITORED_CLOUD_RUN_SERVICES
|
||||
assert "karaoke-decide" in config.MONITORED_CLOUD_RUN_SERVICES
|
||||
assert "audio-separator" in config.MONITORED_CLOUD_RUN_SERVICES
|
||||
|
||||
def test_cloud_run_jobs_count(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert len(config.MONITORED_CLOUD_RUN_JOBS) == 4
|
||||
|
||||
def test_cloud_run_jobs_contains_expected(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert "video-encoding-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "lyrics-transcription-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "audio-separation-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
assert "audio-download-job" in config.MONITORED_CLOUD_RUN_JOBS
|
||||
|
||||
def test_cloud_functions_count_at_least_7(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert len(config.MONITORED_CLOUD_FUNCTIONS) >= 7
|
||||
|
||||
def test_cloud_functions_contains_expected(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
expected = [
|
||||
"gdrive-validator",
|
||||
"runner_manager",
|
||||
"backup_to_aws",
|
||||
"divebar_mirror",
|
||||
"kn_data_sync",
|
||||
"divebar_lookup",
|
||||
"encoding_worker_idle",
|
||||
]
|
||||
for fn in expected:
|
||||
assert fn in config.MONITORED_CLOUD_FUNCTIONS, f"Expected '{fn}' in MONITORED_CLOUD_FUNCTIONS"
|
||||
|
||||
def test_gce_instances_count_at_least_4(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert len(config.MONITORED_GCE_INSTANCES) >= 4
|
||||
|
||||
def test_gce_instances_contains_expected(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
expected = [
|
||||
"encoding-worker-a",
|
||||
"encoding-worker-b",
|
||||
"flacfetch-vm",
|
||||
"divebar-sync-vm",
|
||||
]
|
||||
for instance in expected:
|
||||
assert instance in config.MONITORED_GCE_INSTANCES, f"Expected '{instance}' in MONITORED_GCE_INSTANCES"
|
||||
|
||||
|
||||
class TestDefaultValues:
|
||||
"""Tests that config module exposes correct default constants."""
|
||||
|
||||
def test_gcp_project_default(self):
|
||||
with mock.patch.dict(os.environ, {}, clear=False):
|
||||
# Remove GCP_PROJECT if set, then re-import via reload
|
||||
env = {k: v for k, v in os.environ.items() if k != "GCP_PROJECT"}
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
import importlib
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.GCP_PROJECT == "nomadkaraoke"
|
||||
|
||||
def test_lookback_minutes_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.LOOKBACK_MINUTES == 15
|
||||
|
||||
def test_max_log_entries_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.MAX_LOG_ENTRIES == 500
|
||||
|
||||
def test_spike_multiplier_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.SPIKE_MULTIPLIER == 5.0
|
||||
|
||||
def test_spike_min_count_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.SPIKE_MIN_COUNT == 5
|
||||
|
||||
def test_auto_resolve_multiplier_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.AUTO_RESOLVE_MULTIPLIER == 8
|
||||
|
||||
def test_max_discord_messages_per_run_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.MAX_DISCORD_MESSAGES_PER_RUN == 10
|
||||
|
||||
def test_discord_max_message_length_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.DISCORD_MAX_MESSAGE_LENGTH == 2000
|
||||
|
||||
def test_max_active_patterns_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.MAX_ACTIVE_PATTERNS == 500
|
||||
|
||||
def test_rolling_window_days_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.ROLLING_WINDOW_DAYS == 7
|
||||
|
||||
def test_max_normalized_message_length_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.MAX_NORMALIZED_MESSAGE_LENGTH == 200
|
||||
|
||||
def test_min_patterns_for_analysis_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert isinstance(config.MIN_PATTERNS_FOR_ANALYSIS, int)
|
||||
assert config.MIN_PATTERNS_FOR_ANALYSIS >= 1
|
||||
|
||||
def test_auto_resolve_min_hours(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.AUTO_RESOLVE_MIN_HOURS == 6
|
||||
|
||||
def test_auto_resolve_max_hours(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.AUTO_RESOLVE_MAX_HOURS == 168 # 1 week
|
||||
|
||||
def test_auto_resolve_fallback_hours(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert config.AUTO_RESOLVE_FALLBACK_HOURS == 48
|
||||
|
||||
def test_service_dependency_map_is_string(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert isinstance(config.SERVICE_DEPENDENCY_MAP, str)
|
||||
assert len(config.SERVICE_DEPENDENCY_MAP) > 0
|
||||
assert "karaoke-backend" in config.SERVICE_DEPENDENCY_MAP
|
||||
|
||||
def test_llm_analysis_model_is_string(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert isinstance(config.LLM_ANALYSIS_MODEL, str)
|
||||
assert len(config.LLM_ANALYSIS_MODEL) > 0
|
||||
|
||||
def test_llm_vertex_location_is_string(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert isinstance(config.LLM_VERTEX_LOCATION, str)
|
||||
assert len(config.LLM_VERTEX_LOCATION) > 0
|
||||
|
||||
|
||||
class TestEnvVarOverrides:
|
||||
"""Tests that environment variable overrides work correctly."""
|
||||
|
||||
def test_llm_analysis_enabled_default_is_false(self):
|
||||
"""LLM_ANALYSIS_ENABLED should default to False when env var is not set."""
|
||||
import importlib
|
||||
env = {k: v for k, v in os.environ.items() if k != "LLM_ANALYSIS_ENABLED"}
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_llm_enabled() is False
|
||||
|
||||
def test_llm_analysis_enabled_true_when_env_var_set(self):
|
||||
"""get_llm_enabled() should return True when LLM_ANALYSIS_ENABLED=true."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"LLM_ANALYSIS_ENABLED": "true"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_llm_enabled() is True
|
||||
|
||||
def test_llm_analysis_enabled_true_when_env_var_set_uppercase(self):
|
||||
"""get_llm_enabled() should handle case-insensitive 'TRUE'."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"LLM_ANALYSIS_ENABLED": "TRUE"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_llm_enabled() is True
|
||||
|
||||
def test_llm_analysis_enabled_false_when_env_var_set_false(self):
|
||||
"""get_llm_enabled() should return False when LLM_ANALYSIS_ENABLED=false."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"LLM_ANALYSIS_ENABLED": "false"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_llm_enabled() is False
|
||||
|
||||
def test_gcp_project_overridable_via_env(self):
|
||||
"""GCP_PROJECT should pick up the GCP_PROJECT environment variable."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"GCP_PROJECT": "my-test-project"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.GCP_PROJECT == "my-test-project"
|
||||
|
||||
def test_gcp_region_has_default(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
assert isinstance(config.GCP_REGION, str)
|
||||
assert len(config.GCP_REGION) > 0
|
||||
|
||||
def test_gcp_region_overridable_via_env(self):
|
||||
"""GCP_REGION should pick up the GCP_REGION environment variable."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"GCP_REGION": "europe-west1"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.GCP_REGION == "europe-west1"
|
||||
|
||||
|
||||
class TestHelperFunctions:
|
||||
"""Tests for config helper functions."""
|
||||
|
||||
def test_get_discord_webhook_secret_name_returns_string(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
result = config.get_discord_webhook_secret_name()
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
def test_get_digest_mode_returns_bool(self):
|
||||
from backend.services.error_monitor import config
|
||||
|
||||
result = config.get_digest_mode()
|
||||
assert isinstance(result, bool)
|
||||
|
||||
def test_get_digest_mode_default_false(self):
|
||||
"""DIGEST_MODE should default to False."""
|
||||
import importlib
|
||||
env = {k: v for k, v in os.environ.items() if k != "DIGEST_MODE"}
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_digest_mode() is False
|
||||
|
||||
def test_get_digest_mode_true_when_env_set(self):
|
||||
"""get_digest_mode() should return True when DIGEST_MODE=true."""
|
||||
import importlib
|
||||
with mock.patch.dict(os.environ, {"DIGEST_MODE": "true"}):
|
||||
from backend.services.error_monitor import config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.get_digest_mode() is True
|
||||
@@ -0,0 +1,619 @@
|
||||
"""Tests for error_monitor.discord module."""
|
||||
|
||||
from datetime import datetime
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
|
||||
class TestFormatNewPatternAlert:
|
||||
"""Tests for format_new_pattern_alert formatting function."""
|
||||
|
||||
def test_contains_service_name(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Connection refused",
|
||||
sample_message="Connection refused to db at 192.168.1.1",
|
||||
count=5,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "karaoke-backend" in result
|
||||
|
||||
def test_contains_normalized_message(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Connection refused",
|
||||
sample_message="Connection refused to db at 192.168.1.1",
|
||||
count=5,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "Connection refused" in result
|
||||
|
||||
def test_contains_red_circle_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Connection refused",
|
||||
sample_message="Connection refused to db",
|
||||
count=3,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "🔴" in result
|
||||
|
||||
def test_contains_prod_investigate_prompt(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Connection refused",
|
||||
sample_message="Connection refused to db",
|
||||
count=3,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "/prod-investigate" in result
|
||||
|
||||
def test_truncates_long_message(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
from backend.services.error_monitor.config import DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
very_long_message = "x" * 3000
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message=very_long_message,
|
||||
sample_message="sample",
|
||||
count=1,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert len(result) <= DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
def test_contains_count(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Timeout error",
|
||||
sample_message="Timeout after 30s",
|
||||
count=42,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "42" in result
|
||||
|
||||
def test_contains_first_seen(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Timeout error",
|
||||
sample_message="Timeout after 30s",
|
||||
count=1,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "2026-04-10T12:00:00Z" in result
|
||||
|
||||
def test_contains_sample_message(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="karaoke-backend",
|
||||
resource_type="cloud_run_service",
|
||||
normalized_message="Timeout error",
|
||||
sample_message="Timeout after 30s on job xyz",
|
||||
count=1,
|
||||
first_seen="2026-04-10T12:00:00Z",
|
||||
)
|
||||
assert "Timeout after 30s on job xyz" in result
|
||||
|
||||
def test_contains_resource_type_label(self):
|
||||
from backend.services.error_monitor.discord import format_new_pattern_alert
|
||||
|
||||
result = format_new_pattern_alert(
|
||||
service="encoding-worker-a",
|
||||
resource_type="gce_instance",
|
||||
normalized_message="Disk full",
|
||||
sample_message="No space left on device",
|
||||
count=2,
|
||||
first_seen="2026-04-10T08:00:00Z",
|
||||
)
|
||||
# Resource type should appear somewhere in the message
|
||||
assert "gce_instance" in result or "GCE" in result or "VM" in result or "Instance" in result
|
||||
|
||||
|
||||
class TestFormatIncidentAlert:
|
||||
"""Tests for format_incident_alert formatting function."""
|
||||
|
||||
def test_p0_uses_siren_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="Database down",
|
||||
severity="P0",
|
||||
root_cause="Firestore quota exceeded",
|
||||
suggested_fix="Increase quota",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "🚨" in result
|
||||
|
||||
def test_p1_uses_red_circle(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="High error rate",
|
||||
severity="P1",
|
||||
root_cause="Memory pressure",
|
||||
suggested_fix="Scale up",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "🔴" in result
|
||||
|
||||
def test_p2_uses_warning_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="Elevated latency",
|
||||
severity="P2",
|
||||
root_cause="Slow queries",
|
||||
suggested_fix="Add index",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "⚠️" in result
|
||||
|
||||
def test_p3_uses_yellow_circle(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="Minor degradation",
|
||||
severity="P3",
|
||||
root_cause="Cache miss",
|
||||
suggested_fix="Warm cache",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "🟡" in result
|
||||
|
||||
def test_contains_title(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="My Special Incident Title",
|
||||
severity="P1",
|
||||
root_cause="Something broke",
|
||||
suggested_fix="Fix the thing",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "My Special Incident Title" in result
|
||||
|
||||
def test_contains_root_cause(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="Incident",
|
||||
severity="P1",
|
||||
root_cause="The root cause explanation here",
|
||||
suggested_fix="Fix it",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "The root cause explanation here" in result
|
||||
|
||||
def test_contains_suggested_fix(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
result = format_incident_alert(
|
||||
title="Incident",
|
||||
severity="P1",
|
||||
root_cause="Root cause",
|
||||
suggested_fix="The suggested fix steps here",
|
||||
primary_service="karaoke-backend",
|
||||
patterns=[],
|
||||
)
|
||||
assert "The suggested fix steps here" in result
|
||||
|
||||
def test_shows_up_to_5_patterns(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
patterns = [
|
||||
{"service": f"service-{i}", "normalized_message": f"Error message {i}", "count": i + 1}
|
||||
for i in range(7)
|
||||
]
|
||||
result = format_incident_alert(
|
||||
title="Multi-pattern incident",
|
||||
severity="P1",
|
||||
root_cause="Root cause",
|
||||
suggested_fix="Fix",
|
||||
primary_service="service-0",
|
||||
patterns=patterns,
|
||||
)
|
||||
# First 5 should appear
|
||||
for i in range(5):
|
||||
assert f"Error message {i}" in result
|
||||
# 6th and 7th should not appear
|
||||
assert "Error message 5" not in result
|
||||
assert "Error message 6" not in result
|
||||
|
||||
def test_pattern_message_truncated_to_80_chars(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
|
||||
long_msg = "A" * 100
|
||||
patterns = [{"service": "svc", "normalized_message": long_msg, "count": 1}]
|
||||
result = format_incident_alert(
|
||||
title="Incident",
|
||||
severity="P1",
|
||||
root_cause="Root cause",
|
||||
suggested_fix="Fix",
|
||||
primary_service="svc",
|
||||
patterns=patterns,
|
||||
)
|
||||
# The full 100-char message should not appear; only first 80
|
||||
assert long_msg not in result
|
||||
assert long_msg[:80] in result
|
||||
|
||||
def test_truncates_to_discord_limit(self):
|
||||
from backend.services.error_monitor.discord import format_incident_alert
|
||||
from backend.services.error_monitor.config import DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
result = format_incident_alert(
|
||||
title="T" * 500,
|
||||
severity="P0",
|
||||
root_cause="R" * 500,
|
||||
suggested_fix="F" * 500,
|
||||
primary_service="svc",
|
||||
patterns=[],
|
||||
)
|
||||
assert len(result) <= DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
|
||||
class TestFormatAutoResolvedAlert:
|
||||
"""Tests for format_auto_resolved_alert formatting function."""
|
||||
|
||||
def test_contains_checkmark_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
result = format_auto_resolved_alert(
|
||||
resolved_patterns=[
|
||||
{"service": "karaoke-backend", "message": "Connection refused", "hours_silent": 8.5}
|
||||
]
|
||||
)
|
||||
assert "✅" in result
|
||||
|
||||
def test_consolidated_list_up_to_8_patterns(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
patterns = [
|
||||
{"service": f"service-{i}", "message": f"Error {i}", "hours_silent": float(i + 1)}
|
||||
for i in range(10)
|
||||
]
|
||||
result = format_auto_resolved_alert(resolved_patterns=patterns)
|
||||
# First 8 should appear
|
||||
for i in range(8):
|
||||
assert f"Error {i}" in result
|
||||
# 9th and 10th should not appear
|
||||
assert "Error 8" not in result
|
||||
assert "Error 9" not in result
|
||||
|
||||
def test_contains_service_name(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
result = format_auto_resolved_alert(
|
||||
resolved_patterns=[
|
||||
{"service": "audio-separator", "message": "GPU error", "hours_silent": 12.0}
|
||||
]
|
||||
)
|
||||
assert "audio-separator" in result
|
||||
|
||||
def test_contains_hours_silent(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
result = format_auto_resolved_alert(
|
||||
resolved_patterns=[
|
||||
{"service": "karaoke-backend", "message": "Timeout", "hours_silent": 7.5}
|
||||
]
|
||||
)
|
||||
# Should mention 7.5 or the number somewhere
|
||||
assert "7.5" in result or "7" in result
|
||||
|
||||
def test_message_truncated_to_60_chars(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
long_msg = "B" * 80
|
||||
result = format_auto_resolved_alert(
|
||||
resolved_patterns=[
|
||||
{"service": "svc", "message": long_msg, "hours_silent": 10.0}
|
||||
]
|
||||
)
|
||||
assert long_msg not in result
|
||||
assert long_msg[:60] in result
|
||||
|
||||
def test_empty_patterns_returns_string(self):
|
||||
from backend.services.error_monitor.discord import format_auto_resolved_alert
|
||||
|
||||
result = format_auto_resolved_alert(resolved_patterns=[])
|
||||
assert isinstance(result, str)
|
||||
assert "✅" in result
|
||||
|
||||
|
||||
class TestFormatSpikeAlert:
|
||||
"""Tests for format_spike_alert formatting function."""
|
||||
|
||||
def test_contains_warning_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="karaoke-backend",
|
||||
normalized_message="Connection refused",
|
||||
current_count=50,
|
||||
rolling_average=5.0,
|
||||
)
|
||||
assert "⚠️" in result
|
||||
|
||||
def test_contains_service_name(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="audio-separator",
|
||||
normalized_message="OOM error",
|
||||
current_count=30,
|
||||
rolling_average=3.0,
|
||||
)
|
||||
assert "audio-separator" in result
|
||||
|
||||
def test_contains_current_count(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="karaoke-backend",
|
||||
normalized_message="Timeout",
|
||||
current_count=75,
|
||||
rolling_average=10.0,
|
||||
)
|
||||
assert "75" in result
|
||||
|
||||
def test_contains_rolling_average(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="karaoke-backend",
|
||||
normalized_message="Timeout",
|
||||
current_count=75,
|
||||
rolling_average=10.0,
|
||||
)
|
||||
assert "10" in result
|
||||
|
||||
def test_contains_multiplier(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="karaoke-backend",
|
||||
normalized_message="Timeout",
|
||||
current_count=50,
|
||||
rolling_average=5.0,
|
||||
)
|
||||
# 50 / 5.0 = 10x
|
||||
assert "10" in result or "10.0" in result
|
||||
|
||||
def test_contains_normalized_message(self):
|
||||
from backend.services.error_monitor.discord import format_spike_alert
|
||||
|
||||
result = format_spike_alert(
|
||||
service="karaoke-backend",
|
||||
normalized_message="Database connection pool exhausted",
|
||||
current_count=50,
|
||||
rolling_average=5.0,
|
||||
)
|
||||
assert "Database connection pool exhausted" in result
|
||||
|
||||
|
||||
class TestFormatDailyDigest:
|
||||
"""Tests for format_daily_digest formatting function."""
|
||||
|
||||
def test_contains_chart_emoji(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=100,
|
||||
new_patterns=5,
|
||||
resolved_patterns=2,
|
||||
active_patterns=10,
|
||||
per_service_counts={"karaoke-backend": 60, "audio-separator": 40},
|
||||
)
|
||||
assert "📊" in result
|
||||
|
||||
def test_contains_total_errors(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=1234,
|
||||
new_patterns=5,
|
||||
resolved_patterns=2,
|
||||
active_patterns=10,
|
||||
per_service_counts={},
|
||||
)
|
||||
assert "1234" in result
|
||||
|
||||
def test_contains_new_patterns(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=100,
|
||||
new_patterns=7,
|
||||
resolved_patterns=2,
|
||||
active_patterns=10,
|
||||
per_service_counts={},
|
||||
)
|
||||
assert "7" in result
|
||||
|
||||
def test_contains_per_service_counts(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=100,
|
||||
new_patterns=5,
|
||||
resolved_patterns=2,
|
||||
active_patterns=10,
|
||||
per_service_counts={"karaoke-backend": 60, "audio-separator": 40},
|
||||
)
|
||||
assert "karaoke-backend" in result
|
||||
assert "audio-separator" in result
|
||||
assert "60" in result
|
||||
assert "40" in result
|
||||
|
||||
def test_per_service_sorted_by_count_desc(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=100,
|
||||
new_patterns=5,
|
||||
resolved_patterns=2,
|
||||
active_patterns=10,
|
||||
per_service_counts={
|
||||
"service-low": 10,
|
||||
"service-high": 80,
|
||||
"service-mid": 30,
|
||||
},
|
||||
)
|
||||
# service-high should appear before service-low in the output
|
||||
high_pos = result.index("service-high")
|
||||
low_pos = result.index("service-low")
|
||||
assert high_pos < low_pos
|
||||
|
||||
def test_contains_active_patterns(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
|
||||
result = format_daily_digest(
|
||||
total_errors=100,
|
||||
new_patterns=5,
|
||||
resolved_patterns=2,
|
||||
active_patterns=15,
|
||||
per_service_counts={},
|
||||
)
|
||||
assert "15" in result
|
||||
|
||||
def test_truncates_to_discord_limit(self):
|
||||
from backend.services.error_monitor.discord import format_daily_digest
|
||||
from backend.services.error_monitor.config import DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
# Create lots of services to potentially overflow
|
||||
per_service = {f"service-{i:03d}": i * 10 for i in range(100)}
|
||||
result = format_daily_digest(
|
||||
total_errors=99999,
|
||||
new_patterns=99,
|
||||
resolved_patterns=50,
|
||||
active_patterns=200,
|
||||
per_service_counts=per_service,
|
||||
)
|
||||
assert len(result) <= DISCORD_MAX_MESSAGE_LENGTH
|
||||
|
||||
|
||||
class TestErrorMonitorDiscordSendMessage:
|
||||
"""Tests for ErrorMonitorDiscord.send_message method."""
|
||||
|
||||
def test_send_message_returns_true_on_success(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
mock_response = mock.MagicMock()
|
||||
mock_response.status_code = 204
|
||||
mock_response.raise_for_status.return_value = None
|
||||
|
||||
with mock.patch("requests.post", return_value=mock_response) as mock_post:
|
||||
result = client.send_message("Hello Discord!")
|
||||
assert result is True
|
||||
mock_post.assert_called_once_with(
|
||||
"https://discord.com/api/webhooks/123/abc",
|
||||
json={"content": "Hello Discord!"},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def test_send_message_returns_false_on_http_error(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
mock_response = mock.MagicMock()
|
||||
mock_response.raise_for_status.side_effect = requests.HTTPError("429 Too Many Requests")
|
||||
|
||||
with mock.patch("requests.post", return_value=mock_response):
|
||||
result = client.send_message("Hello Discord!")
|
||||
assert result is False
|
||||
|
||||
def test_send_message_returns_false_on_connection_error(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
|
||||
with mock.patch("requests.post", side_effect=requests.ConnectionError("timeout")):
|
||||
result = client.send_message("Hello Discord!")
|
||||
assert result is False
|
||||
|
||||
def test_send_message_respects_rate_limit(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
from backend.services.error_monitor.config import MAX_DISCORD_MESSAGES_PER_RUN
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
client.messages_sent = MAX_DISCORD_MESSAGES_PER_RUN # Already at limit
|
||||
|
||||
with mock.patch("requests.post") as mock_post:
|
||||
result = client.send_message("Should be skipped")
|
||||
assert result is False
|
||||
mock_post.assert_not_called()
|
||||
|
||||
def test_send_message_increments_counter_on_success(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
assert client.messages_sent == 0
|
||||
|
||||
mock_response = mock.MagicMock()
|
||||
mock_response.raise_for_status.return_value = None
|
||||
|
||||
with mock.patch("requests.post", return_value=mock_response):
|
||||
client.send_message("First message")
|
||||
assert client.messages_sent == 1
|
||||
client.send_message("Second message")
|
||||
assert client.messages_sent == 2
|
||||
|
||||
def test_send_message_increments_counter_on_failure(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
assert client.messages_sent == 0
|
||||
|
||||
mock_response = mock.MagicMock()
|
||||
mock_response.raise_for_status.side_effect = requests.HTTPError("500")
|
||||
|
||||
with mock.patch("requests.post", return_value=mock_response):
|
||||
client.send_message("Will fail")
|
||||
assert client.messages_sent == 1
|
||||
|
||||
def test_send_message_initial_counter_is_zero(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
assert client.messages_sent == 0
|
||||
|
||||
def test_send_message_does_not_increment_when_rate_limited(self):
|
||||
from backend.services.error_monitor.discord import ErrorMonitorDiscord
|
||||
from backend.services.error_monitor.config import MAX_DISCORD_MESSAGES_PER_RUN
|
||||
|
||||
client = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/123/abc")
|
||||
client.messages_sent = MAX_DISCORD_MESSAGES_PER_RUN
|
||||
|
||||
with mock.patch("requests.post") as mock_post:
|
||||
client.send_message("Skipped")
|
||||
# Counter should not go beyond limit when rate-limited
|
||||
assert client.messages_sent == MAX_DISCORD_MESSAGES_PER_RUN
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,445 @@
|
||||
"""Tests for error_monitor.known_issues module."""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestIgnoreReasonDataclass:
|
||||
"""IgnoreReason dataclass should hold pattern_name and reason fields."""
|
||||
|
||||
def test_ignore_reason_has_pattern_name(self):
|
||||
from backend.services.error_monitor.known_issues import IgnoreReason
|
||||
|
||||
ir = IgnoreReason(pattern_name="startup_probe", reason="Cloud Run cold start")
|
||||
assert ir.pattern_name == "startup_probe"
|
||||
|
||||
def test_ignore_reason_has_reason(self):
|
||||
from backend.services.error_monitor.known_issues import IgnoreReason
|
||||
|
||||
ir = IgnoreReason(pattern_name="startup_probe", reason="Cloud Run cold start")
|
||||
assert ir.reason == "Cloud Run cold start"
|
||||
|
||||
def test_ignore_reason_is_dataclass_equality(self):
|
||||
from backend.services.error_monitor.known_issues import IgnoreReason
|
||||
|
||||
a = IgnoreReason(pattern_name="foo", reason="bar")
|
||||
b = IgnoreReason(pattern_name="foo", reason="bar")
|
||||
assert a == b
|
||||
|
||||
def test_ignore_reason_inequality(self):
|
||||
from backend.services.error_monitor.known_issues import IgnoreReason
|
||||
|
||||
a = IgnoreReason(pattern_name="foo", reason="bar")
|
||||
b = IgnoreReason(pattern_name="baz", reason="bar")
|
||||
assert a != b
|
||||
|
||||
|
||||
class TestStartupProbePattern:
|
||||
"""startup_probe — 'startup probe failed' should be ignored (Cloud Run cold start)."""
|
||||
|
||||
def test_startup_probe_exact(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "startup probe failed")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "startup_probe"
|
||||
|
||||
def test_startup_probe_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "Startup Probe Failed")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "startup_probe"
|
||||
|
||||
def test_startup_probe_in_longer_message(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Readiness probe failed: startup probe failed for container api",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "startup_probe"
|
||||
|
||||
def test_startup_probe_any_service(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("audio-separator", "startup probe failed")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "startup_probe"
|
||||
|
||||
|
||||
class TestReadyConditionPattern:
|
||||
"""ready_condition — 'ready condition status changed' should be ignored (deploy event)."""
|
||||
|
||||
def test_ready_condition_exact(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "ready condition status changed")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "ready_condition"
|
||||
|
||||
def test_ready_condition_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "Ready Condition Status Changed")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "ready_condition"
|
||||
|
||||
def test_ready_condition_with_context(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Service karaoke-backend: ready condition status changed to True",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "ready_condition"
|
||||
|
||||
|
||||
class TestSpotPreemptionPattern:
|
||||
"""spot_preemption — 'instance was preempted' should be ignored (GitHub runner spot VMs)."""
|
||||
|
||||
def test_spot_preemption_exact(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("encoding-worker-a", "instance was preempted")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "spot_preemption"
|
||||
|
||||
def test_spot_preemption_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("encoding-worker-a", "Instance Was Preempted")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "spot_preemption"
|
||||
|
||||
def test_spot_preemption_in_sentence(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"encoding-worker-b",
|
||||
"GCE: instance was preempted, shutting down",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "spot_preemption"
|
||||
|
||||
|
||||
class TestIdleShutdownPattern:
|
||||
"""idle_shutdown — 'stopping idle encoding worker' should be ignored (expected behavior)."""
|
||||
|
||||
def test_idle_shutdown_exact(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("encoding_worker_idle", "stopping idle encoding worker")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "idle_shutdown"
|
||||
|
||||
def test_idle_shutdown_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("encoding_worker_idle", "Stopping Idle Encoding Worker")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "idle_shutdown"
|
||||
|
||||
def test_idle_shutdown_with_context(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"encoding_worker_idle",
|
||||
"stopping idle encoding worker after 30 minutes of inactivity",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "idle_shutdown"
|
||||
|
||||
|
||||
class TestHealthCheck404Pattern:
|
||||
"""health_check_404 — GET/HEAD /health with 404/not found should be ignored (load balancer)."""
|
||||
|
||||
def test_health_check_get_404(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", 'GET /health 404')
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_health_check_head_404(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", 'HEAD /health 404')
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_health_check_get_not_found(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", 'GET /health not found')
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_health_check_head_not_found(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", 'HEAD /health not found')
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_health_check_uppercase_method(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "GET /health 404 Not Found")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_health_check_in_log_line(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
'10.0.0.1 - - [01/Jan/2024] "GET /health HTTP/1.1" 404 0',
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "health_check_404"
|
||||
|
||||
def test_non_health_404_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# A 404 for a real endpoint should NOT be ignored
|
||||
result = should_ignore("karaoke-backend", "GET /api/jobs/abc 404")
|
||||
assert result is None
|
||||
|
||||
def test_health_200_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# /health returning 200 is not an error, but should still not trigger this pattern
|
||||
result = should_ignore("karaoke-backend", "GET /health 200")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestSchedulerRetryPattern:
|
||||
"""scheduler_retry — 'cloud scheduler.*retry' should be ignored (transient)."""
|
||||
|
||||
def test_scheduler_retry_basic(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "cloud scheduler retry attempt 1")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "scheduler_retry"
|
||||
|
||||
def test_scheduler_retry_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "Cloud Scheduler Retry")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "scheduler_retry"
|
||||
|
||||
def test_scheduler_retry_with_details(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"runner_manager",
|
||||
"cloud scheduler job failed, will retry in 60s",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "scheduler_retry"
|
||||
|
||||
def test_cloud_scheduler_without_retry_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# "cloud scheduler" alone (without "retry") should NOT be suppressed
|
||||
result = should_ignore("runner_manager", "cloud scheduler job executed successfully")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestRunnerStartupPattern:
|
||||
"""runner_startup — 'github.runner.*(starting|stopping|idle)' should be ignored (lifecycle)."""
|
||||
|
||||
def test_runner_starting(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "github.runner.001 starting")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "runner_startup"
|
||||
|
||||
def test_runner_stopping(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "github.runner.abc stopping")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "runner_startup"
|
||||
|
||||
def test_runner_idle(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "github.runner.xyz idle")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "runner_startup"
|
||||
|
||||
def test_runner_starting_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("runner_manager", "GitHub.Runner.001 Starting")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "runner_startup"
|
||||
|
||||
def test_runner_other_state_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# A GitHub runner in an unexpected state should NOT be ignored
|
||||
result = should_ignore("runner_manager", "github.runner.001 crashed")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestContainerShutdownPattern:
|
||||
"""container_shutdown — 'container called exit(0)' should be ignored (clean shutdown)."""
|
||||
|
||||
def test_container_exit_0(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "container called exit(0)")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "container_shutdown"
|
||||
|
||||
def test_container_exit_0_uppercase(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "Container Called Exit(0)")
|
||||
assert result is not None
|
||||
assert result.pattern_name == "container_shutdown"
|
||||
|
||||
def test_container_exit_0_in_sentence(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Cloud Run instance terminated: container called exit(0)",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.pattern_name == "container_shutdown"
|
||||
|
||||
def test_container_exit_nonzero_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# exit(1) = error, should NOT be ignored
|
||||
result = should_ignore("karaoke-backend", "container called exit(1)")
|
||||
assert result is None
|
||||
|
||||
def test_container_exit_2_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "container called exit(2)")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestRealErrorsNotIgnored:
|
||||
"""Real errors should never be silently ignored."""
|
||||
|
||||
def test_firestore_deadline_exceeded(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Firestore transaction failed: DEADLINE_EXCEEDED",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_audio_separation_oom(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"audio-separator",
|
||||
"CUDA out of memory. Tried to allocate 2.00 GiB",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_payment_stripe_error(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Stripe charge failed: card_declined",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_gcs_permission_denied(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Permission denied accessing gs://nomadkaraoke-prod/output.mp4",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_worker_timeout(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"video-encoding-job",
|
||||
"Worker timed out after 3600 seconds",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_unhandled_exception(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore(
|
||||
"karaoke-backend",
|
||||
"Unhandled exception: KeyError 'job_id'",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestUnknownServiceMessages:
|
||||
"""Messages from unlisted/unknown services should use pattern matching, not service-gating."""
|
||||
|
||||
def test_unknown_service_known_pattern_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
# The patterns apply regardless of service name
|
||||
result = should_ignore("some-unknown-service", "startup probe failed")
|
||||
assert result is not None
|
||||
|
||||
def test_unknown_service_real_error_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("some-unknown-service", "unhandled exception in request handler")
|
||||
assert result is None
|
||||
|
||||
def test_empty_service_name_with_known_pattern(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("", "startup probe failed")
|
||||
assert result is not None
|
||||
|
||||
def test_empty_message_not_ignored(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestCaseInsensitiveMatching:
|
||||
"""All patterns should match case-insensitively."""
|
||||
|
||||
def test_startup_probe_all_caps(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "STARTUP PROBE FAILED")
|
||||
assert result is not None
|
||||
|
||||
def test_ready_condition_mixed_case(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "Ready CONDITION Status CHANGED")
|
||||
assert result is not None
|
||||
|
||||
def test_idle_shutdown_mixed_case(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("encoding_worker_idle", "STOPPING idle ENCODING worker")
|
||||
assert result is not None
|
||||
|
||||
def test_container_shutdown_mixed_case(self):
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
result = should_ignore("karaoke-backend", "Container Called EXIT(0)")
|
||||
assert result is not None
|
||||
@@ -0,0 +1,507 @@
|
||||
"""Tests for error_monitor.llm_analysis module.
|
||||
|
||||
All tests mock _call_llm to avoid real LLM calls.
|
||||
"""
|
||||
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SAMPLE_PATTERNS = [
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Connection refused to Firestore",
|
||||
"count": 15,
|
||||
"first_seen": "2026-04-10T10:00:00Z",
|
||||
"last_seen": "2026-04-10T10:30:00Z",
|
||||
},
|
||||
{
|
||||
"service": "audio-separation-job",
|
||||
"normalized_message": "CUDA out of memory error",
|
||||
"count": 8,
|
||||
"first_seen": "2026-04-10T10:05:00Z",
|
||||
"last_seen": "2026-04-10T10:25:00Z",
|
||||
},
|
||||
{
|
||||
"service": "audio-download-job",
|
||||
"normalized_message": "flacfetch-vm connection timeout",
|
||||
"count": 5,
|
||||
"first_seen": "2026-04-10T10:10:00Z",
|
||||
"last_seen": "2026-04-10T10:20:00Z",
|
||||
},
|
||||
]
|
||||
|
||||
VALID_INCIDENTS_JSON = json.dumps(
|
||||
{
|
||||
"incidents": [
|
||||
{
|
||||
"title": "Firestore connectivity failure",
|
||||
"root_cause": "Firestore is unavailable or misconfigured",
|
||||
"severity": "P1",
|
||||
"suggested_fix": "Check Firestore service health and credentials",
|
||||
"primary_service": "karaoke-backend",
|
||||
"pattern_indices": [0],
|
||||
},
|
||||
{
|
||||
"title": "GPU audio separation failure",
|
||||
"root_cause": "GPU out of memory on audio-separation-job",
|
||||
"severity": "P2",
|
||||
"suggested_fix": "Check GPU memory limits and job queue depth",
|
||||
"primary_service": "audio-separation-job",
|
||||
"pattern_indices": [1, 2],
|
||||
},
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
VALID_DUPLICATES_JSON = json.dumps(
|
||||
{
|
||||
"duplicates": [
|
||||
{
|
||||
"canonical_index": 0,
|
||||
"duplicate_indices": [1],
|
||||
"reason": "Both errors indicate Firestore connection issues",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for _parse_llm_response
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestParseLlmResponse:
|
||||
"""Unit tests for the _parse_llm_response helper."""
|
||||
|
||||
def test_valid_json_returns_incident_analysis(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
result = _parse_llm_response(VALID_INCIDENTS_JSON)
|
||||
assert result is not None
|
||||
assert len(result.incidents) == 2
|
||||
assert result.used_llm is True
|
||||
|
||||
def test_valid_json_incident_fields(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
result = _parse_llm_response(VALID_INCIDENTS_JSON)
|
||||
assert result is not None
|
||||
first = result.incidents[0]
|
||||
assert first.title == "Firestore connectivity failure"
|
||||
assert first.root_cause == "Firestore is unavailable or misconfigured"
|
||||
assert first.severity == "P1"
|
||||
assert first.primary_service == "karaoke-backend"
|
||||
assert first.pattern_indices == [0]
|
||||
|
||||
def test_invalid_json_returns_none(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
result = _parse_llm_response("not valid json {{{")
|
||||
assert result is None
|
||||
|
||||
def test_missing_incidents_key_returns_none(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
result = _parse_llm_response(json.dumps({"data": []}))
|
||||
assert result is None
|
||||
|
||||
def test_markdown_code_block_stripped(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
wrapped = f"```json\n{VALID_INCIDENTS_JSON}\n```"
|
||||
result = _parse_llm_response(wrapped)
|
||||
assert result is not None
|
||||
assert len(result.incidents) == 2
|
||||
|
||||
def test_markdown_code_block_without_language_stripped(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
wrapped = f"```\n{VALID_INCIDENTS_JSON}\n```"
|
||||
result = _parse_llm_response(wrapped)
|
||||
assert result is not None
|
||||
assert len(result.incidents) == 2
|
||||
|
||||
def test_empty_string_returns_none(self):
|
||||
from backend.services.error_monitor.llm_analysis import _parse_llm_response
|
||||
|
||||
result = _parse_llm_response("")
|
||||
assert result is None
|
||||
|
||||
def test_incidents_is_list_of_incident_objects(self):
|
||||
from backend.services.error_monitor.llm_analysis import (
|
||||
_parse_llm_response,
|
||||
Incident,
|
||||
)
|
||||
|
||||
result = _parse_llm_response(VALID_INCIDENTS_JSON)
|
||||
assert result is not None
|
||||
for incident in result.incidents:
|
||||
assert isinstance(incident, Incident)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for analyze_patterns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAnalyzePatterns:
|
||||
"""Unit tests for analyze_patterns."""
|
||||
|
||||
def test_returns_none_for_fewer_than_min_patterns(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
from backend.services.error_monitor.config import MIN_PATTERNS_FOR_ANALYSIS
|
||||
|
||||
# Build a list with fewer patterns than the minimum
|
||||
few_patterns = SAMPLE_PATTERNS[: MIN_PATTERNS_FOR_ANALYSIS - 1]
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm"
|
||||
) as mock_call:
|
||||
result = analyze_patterns(few_patterns)
|
||||
|
||||
assert result is None
|
||||
mock_call.assert_not_called()
|
||||
|
||||
def test_groups_patterns_into_incidents(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_INCIDENTS_JSON,
|
||||
):
|
||||
result = analyze_patterns(SAMPLE_PATTERNS)
|
||||
|
||||
assert result is not None
|
||||
assert len(result.incidents) == 2
|
||||
assert result.used_llm is True
|
||||
|
||||
def test_incident_has_correct_fields(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_INCIDENTS_JSON,
|
||||
):
|
||||
result = analyze_patterns(SAMPLE_PATTERNS)
|
||||
|
||||
assert result is not None
|
||||
incident = result.incidents[0]
|
||||
assert incident.title == "Firestore connectivity failure"
|
||||
assert incident.severity == "P1"
|
||||
assert incident.primary_service == "karaoke-backend"
|
||||
|
||||
def test_falls_back_on_llm_exception(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
side_effect=Exception("LLM unavailable"),
|
||||
):
|
||||
result = analyze_patterns(SAMPLE_PATTERNS)
|
||||
|
||||
# Should fall back to service grouping, not None
|
||||
assert result is not None
|
||||
assert result.used_llm is False
|
||||
|
||||
def test_fallback_groups_by_service(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
side_effect=Exception("LLM unavailable"),
|
||||
):
|
||||
result = analyze_patterns(SAMPLE_PATTERNS)
|
||||
|
||||
assert result is not None
|
||||
# Each unique service should map to one incident
|
||||
services = {inc.primary_service for inc in result.incidents}
|
||||
expected_services = {p["service"] for p in SAMPLE_PATTERNS}
|
||||
assert services == expected_services
|
||||
|
||||
def test_falls_back_on_invalid_llm_response(self):
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value="invalid json",
|
||||
):
|
||||
result = analyze_patterns(SAMPLE_PATTERNS)
|
||||
|
||||
# Should fall back to service grouping on parse failure
|
||||
assert result is not None
|
||||
assert result.used_llm is False
|
||||
|
||||
def test_exact_min_patterns_triggers_analysis(self):
|
||||
"""Exactly MIN_PATTERNS_FOR_ANALYSIS patterns should trigger the LLM."""
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns
|
||||
from backend.services.error_monitor.config import MIN_PATTERNS_FOR_ANALYSIS
|
||||
|
||||
# Ensure we have exactly MIN_PATTERNS_FOR_ANALYSIS patterns
|
||||
exactly_min = SAMPLE_PATTERNS[:MIN_PATTERNS_FOR_ANALYSIS]
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_INCIDENTS_JSON,
|
||||
) as mock_call:
|
||||
result = analyze_patterns(exactly_min)
|
||||
|
||||
mock_call.assert_called_once()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for _fallback_group_by_service
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFallbackGroupByService:
|
||||
"""Unit tests for _fallback_group_by_service."""
|
||||
|
||||
def test_groups_by_service(self):
|
||||
from backend.services.error_monitor.llm_analysis import _fallback_group_by_service
|
||||
|
||||
result = _fallback_group_by_service(SAMPLE_PATTERNS)
|
||||
services = {inc.primary_service for inc in result.incidents}
|
||||
assert services == {"karaoke-backend", "audio-separation-job", "audio-download-job"}
|
||||
|
||||
def test_used_llm_is_false(self):
|
||||
from backend.services.error_monitor.llm_analysis import _fallback_group_by_service
|
||||
|
||||
result = _fallback_group_by_service(SAMPLE_PATTERNS)
|
||||
assert result.used_llm is False
|
||||
|
||||
def test_severity_is_p2(self):
|
||||
from backend.services.error_monitor.llm_analysis import _fallback_group_by_service
|
||||
|
||||
result = _fallback_group_by_service(SAMPLE_PATTERNS)
|
||||
for incident in result.incidents:
|
||||
assert incident.severity == "P2"
|
||||
|
||||
def test_pattern_indices_are_populated(self):
|
||||
from backend.services.error_monitor.llm_analysis import _fallback_group_by_service
|
||||
|
||||
# Two patterns for the same service
|
||||
two_patterns = [
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Error A",
|
||||
"count": 3,
|
||||
},
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Error B",
|
||||
"count": 2,
|
||||
},
|
||||
]
|
||||
result = _fallback_group_by_service(two_patterns)
|
||||
assert len(result.incidents) == 1
|
||||
assert result.incidents[0].pattern_indices == [0, 1]
|
||||
|
||||
def test_empty_patterns_returns_empty_incidents(self):
|
||||
from backend.services.error_monitor.llm_analysis import _fallback_group_by_service
|
||||
|
||||
result = _fallback_group_by_service([])
|
||||
assert result.incidents == []
|
||||
assert result.used_llm is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for find_duplicate_patterns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFindDuplicatePatterns:
|
||||
"""Unit tests for find_duplicate_patterns."""
|
||||
|
||||
def test_returns_empty_for_empty_new_patterns(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm"
|
||||
) as mock_call:
|
||||
result = find_duplicate_patterns([], SAMPLE_PATTERNS)
|
||||
|
||||
assert result == []
|
||||
mock_call.assert_not_called()
|
||||
|
||||
def test_returns_empty_for_empty_existing_patterns(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm"
|
||||
) as mock_call:
|
||||
result = find_duplicate_patterns(SAMPLE_PATTERNS, [])
|
||||
|
||||
assert result == []
|
||||
mock_call.assert_not_called()
|
||||
|
||||
def test_identifies_duplicates(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
new_patterns = [
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Cannot reach Firestore endpoint",
|
||||
},
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Firestore deadline exceeded",
|
||||
},
|
||||
]
|
||||
existing_patterns = [
|
||||
{
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Connection refused to Firestore",
|
||||
}
|
||||
]
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_DUPLICATES_JSON,
|
||||
):
|
||||
result = find_duplicate_patterns(new_patterns, existing_patterns)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].canonical_index == 0
|
||||
assert result[0].duplicate_indices == [1]
|
||||
assert "Firestore" in result[0].reason
|
||||
|
||||
def test_returns_empty_on_no_duplicates_in_response(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
no_dups_json = json.dumps({"duplicates": []})
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=no_dups_json,
|
||||
):
|
||||
result = find_duplicate_patterns(SAMPLE_PATTERNS[:1], SAMPLE_PATTERNS[1:])
|
||||
|
||||
assert result == []
|
||||
|
||||
def test_returns_empty_on_llm_failure(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
side_effect=Exception("LLM unavailable"),
|
||||
):
|
||||
result = find_duplicate_patterns(SAMPLE_PATTERNS[:1], SAMPLE_PATTERNS[1:])
|
||||
|
||||
assert result == []
|
||||
|
||||
def test_returns_empty_on_invalid_response(self):
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value="not json",
|
||||
):
|
||||
result = find_duplicate_patterns(SAMPLE_PATTERNS[:1], SAMPLE_PATTERNS[1:])
|
||||
|
||||
assert result == []
|
||||
|
||||
def test_duplicate_group_fields(self):
|
||||
from backend.services.error_monitor.llm_analysis import (
|
||||
find_duplicate_patterns,
|
||||
DuplicateGroup,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_DUPLICATES_JSON,
|
||||
):
|
||||
result = find_duplicate_patterns(SAMPLE_PATTERNS[:2], SAMPLE_PATTERNS[2:])
|
||||
|
||||
assert len(result) == 1
|
||||
assert isinstance(result[0], DuplicateGroup)
|
||||
|
||||
def test_uses_low_temperature(self):
|
||||
"""find_duplicate_patterns should call _call_llm with temperature=0.1."""
|
||||
from backend.services.error_monitor.llm_analysis import find_duplicate_patterns
|
||||
|
||||
with patch(
|
||||
"backend.services.error_monitor.llm_analysis._call_llm",
|
||||
return_value=VALID_DUPLICATES_JSON,
|
||||
) as mock_call:
|
||||
find_duplicate_patterns(SAMPLE_PATTERNS[:1], SAMPLE_PATTERNS[1:])
|
||||
|
||||
# Check the temperature kwarg was 0.1
|
||||
call_kwargs = mock_call.call_args
|
||||
assert call_kwargs is not None
|
||||
# temperature is the 3rd positional arg or keyword arg
|
||||
if call_kwargs.kwargs.get("temperature") is not None:
|
||||
assert call_kwargs.kwargs["temperature"] == 0.1
|
||||
else:
|
||||
# positional: (system_prompt, user_prompt, temperature)
|
||||
assert call_kwargs.args[2] == 0.1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for dataclasses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDataclasses:
|
||||
"""Tests for the exported dataclasses."""
|
||||
|
||||
def test_incident_dataclass(self):
|
||||
from backend.services.error_monitor.llm_analysis import Incident
|
||||
|
||||
inc = Incident(
|
||||
title="Test",
|
||||
root_cause="Root cause",
|
||||
severity="P1",
|
||||
suggested_fix="Fix it",
|
||||
primary_service="karaoke-backend",
|
||||
pattern_indices=[0, 1],
|
||||
)
|
||||
assert inc.title == "Test"
|
||||
assert inc.severity == "P1"
|
||||
assert inc.pattern_indices == [0, 1]
|
||||
|
||||
def test_incident_nullable_fields(self):
|
||||
from backend.services.error_monitor.llm_analysis import Incident
|
||||
|
||||
inc = Incident(
|
||||
title="Test",
|
||||
root_cause=None,
|
||||
severity="P3",
|
||||
suggested_fix=None,
|
||||
primary_service="audio-separator",
|
||||
pattern_indices=[2],
|
||||
)
|
||||
assert inc.root_cause is None
|
||||
assert inc.suggested_fix is None
|
||||
|
||||
def test_incident_analysis_dataclass(self):
|
||||
from backend.services.error_monitor.llm_analysis import IncidentAnalysis, Incident
|
||||
|
||||
ia = IncidentAnalysis(incidents=[])
|
||||
assert ia.incidents == []
|
||||
assert ia.used_llm is True # default
|
||||
|
||||
def test_incident_analysis_used_llm_false(self):
|
||||
from backend.services.error_monitor.llm_analysis import IncidentAnalysis
|
||||
|
||||
ia = IncidentAnalysis(incidents=[], used_llm=False)
|
||||
assert ia.used_llm is False
|
||||
|
||||
def test_duplicate_group_dataclass(self):
|
||||
from backend.services.error_monitor.llm_analysis import DuplicateGroup
|
||||
|
||||
dg = DuplicateGroup(
|
||||
canonical_index=0,
|
||||
duplicate_indices=[1, 2],
|
||||
reason="Same root cause",
|
||||
)
|
||||
assert dg.canonical_index == 0
|
||||
assert dg.duplicate_indices == [1, 2]
|
||||
assert dg.reason == "Same root cause"
|
||||
@@ -0,0 +1,954 @@
|
||||
"""Tests for error_monitor.monitor module.
|
||||
|
||||
All external dependencies (Cloud Logging, Firestore, Discord, LLM, Secret Manager)
|
||||
are mocked — no real GCP connections are made.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Import helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _import_monitor_module():
|
||||
from backend.services.error_monitor import monitor as m
|
||||
|
||||
return m
|
||||
|
||||
|
||||
def _import_error_monitor_class():
|
||||
from backend.services.error_monitor.monitor import ErrorMonitor
|
||||
|
||||
return ErrorMonitor
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper to build a minimal mock log entry
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_entry(
|
||||
payload=None,
|
||||
resource_type="cloud_run_revision",
|
||||
service_name="karaoke-backend",
|
||||
job_name=None,
|
||||
function_name=None,
|
||||
instance_id=None,
|
||||
resource_name=None,
|
||||
):
|
||||
"""Return a mock Cloud Logging entry."""
|
||||
entry = MagicMock()
|
||||
entry.payload = payload
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = resource_type
|
||||
entry.resource.labels = {
|
||||
"service_name": service_name,
|
||||
"job_name": job_name or "",
|
||||
"function_name": function_name or "",
|
||||
"instance_id": instance_id or "",
|
||||
}
|
||||
entry.labels = {}
|
||||
if resource_name:
|
||||
entry.labels["compute.googleapis.com/resource_name"] = resource_name
|
||||
return entry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _build_log_filter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestBuildLogFilter:
|
||||
"""_build_log_filter should produce correct Cloud Logging filter strings."""
|
||||
|
||||
def test_cloud_run_revision_filter(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("cloud_run_revision", ["svc-a", "svc-b"], 15)
|
||||
assert 'resource.type="cloud_run_revision"' in result
|
||||
assert "severity>=ERROR" in result
|
||||
assert "svc-a" in result
|
||||
assert "svc-b" in result
|
||||
assert "resource.labels.service_name" in result
|
||||
|
||||
def test_cloud_run_job_filter(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("cloud_run_job", ["job-x"], 15)
|
||||
assert 'resource.type="cloud_run_job"' in result
|
||||
assert "severity>=ERROR" in result
|
||||
assert "job-x" in result
|
||||
assert "resource.labels.job_name" in result
|
||||
|
||||
def test_gce_instance_filter(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("gce_instance", ["enc-worker-a"], 15)
|
||||
assert 'resource.type="gce_instance"' in result
|
||||
assert "severity>=ERROR" in result
|
||||
assert "enc-worker-a" in result
|
||||
assert 'compute.googleapis.com/resource_name' in result
|
||||
|
||||
def test_cloud_function_filter(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("cloud_function", ["fn-one", "fn-two"], 10)
|
||||
assert 'resource.type="cloud_function"' in result
|
||||
assert "fn-one" in result
|
||||
assert "fn-two" in result
|
||||
|
||||
def test_filter_contains_timestamp(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("cloud_run_revision", ["svc"], 30)
|
||||
assert "timestamp>=" in result
|
||||
|
||||
def test_single_resource_no_or_clause_needed(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._build_log_filter("cloud_run_revision", ["only-svc"], 15)
|
||||
assert "only-svc" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _extract_message
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestExtractMessage:
|
||||
"""_extract_message should handle all payload shapes."""
|
||||
|
||||
def test_text_payload_string_returned_directly(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = "Something went wrong"
|
||||
result = m._extract_message(entry)
|
||||
assert result == "Something went wrong"
|
||||
|
||||
def test_dict_payload_message_key(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = {"message": "DB connection refused"}
|
||||
result = m._extract_message(entry)
|
||||
assert result == "DB connection refused"
|
||||
|
||||
def test_dict_payload_textPayload_key(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = {"textPayload": "File not found: /tmp/foo"}
|
||||
result = m._extract_message(entry)
|
||||
assert result == "File not found: /tmp/foo"
|
||||
|
||||
def test_dict_payload_error_key(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = {"error": "timeout after 30s"}
|
||||
result = m._extract_message(entry)
|
||||
assert result == "timeout after 30s"
|
||||
|
||||
def test_dict_payload_msg_key(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = {"msg": "panic: nil pointer dereference"}
|
||||
result = m._extract_message(entry)
|
||||
assert result == "panic: nil pointer dereference"
|
||||
|
||||
def test_none_payload_returns_none(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = None
|
||||
result = m._extract_message(entry)
|
||||
assert result is None
|
||||
|
||||
def test_dict_payload_no_known_key_returns_none(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = {"severity": "ERROR", "timestamp": "2026-04-10T10:00:00Z"}
|
||||
result = m._extract_message(entry)
|
||||
assert result is None
|
||||
|
||||
def test_empty_string_payload_treated_as_text(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.payload = ""
|
||||
result = m._extract_message(entry)
|
||||
# Empty string is falsy — should return the string or None depending on impl
|
||||
# As long as it doesn't crash; either return value is acceptable
|
||||
assert result is None or result == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _extract_service_name
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestExtractServiceName:
|
||||
"""_extract_service_name should return the correct label for each resource type."""
|
||||
|
||||
def test_cloud_run_revision_returns_service_name(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {"service_name": "karaoke-backend"}
|
||||
result = m._extract_service_name(entry, "cloud_run_revision")
|
||||
assert result == "karaoke-backend"
|
||||
|
||||
def test_cloud_run_job_returns_job_name(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {"job_name": "video-encoding-job"}
|
||||
result = m._extract_service_name(entry, "cloud_run_job")
|
||||
assert result == "video-encoding-job"
|
||||
|
||||
def test_cloud_function_returns_function_name(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {"function_name": "gdrive-validator"}
|
||||
result = m._extract_service_name(entry, "cloud_function")
|
||||
assert result == "gdrive-validator"
|
||||
|
||||
def test_gce_instance_returns_resource_name_from_labels(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {}
|
||||
entry.labels = {"compute.googleapis.com/resource_name": "encoding-worker-a"}
|
||||
result = m._extract_service_name(entry, "gce_instance")
|
||||
assert result == "encoding-worker-a"
|
||||
|
||||
def test_gce_instance_falls_back_to_instance_id(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {"instance_id": "1234567890"}
|
||||
entry.labels = {}
|
||||
result = m._extract_service_name(entry, "gce_instance")
|
||||
assert result == "1234567890"
|
||||
|
||||
def test_missing_labels_returns_unknown(self):
|
||||
m = _import_monitor_module()
|
||||
entry = MagicMock()
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.labels = {}
|
||||
entry.labels = {}
|
||||
# Should not raise — returns some fallback string
|
||||
result = m._extract_service_name(entry, "cloud_run_revision")
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _classify_resource_type
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestClassifyResourceType:
|
||||
"""_classify_resource_type should map log resource types to canonical types."""
|
||||
|
||||
def test_cloud_run_revision_mapped(self):
|
||||
m = _import_monitor_module()
|
||||
assert m._classify_resource_type("cloud_run_revision") == "cloud_run_service"
|
||||
|
||||
def test_cloud_run_job_mapped(self):
|
||||
m = _import_monitor_module()
|
||||
assert m._classify_resource_type("cloud_run_job") == "cloud_run_job"
|
||||
|
||||
def test_cloud_function_mapped(self):
|
||||
m = _import_monitor_module()
|
||||
assert m._classify_resource_type("cloud_function") == "cloud_function"
|
||||
|
||||
def test_gce_instance_mapped(self):
|
||||
m = _import_monitor_module()
|
||||
assert m._classify_resource_type("gce_instance") == "gce_instance"
|
||||
|
||||
def test_unknown_type_returns_original_or_unknown(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._classify_resource_type("unknown_type")
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _group_by_pattern (via _run_monitor_cycle logic)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestGroupByPattern:
|
||||
"""_group_by_pattern should correctly group entries by hash and count duplicates."""
|
||||
|
||||
def _make_monitor(self):
|
||||
"""Create an ErrorMonitor instance without calling __init__ (no GCP calls)."""
|
||||
ErrorMonitor = _import_error_monitor_class()
|
||||
monitor = ErrorMonitor.__new__(ErrorMonitor)
|
||||
monitor.logging_client = MagicMock()
|
||||
monitor.firestore_adapter = MagicMock()
|
||||
monitor.discord = MagicMock()
|
||||
return monitor
|
||||
|
||||
def test_groups_entries_by_hash(self):
|
||||
monitor = self._make_monitor()
|
||||
m = _import_monitor_module()
|
||||
|
||||
entries = [
|
||||
{"service": "svc-a", "normalized": "Connection refused", "message": "msg1"},
|
||||
{"service": "svc-a", "normalized": "Connection refused", "message": "msg2"},
|
||||
{"service": "svc-b", "normalized": "Timeout error", "message": "msg3"},
|
||||
]
|
||||
result = m._group_by_pattern(entries)
|
||||
# 2 unique patterns
|
||||
assert len(result) == 2
|
||||
|
||||
def test_counts_duplicates_correctly(self):
|
||||
monitor = self._make_monitor()
|
||||
m = _import_monitor_module()
|
||||
|
||||
entries = [
|
||||
{"service": "svc-a", "normalized": "Connection refused", "message": "msg1"},
|
||||
{"service": "svc-a", "normalized": "Connection refused", "message": "msg2"},
|
||||
{"service": "svc-a", "normalized": "Connection refused", "message": "msg3"},
|
||||
]
|
||||
result = m._group_by_pattern(entries)
|
||||
assert len(result) == 1
|
||||
group = list(result.values())[0]
|
||||
assert group["count"] == 3
|
||||
|
||||
def test_each_group_has_sample_message(self):
|
||||
m = _import_monitor_module()
|
||||
|
||||
entries = [
|
||||
{"service": "svc-a", "normalized": "DB error", "message": "DB error at line 42"},
|
||||
]
|
||||
result = m._group_by_pattern(entries)
|
||||
group = list(result.values())[0]
|
||||
assert "sample_message" in group
|
||||
assert group["sample_message"] == "DB error at line 42"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _is_spike
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestIsSpike:
|
||||
"""_is_spike should detect spikes based on multiplier and minimum count."""
|
||||
|
||||
def _make_monitor(self):
|
||||
ErrorMonitor = _import_error_monitor_class()
|
||||
monitor = ErrorMonitor.__new__(ErrorMonitor)
|
||||
monitor.logging_client = MagicMock()
|
||||
monitor.firestore_adapter = MagicMock()
|
||||
monitor.discord = MagicMock()
|
||||
return monitor
|
||||
|
||||
def test_detects_spike_when_count_exceeds_multiplier_and_min(self):
|
||||
m = _import_monitor_module()
|
||||
# rolling_counts of 1 each for the past 5 periods, current count = 10
|
||||
# avg = 1.0, SPIKE_MULTIPLIER=5.0, so 10 > 5 and 10 >= SPIKE_MIN_COUNT=5
|
||||
rolling_counts = [{"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}]
|
||||
assert m._is_spike(current_count=10, rolling_counts=rolling_counts) is True
|
||||
|
||||
def test_rejects_non_spike_count(self):
|
||||
m = _import_monitor_module()
|
||||
rolling_counts = [{"count": 4}, {"count": 4}, {"count": 4}, {"count": 4}]
|
||||
# avg = 4.0, 5x = 20, current=5 → not a spike
|
||||
assert m._is_spike(current_count=5, rolling_counts=rolling_counts) is False
|
||||
|
||||
def test_rejects_spike_below_min_count(self):
|
||||
m = _import_monitor_module()
|
||||
# avg = 0.5, 5x = 2.5, current = 3 → exceeds multiplier but below SPIKE_MIN_COUNT
|
||||
rolling_counts = [{"count": 1}, {"count": 0}]
|
||||
assert m._is_spike(current_count=3, rolling_counts=rolling_counts) is False
|
||||
|
||||
def test_empty_rolling_counts_not_a_spike(self):
|
||||
m = _import_monitor_module()
|
||||
assert m._is_spike(current_count=100, rolling_counts=[]) is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _rolling_average
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRollingAverage:
|
||||
"""_rolling_average should compute mean of rolling_counts."""
|
||||
|
||||
def test_computes_average_correctly(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 2}, {"count": 4}, {"count": 6}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(4.0)
|
||||
|
||||
def test_single_entry_returns_that_value(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 7}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(7.0)
|
||||
|
||||
def test_empty_list_returns_zero(self):
|
||||
m = _import_monitor_module()
|
||||
result = m._rolling_average([])
|
||||
assert result == 0.0
|
||||
|
||||
def test_counts_with_zeros(self):
|
||||
m = _import_monitor_module()
|
||||
rolling = [{"count": 0}, {"count": 0}, {"count": 10}]
|
||||
result = m._rolling_average(rolling)
|
||||
assert result == pytest.approx(10 / 3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _run_monitor_cycle end-to-end
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_monitor_with_mocks():
|
||||
"""Return an ErrorMonitor with all external dependencies mocked."""
|
||||
ErrorMonitor = _import_error_monitor_class()
|
||||
monitor = ErrorMonitor.__new__(ErrorMonitor)
|
||||
monitor.logging_client = MagicMock()
|
||||
monitor.firestore_adapter = MagicMock()
|
||||
monitor.discord = MagicMock()
|
||||
return monitor
|
||||
|
||||
|
||||
class TestRunMonitorCycleNoErrors:
|
||||
"""When no error entries are found, auto-resolve check should still run."""
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_auto_resolve_called_even_when_no_errors(self, mock_digest, mock_llm):
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
# Cloud Logging returns empty results for all resource types
|
||||
monitor.logging_client.list_entries.return_value = iter([])
|
||||
|
||||
# Firestore adapter returns no patterns eligible for auto-resolve
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
# Auto-resolve check must always run
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.assert_called_once()
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_no_discord_sent_when_no_errors(self, mock_digest, mock_llm):
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
monitor.logging_client.list_entries.return_value = iter([])
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
monitor.discord.send_message.assert_not_called()
|
||||
|
||||
|
||||
class TestRunMonitorCycleOneNewError:
|
||||
"""When one new error pattern is found, an individual alert should be sent."""
|
||||
|
||||
def _make_log_entry(self):
|
||||
entry = MagicMock()
|
||||
entry.payload = "RuntimeError: connection refused"
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = "cloud_run_revision"
|
||||
entry.resource.labels = {"service_name": "karaoke-backend"}
|
||||
entry.labels = {}
|
||||
return entry
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_individual_alert_sent_for_new_pattern(self, mock_digest, mock_llm, mock_ignore):
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
log_entry = self._make_log_entry()
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
|
||||
# Upsert returns is_new=True for first encounter
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="abc123", is_new=True
|
||||
)
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
# An alert should have been sent
|
||||
assert monitor.discord.send_message.call_count >= 1
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_upsert_called_for_each_pattern_group(self, mock_digest, mock_llm, mock_ignore):
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
log_entry = self._make_log_entry()
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="abc123", is_new=True
|
||||
)
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
assert monitor.firestore_adapter.upsert_pattern.call_count >= 1
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_known_issue_skipped(self, mock_digest, mock_llm, mock_ignore):
|
||||
"""Entries matched by should_ignore should not be upserted or alerted."""
|
||||
from backend.services.error_monitor.known_issues import IgnoreReason
|
||||
|
||||
# Override: should_ignore returns a reason (i.e., ignore this entry)
|
||||
mock_ignore.return_value = IgnoreReason(
|
||||
pattern_name="startup_probe",
|
||||
reason="Cloud Run cold start — startup probe failure is transient",
|
||||
)
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
log_entry = self._make_log_entry()
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
monitor.firestore_adapter.upsert_pattern.assert_not_called()
|
||||
monitor.discord.send_message.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: _run_daily_digest (P0)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRunDailyDigest:
|
||||
"""_run_daily_digest should fetch active patterns and send a digest to Discord."""
|
||||
|
||||
@pytest.fixture
|
||||
def monitor(self):
|
||||
ErrorMonitor = _import_error_monitor_class()
|
||||
m = ErrorMonitor.__new__(ErrorMonitor)
|
||||
m.logging_client = MagicMock()
|
||||
m.firestore_adapter = MagicMock()
|
||||
m.discord = MagicMock()
|
||||
m.discord.messages_sent = 0
|
||||
m.logger = MagicMock()
|
||||
return m
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
def test_digest_sends_message_with_chart_emoji(self, mock_llm, monitor):
|
||||
"""_run_daily_digest should send a message containing the 📊 emoji."""
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = [
|
||||
{"service": "karaoke-backend", "total_count": 10, "status": "new"},
|
||||
{"service": "video-worker", "total_count": 5, "status": "acknowledged"},
|
||||
]
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_daily_digest()
|
||||
|
||||
assert monitor.discord.send_message.call_count == 1
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
assert "📊" in sent_content
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
def test_digest_includes_per_service_counts(self, mock_llm, monitor):
|
||||
"""_run_daily_digest should aggregate counts per service."""
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = [
|
||||
{"service": "svc-alpha", "total_count": 7, "status": "new"},
|
||||
{"service": "svc-alpha", "total_count": 3, "status": "acknowledged"},
|
||||
{"service": "svc-beta", "total_count": 2, "status": "new"},
|
||||
]
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_daily_digest()
|
||||
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
# Both services should be mentioned in the digest
|
||||
assert "svc-alpha" in sent_content
|
||||
assert "svc-beta" in sent_content
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
def test_digest_with_no_active_patterns(self, mock_llm, monitor):
|
||||
"""_run_daily_digest should still send a digest even when there are no patterns."""
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_daily_digest()
|
||||
|
||||
assert monitor.discord.send_message.call_count == 1
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
assert "📊" in sent_content
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: PatternData construction (P0)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPatternDataConstruction:
|
||||
"""upsert_pattern should be called with a PatternData object with correct field types."""
|
||||
|
||||
def _make_log_entry(self, message="RuntimeError: disk full", service="karaoke-backend"):
|
||||
entry = MagicMock()
|
||||
entry.payload = message
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = "cloud_run_revision"
|
||||
entry.resource.labels = {"service_name": service}
|
||||
entry.labels = {}
|
||||
return entry
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_pattern_data_fields_have_correct_types(self, mock_digest, mock_llm, mock_ignore):
|
||||
"""upsert_pattern receives a PatternData with correctly typed fields."""
|
||||
from backend.services.error_monitor.firestore_adapter import PatternData, UpsertResult
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
log_entry = self._make_log_entry()
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="xyz789", is_new=True
|
||||
)
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
assert monitor.firestore_adapter.upsert_pattern.call_count >= 1
|
||||
call_arg = monitor.firestore_adapter.upsert_pattern.call_args[0][0]
|
||||
assert isinstance(call_arg, PatternData)
|
||||
|
||||
# pattern_id should be a non-empty hex string
|
||||
assert isinstance(call_arg.pattern_id, str)
|
||||
assert len(call_arg.pattern_id) > 0
|
||||
# All characters should be valid hex (the hash function produces hex)
|
||||
assert all(c in "0123456789abcdef" for c in call_arg.pattern_id)
|
||||
|
||||
# service must match the log entry's service label
|
||||
assert call_arg.service == "karaoke-backend"
|
||||
|
||||
# resource_type maps to canonical string
|
||||
assert isinstance(call_arg.resource_type, str)
|
||||
assert len(call_arg.resource_type) > 0
|
||||
|
||||
# normalized_message and sample_message must be non-empty strings
|
||||
assert isinstance(call_arg.normalized_message, str)
|
||||
assert len(call_arg.normalized_message) > 0
|
||||
assert isinstance(call_arg.sample_message, str)
|
||||
assert len(call_arg.sample_message) > 0
|
||||
|
||||
# count is a positive int
|
||||
assert isinstance(call_arg.count, int)
|
||||
assert call_arg.count >= 1
|
||||
|
||||
# timestamp is a datetime
|
||||
assert isinstance(call_arg.timestamp, datetime)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: Discord alert argument verification (P0)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDiscordAlertContent:
|
||||
"""The Discord alert message should contain the service name and normalized message."""
|
||||
|
||||
def _make_log_entry(self, message, service):
|
||||
entry = MagicMock()
|
||||
entry.payload = message
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = "cloud_run_revision"
|
||||
entry.resource.labels = {"service_name": service}
|
||||
entry.labels = {}
|
||||
return entry
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_new_pattern_alert_contains_service_name(self, mock_digest, mock_llm, mock_ignore):
|
||||
"""The alert message sent to Discord should contain the originating service name."""
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
service_name = "my-special-service"
|
||||
monitor = _make_monitor_with_mocks()
|
||||
log_entry = self._make_log_entry("RuntimeError: boom", service=service_name)
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="aabbcc", is_new=True
|
||||
)
|
||||
monitor.firestore_adapter.get_pattern.return_value = {"first_seen": "2026-01-01T00:00:00Z"}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
assert monitor.discord.send_message.call_count >= 1
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
assert service_name in sent_content
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_new_pattern_alert_contains_normalized_message(
|
||||
self, mock_digest, mock_llm, mock_ignore
|
||||
):
|
||||
"""The alert message should contain a recognizable part of the normalized error."""
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
# Use a distinctive error phrase that should survive normalization
|
||||
log_entry = self._make_log_entry(
|
||||
"ConnectionError: database connection refused", service="karaoke-backend"
|
||||
)
|
||||
monitor.logging_client.list_entries.return_value = iter([log_entry])
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="def456", is_new=True
|
||||
)
|
||||
monitor.firestore_adapter.get_pattern.return_value = {"first_seen": "2026-01-01T00:00:00Z"}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
assert monitor.discord.send_message.call_count >= 1
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
# The normalized message should contain at least "connection" or "refused"
|
||||
assert "connection" in sent_content.lower() or "refused" in sent_content.lower()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: analyze_patterns input format (P0)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAnalyzePatternsInputFormat:
|
||||
"""When LLM is enabled, analyze_patterns is called with correctly shaped dicts."""
|
||||
|
||||
def _make_log_entry(self, message, service):
|
||||
entry = MagicMock()
|
||||
entry.payload = message
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = "cloud_run_revision"
|
||||
entry.resource.labels = {"service_name": service}
|
||||
entry.labels = {}
|
||||
return entry
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.analyze_patterns")
|
||||
@patch("backend.services.error_monitor.monitor.find_duplicate_patterns")
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=True)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_analyze_patterns_receives_correct_keys(
|
||||
self, mock_digest, mock_llm, mock_ignore, mock_find_dups, mock_analyze
|
||||
):
|
||||
"""analyze_patterns should receive a list of dicts with service, normalized_message, count."""
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
mock_analyze.return_value = MagicMock(incidents=[])
|
||||
mock_find_dups.return_value = []
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
# Create 2 distinct log entries so LLM dedup + analysis paths are triggered
|
||||
entry1 = self._make_log_entry("RuntimeError: disk full", service="svc-one")
|
||||
entry2 = self._make_log_entry("ValueError: invalid input", service="svc-two")
|
||||
monitor.logging_client.list_entries.side_effect = [
|
||||
iter([entry1, entry2]),
|
||||
iter([]),
|
||||
iter([]),
|
||||
iter([]),
|
||||
]
|
||||
|
||||
call_count = [0]
|
||||
|
||||
def upsert_side_effect(data):
|
||||
call_count[0] += 1
|
||||
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
|
||||
|
||||
monitor.firestore_adapter.upsert_pattern.side_effect = upsert_side_effect
|
||||
monitor.firestore_adapter.get_pattern.return_value = {"first_seen": "2026-01-01T00:00:00Z"}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
# analyze_patterns should have been called once both new patterns exist
|
||||
assert mock_analyze.call_count >= 1
|
||||
call_args = mock_analyze.call_args[0][0]
|
||||
assert isinstance(call_args, list)
|
||||
assert len(call_args) >= 1
|
||||
|
||||
for item in call_args:
|
||||
assert "service" in item, f"Missing 'service' key in {item}"
|
||||
assert "normalized_message" in item, f"Missing 'normalized_message' key in {item}"
|
||||
assert "count" in item, f"Missing 'count' key in {item}"
|
||||
assert isinstance(item["service"], str)
|
||||
assert isinstance(item["normalized_message"], str)
|
||||
assert isinstance(item["count"], int)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: Spike detection flow (P1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestSpikeDetectionFlow:
|
||||
"""_run_monitor_cycle should send a spike alert when counts exceed the threshold."""
|
||||
|
||||
def _make_log_entry(self, message="RuntimeError: timeout", service="karaoke-backend"):
|
||||
entry = MagicMock()
|
||||
entry.payload = message
|
||||
entry.resource = MagicMock()
|
||||
entry.resource.type = "cloud_run_revision"
|
||||
entry.resource.labels = {"service_name": service}
|
||||
entry.labels = {}
|
||||
return entry
|
||||
|
||||
@patch("backend.services.error_monitor.monitor.should_ignore", return_value=None)
|
||||
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
|
||||
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
|
||||
def test_spike_alert_sent_when_count_exceeds_threshold(
|
||||
self, mock_digest, mock_llm, mock_ignore
|
||||
):
|
||||
"""A spike alert (⚠️) is sent when current count is >5x rolling average and >= min."""
|
||||
from backend.services.error_monitor.firestore_adapter import UpsertResult
|
||||
|
||||
monitor = _make_monitor_with_mocks()
|
||||
|
||||
# Send 10 identical entries to make count = 10 (> SPIKE_MIN_COUNT=5)
|
||||
entries = [self._make_log_entry() for _ in range(10)]
|
||||
monitor.logging_client.list_entries.return_value = iter(entries)
|
||||
|
||||
# Upsert returns is_new=False (existing pattern) so spike check runs
|
||||
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(
|
||||
pattern_id="spike-pattern-1", is_new=False
|
||||
)
|
||||
|
||||
# get_pattern returns a pattern with rolling_counts that average to 1
|
||||
# avg=1.0, 5x=5.0, current_count=10 → spike detected
|
||||
monitor.firestore_adapter.get_pattern.return_value = {
|
||||
"pattern_id": "spike-pattern-1",
|
||||
"rolling_counts": [{"count": 1}, {"count": 1}, {"count": 1}, {"count": 1}],
|
||||
}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
# At least one Discord message should have been sent
|
||||
assert monitor.discord.send_message.call_count >= 1
|
||||
|
||||
# At least one of the messages should be a spike alert (⚠️)
|
||||
all_calls = monitor.discord.send_message.call_args_list
|
||||
spike_messages = [c for c in all_calls if "⚠️" in c[0][0]]
|
||||
assert len(spike_messages) >= 1, (
|
||||
"Expected at least one spike alert (⚠️) but none found. "
|
||||
f"Messages sent: {[c[0][0][:80] for c in all_calls]}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: Auto-resolve alert (P1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAutoResolveAlert:
|
||||
"""_check_auto_resolve should resolve eligible patterns and send a ✅ alert."""
|
||||
|
||||
@pytest.fixture
|
||||
def monitor(self):
|
||||
ErrorMonitor = _import_error_monitor_class()
|
||||
m = ErrorMonitor.__new__(ErrorMonitor)
|
||||
m.logging_client = MagicMock()
|
||||
m.firestore_adapter = MagicMock()
|
||||
m.discord = MagicMock()
|
||||
m.discord.messages_sent = 0
|
||||
m.logger = MagicMock()
|
||||
return m
|
||||
|
||||
def test_auto_resolve_calls_resolve_and_sends_alert(self, monitor):
|
||||
"""When a pattern qualifies for auto-resolve, the pattern is resolved and ✅ is sent."""
|
||||
pattern = {
|
||||
"pattern_id": "resolve-me-123",
|
||||
"service": "karaoke-backend",
|
||||
"normalized_message": "Connection refused",
|
||||
"status": "new",
|
||||
}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = [pattern]
|
||||
monitor.firestore_adapter.check_auto_resolve.return_value = 25.5 # hours silent
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._check_auto_resolve()
|
||||
|
||||
# auto_resolve_pattern must have been called with the correct pattern_id
|
||||
monitor.firestore_adapter.auto_resolve_pattern.assert_called_once_with(
|
||||
"resolve-me-123", 25.5
|
||||
)
|
||||
|
||||
# A Discord message must have been sent
|
||||
assert monitor.discord.send_message.call_count == 1
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
assert "✅" in sent_content
|
||||
|
||||
def test_auto_resolve_no_alert_when_no_patterns_qualify(self, monitor):
|
||||
"""When no patterns qualify for auto-resolve, no Discord alert is sent."""
|
||||
pattern = {
|
||||
"pattern_id": "still-active",
|
||||
"service": "svc-x",
|
||||
"normalized_message": "Disk full",
|
||||
"status": "acknowledged",
|
||||
}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = [pattern]
|
||||
# check_auto_resolve returns None → pattern does not qualify yet
|
||||
monitor.firestore_adapter.check_auto_resolve.return_value = None
|
||||
|
||||
monitor._check_auto_resolve()
|
||||
|
||||
monitor.firestore_adapter.auto_resolve_pattern.assert_not_called()
|
||||
monitor.discord.send_message.assert_not_called()
|
||||
|
||||
def test_auto_resolve_via_monitor_cycle(self, monitor):
|
||||
"""_run_monitor_cycle with no errors should still trigger the auto-resolve check."""
|
||||
with patch(
|
||||
"backend.services.error_monitor.monitor.get_llm_enabled", return_value=False
|
||||
), patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False):
|
||||
monitor.logging_client.list_entries.return_value = iter([])
|
||||
|
||||
pattern = {
|
||||
"pattern_id": "cycle-resolve",
|
||||
"service": "bg-worker",
|
||||
"normalized_message": "queue timeout",
|
||||
"status": "new",
|
||||
}
|
||||
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = [pattern]
|
||||
monitor.firestore_adapter.check_auto_resolve.return_value = 12.0
|
||||
monitor.firestore_adapter.get_active_patterns.return_value = []
|
||||
monitor.discord.send_message.return_value = True
|
||||
|
||||
monitor._run_monitor_cycle()
|
||||
|
||||
monitor.firestore_adapter.auto_resolve_pattern.assert_called_once()
|
||||
sent_content = monitor.discord.send_message.call_args[0][0]
|
||||
assert "✅" in sent_content
|
||||
@@ -0,0 +1,415 @@
|
||||
"""Tests for error_monitor.normalizer module."""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestUUIDReplacement:
|
||||
"""UUID patterns should be replaced with <ID>."""
|
||||
|
||||
def test_uuid_v4_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Job failed for job_id=550e8400-e29b-41d4-a716-446655440000"
|
||||
result = normalize_message(msg)
|
||||
assert "550e8400-e29b-41d4-a716-446655440000" not in result
|
||||
assert "<ID>" in result
|
||||
|
||||
def test_uuid_uppercase_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Error in request 550E8400-E29B-41D4-A716-446655440000"
|
||||
result = normalize_message(msg)
|
||||
assert "550E8400-E29B-41D4-A716-446655440000" not in result
|
||||
assert "<ID>" in result
|
||||
|
||||
def test_multiple_uuids_all_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Copy from 550e8400-e29b-41d4-a716-446655440000 to 660f9511-f30c-52e5-b827-557766551111"
|
||||
result = normalize_message(msg)
|
||||
assert "550e8400" not in result
|
||||
assert "660f9511" not in result
|
||||
|
||||
|
||||
class TestISOTimestampReplacement:
|
||||
"""ISO 8601 timestamps should be replaced with <TS>."""
|
||||
|
||||
def test_iso_datetime_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Error occurred at 2024-01-15T10:30:45Z"
|
||||
result = normalize_message(msg)
|
||||
assert "2024-01-15T10:30:45Z" not in result
|
||||
assert "<TS>" in result
|
||||
|
||||
def test_iso_datetime_with_ms_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Timeout at 2024-03-22T14:55:01.123Z"
|
||||
result = normalize_message(msg)
|
||||
assert "2024-03-22T14:55:01.123Z" not in result
|
||||
assert "<TS>" in result
|
||||
|
||||
def test_iso_datetime_with_offset_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Created at 2024-06-01T08:00:00+05:30"
|
||||
result = normalize_message(msg)
|
||||
assert "2024-06-01T08:00:00+05:30" not in result
|
||||
assert "<TS>" in result
|
||||
|
||||
|
||||
class TestEpochTimestampReplacement:
|
||||
"""Epoch timestamps (10+ digit floats) should be replaced with <EPOCH>."""
|
||||
|
||||
def test_epoch_float_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Received at t=1711234567.891234"
|
||||
result = normalize_message(msg)
|
||||
assert "1711234567.891234" not in result
|
||||
assert "<EPOCH>" in result
|
||||
|
||||
def test_epoch_integer_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "timestamp=1711234567890"
|
||||
result = normalize_message(msg)
|
||||
assert "1711234567890" not in result
|
||||
assert "<EPOCH>" in result
|
||||
|
||||
def test_small_number_not_epoch(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
# 4-digit number should become <NUM>, not <EPOCH>
|
||||
msg = "Status code 404 returned"
|
||||
result = normalize_message(msg)
|
||||
assert "<EPOCH>" not in result
|
||||
|
||||
|
||||
class TestEmailReplacement:
|
||||
"""Email addresses should be replaced with <EMAIL>."""
|
||||
|
||||
def test_simple_email_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "User user@example.com not found"
|
||||
result = normalize_message(msg)
|
||||
assert "user@example.com" not in result
|
||||
assert "<EMAIL>" in result
|
||||
|
||||
def test_email_with_subdomain_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Sent to andrew@api.nomadkaraoke.com"
|
||||
result = normalize_message(msg)
|
||||
assert "andrew@api.nomadkaraoke.com" not in result
|
||||
assert "<EMAIL>" in result
|
||||
|
||||
def test_email_with_plus_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Contact for test+filter@gmail.com"
|
||||
result = normalize_message(msg)
|
||||
assert "test+filter@gmail.com" not in result
|
||||
assert "<EMAIL>" in result
|
||||
|
||||
|
||||
class TestIPAddressReplacement:
|
||||
"""IP addresses should be replaced with <IP>."""
|
||||
|
||||
def test_ipv4_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Connection refused from 192.168.1.100"
|
||||
result = normalize_message(msg)
|
||||
assert "192.168.1.100" not in result
|
||||
assert "<IP>" in result
|
||||
|
||||
def test_ipv4_with_port_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Failed to connect to 10.0.0.1:8080"
|
||||
result = normalize_message(msg)
|
||||
assert "10.0.0.1" not in result
|
||||
assert "<IP>" in result
|
||||
|
||||
def test_multiple_ips_all_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Route from 10.0.0.1 to 172.16.0.254 failed"
|
||||
result = normalize_message(msg)
|
||||
assert "10.0.0.1" not in result
|
||||
assert "172.16.0.254" not in result
|
||||
|
||||
|
||||
class TestHexIDReplacement:
|
||||
"""Hex/alphanumeric IDs (8+ chars with both digits and letters) should be replaced with <ID>."""
|
||||
|
||||
def test_hex_id_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Resource abc12345def not found"
|
||||
result = normalize_message(msg)
|
||||
assert "abc12345def" not in result
|
||||
assert "<ID>" in result
|
||||
|
||||
def test_pure_alpha_word_not_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
# Pure alphabetic strings should not be replaced
|
||||
msg = "Authentication failed completely"
|
||||
result = normalize_message(msg)
|
||||
assert result == "Authentication failed completely"
|
||||
|
||||
def test_short_id_not_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
# IDs shorter than 8 chars should not be replaced
|
||||
msg = "Error in abc123 handler"
|
||||
result = normalize_message(msg)
|
||||
# Should not replace short mixed alphanum under 8 chars as <ID>
|
||||
assert "abc123" in result
|
||||
|
||||
|
||||
class TestLargeNumberReplacement:
|
||||
"""Numbers with 4+ digits should be replaced with <NUM>."""
|
||||
|
||||
def test_four_digit_number_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "HTTP error code 5000 encountered"
|
||||
result = normalize_message(msg)
|
||||
assert "5000" not in result
|
||||
assert "<NUM>" in result
|
||||
|
||||
def test_large_number_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Allocated 12345 bytes"
|
||||
result = normalize_message(msg)
|
||||
assert "12345" not in result
|
||||
assert "<NUM>" in result
|
||||
|
||||
def test_small_number_preserved(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
# 3-digit numbers like HTTP status codes should be preserved
|
||||
msg = "HTTP 404 Not Found"
|
||||
result = normalize_message(msg)
|
||||
assert "404" in result
|
||||
|
||||
def test_two_digit_number_preserved(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Retry attempt 42"
|
||||
result = normalize_message(msg)
|
||||
assert "42" in result
|
||||
|
||||
|
||||
class TestJobIDReplacement:
|
||||
"""Job IDs in paths should be replaced."""
|
||||
|
||||
def test_job_id_in_path_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Failed processing /jobs/abc123def456 in queue"
|
||||
result = normalize_message(msg)
|
||||
assert "abc123def456" not in result
|
||||
assert "/jobs/<ID>" in result
|
||||
|
||||
def test_job_id_alphanumeric_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Job at /jobs/XyZ9a1b2C3d4 timed out"
|
||||
result = normalize_message(msg)
|
||||
assert "XyZ9a1b2C3d4" not in result
|
||||
assert "/jobs/<ID>" in result
|
||||
|
||||
|
||||
class TestGCSPathReplacement:
|
||||
"""GCS paths should be normalized."""
|
||||
|
||||
def test_gcs_path_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Could not read gs://my-bucket/path/to/file.mp4"
|
||||
result = normalize_message(msg)
|
||||
assert "gs://my-bucket/path/to/file.mp4" not in result
|
||||
assert "gs://<BUCKET>/<PATH>" in result
|
||||
|
||||
def test_gcs_path_without_object_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Bucket access denied: gs://nomadkaraoke-prod-videos/"
|
||||
result = normalize_message(msg)
|
||||
assert "gs://nomadkaraoke-prod-videos/" not in result
|
||||
assert "gs://<BUCKET>" in result
|
||||
|
||||
def test_gcs_path_with_nested_path_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "File gs://nomad-audio/jobs/abc123/output/stem.wav not found"
|
||||
result = normalize_message(msg)
|
||||
assert "gs://nomad-audio/jobs/abc123/output/stem.wav" not in result
|
||||
assert "gs://<BUCKET>/<PATH>" in result
|
||||
|
||||
|
||||
class TestFirebaseUIDReplacement:
|
||||
"""Firebase UIDs (20-28 mixed-case alphanumeric) should be replaced with <UID>."""
|
||||
|
||||
def test_firebase_uid_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
# Firebase UIDs are 28 chars: letters and digits, mixed case
|
||||
msg = "User uid=ABC123defGHI456jklMNO7 not authorized"
|
||||
result = normalize_message(msg)
|
||||
assert "ABC123defGHI456jklMNO7" not in result
|
||||
assert "<UID>" in result
|
||||
|
||||
def test_firebase_uid_28_chars_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Auth failed for 8JkLmNoPqRsT1uVwXyZ23456AB"
|
||||
result = normalize_message(msg)
|
||||
assert "8JkLmNoPqRsT1uVwXyZ23456AB" not in result
|
||||
assert "<UID>" in result
|
||||
|
||||
|
||||
class TestFirestoreDocPathReplacement:
|
||||
"""Firestore document paths should be replaced with <DOC_PATH>."""
|
||||
|
||||
def test_firestore_doc_path_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Document jobs/abc123def/state_data/current does not exist"
|
||||
result = normalize_message(msg)
|
||||
assert "jobs/abc123def/state_data/current" not in result
|
||||
assert "<DOC_PATH>" in result
|
||||
|
||||
def test_firestore_users_path_replaced(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Permission denied for users/uid12345/profile/settings"
|
||||
result = normalize_message(msg)
|
||||
assert "users/uid12345/profile/settings" not in result
|
||||
assert "<DOC_PATH>" in result
|
||||
|
||||
|
||||
class TestURLNormalization:
|
||||
"""URLs should be stripped to domain only."""
|
||||
|
||||
def test_url_stripped_to_domain(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Failed to fetch https://api.example.com/v1/users/12345/data"
|
||||
result = normalize_message(msg)
|
||||
assert "/v1/users/12345/data" not in result
|
||||
assert "api.example.com" in result
|
||||
|
||||
def test_http_url_stripped(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Redirect from http://old.example.com/path?q=abc123"
|
||||
result = normalize_message(msg)
|
||||
assert "/path?q=abc123" not in result
|
||||
assert "old.example.com" in result
|
||||
|
||||
def test_url_with_port_domain_preserved(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Connection to https://internal.service.com:8080/api/endpoint failed"
|
||||
result = normalize_message(msg)
|
||||
assert "internal.service.com" in result
|
||||
|
||||
|
||||
class TestTruncation:
|
||||
"""Long messages should be truncated to MAX_NORMALIZED_MESSAGE_LENGTH (200 chars)."""
|
||||
|
||||
def test_long_message_truncated(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
from backend.services.error_monitor.config import MAX_NORMALIZED_MESSAGE_LENGTH
|
||||
|
||||
long_msg = "Error: " + "x" * 300
|
||||
result = normalize_message(long_msg)
|
||||
assert len(result) <= MAX_NORMALIZED_MESSAGE_LENGTH
|
||||
|
||||
def test_short_message_not_truncated(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Short error message"
|
||||
result = normalize_message(msg)
|
||||
assert result == msg
|
||||
|
||||
def test_exactly_200_chars_not_truncated(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "A" * 200
|
||||
result = normalize_message(msg)
|
||||
assert len(result) == 200
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""Edge cases for normalize_message."""
|
||||
|
||||
def test_empty_message_returns_empty_string(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
result = normalize_message("")
|
||||
assert result == ""
|
||||
|
||||
def test_no_replacements_returns_original(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Connection refused by server"
|
||||
result = normalize_message(msg)
|
||||
assert result == msg
|
||||
|
||||
def test_deterministic_same_input_same_output(self):
|
||||
from backend.services.error_monitor.normalizer import normalize_message
|
||||
|
||||
msg = "Job failed for 550e8400-e29b-41d4-a716-446655440000 at 2024-01-15T10:30:45Z"
|
||||
result1 = normalize_message(msg)
|
||||
result2 = normalize_message(msg)
|
||||
assert result1 == result2
|
||||
|
||||
|
||||
class TestComputePatternHash:
|
||||
"""Tests for the compute_pattern_hash function."""
|
||||
|
||||
def test_returns_64_char_hex(self):
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash
|
||||
|
||||
result = compute_pattern_hash("karaoke-backend", "Connection refused by server")
|
||||
assert isinstance(result, str)
|
||||
assert len(result) == 64
|
||||
# SHA-256 hex is lowercase hex
|
||||
assert all(c in "0123456789abcdef" for c in result)
|
||||
|
||||
def test_same_inputs_same_hash(self):
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash
|
||||
|
||||
h1 = compute_pattern_hash("karaoke-backend", "Connection refused by server")
|
||||
h2 = compute_pattern_hash("karaoke-backend", "Connection refused by server")
|
||||
assert h1 == h2
|
||||
|
||||
def test_different_services_different_hash(self):
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash
|
||||
|
||||
h1 = compute_pattern_hash("karaoke-backend", "Connection refused by server")
|
||||
h2 = compute_pattern_hash("audio-separator", "Connection refused by server")
|
||||
assert h1 != h2
|
||||
|
||||
def test_different_messages_different_hash(self):
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash
|
||||
|
||||
h1 = compute_pattern_hash("karaoke-backend", "Connection refused by server")
|
||||
h2 = compute_pattern_hash("karaoke-backend", "Timeout waiting for response")
|
||||
assert h1 != h2
|
||||
|
||||
def test_empty_service_and_message(self):
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash
|
||||
|
||||
result = compute_pattern_hash("", "")
|
||||
assert isinstance(result, str)
|
||||
assert len(result) == 64
|
||||
Reference in new issue
Block a user