Files
smart-org/apps/api/app/domain/audit/models.py
T
mjalmoudy94 e56f105db3 رفع فلو دعوت عضو: لینک کلیک‌پذیر و صفحهٔ پذیرش دعوت
لینک دعوت هم کلیک‌پذیر نبود و هم کار نمی‌کرد؛ چهار نقص هم‌زمان:

- `invite_url` نسبی بود (`/accept-invite?token=…`) و host نداشت → حالا از
  `settings.app_url` آدرس مطلق ساخته می‌شود.
- صفحهٔ `/accept-invite` در اپ Next وجود نداشت → ۴۰۴.
- هیچ اندپوینت پذیرش دعوت در بک‌اند نبود؛ `InviteRepository.mark_accepted`
  نوشته شده بود ولی هرگز صدا زده نمی‌شد، پس توکن مصرف نمی‌شد.
- در تنظیمات، لینک به‌صورت متن ساده در `<p>` رندر می‌شد.

بک‌اند:
- روتر `app/interfaces/http/routers/invites.py`:
  `GET /api/invites/{token}` (پیش‌نمایش) و `POST /api/invites/accept`.
  عمداً زیر `/organizations/{org_id}` نیست: دعوت‌شونده هنوز عضو نیست و
  `get_org_context` ردش می‌کند، پس خود توکن مجوز است. accept ایدمپوتنت است.
- `AuditAction.MEMBER_JOIN = "member.join"`.
- رفع باگ نهفته: `Invite.is_expired()` بین `expires_at` خوانده‌شده از SQLite
  (naive) و `utcnow()` (aware) خطای مقایسه می‌داد. طبق قرارداد موجود پروژه
  (`_aware` در `adapters/agy.py`)، در `repositories/identity.py` تابع `_aware`
  اضافه و روی `expires_at`/`accepted_at` اعمال شد.

فرانت:
- صفحهٔ `app/accept-invite/page.tsx` با پیش‌نمایش سازمان/نقش و پذیرش؛ پس از
  پذیرش `setActiveOrganization` می‌کند تا در همان سازمان لند کند.
- قراردادهای `InvitePreview`/`AcceptInviteResult` و کلاینت
  `previewInvite`/`acceptInvite`.
- `login`/`signup` پارامتر `?next=` را می‌فهمند (فقط same-origin) تا توکن دعوت
  در مسیر احراز هویت گم نشود.
- `settings`: لینک به `<a>` واقعی + دکمهٔ «کپی لینک».

تست: `tests/test_invites.py` (۶) و `src/test/accept-invite.test.tsx` (۵).
بک‌اند ۲۵۲ سبز + ruff/mypy تمیز؛ فرانت ۶۱ سبز + tsc/eslint تمیز.
2026-10-13 17:47:26 +03:30

156 lines
5.0 KiB
Python

"""Observability & Audit domain: the immutable trail of who did what."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from app.domain.base import new_id, utcnow
class AuditAction:
"""Well-known auditable actions. Free-form strings are allowed but these are
the ones the application layer emits so far."""
LOGIN = "auth.login"
LOGOUT = "auth.logout"
SIGNUP = "auth.signup"
ORG_CREATE = "organization.create"
ORG_DELETE = "organization.delete"
MEMBER_INVITE = "member.invite"
#: An invited user redeemed their token and joined the organization.
MEMBER_JOIN = "member.join"
MEMBER_ROLE_CHANGE = "member.role_change"
MEMBER_REMOVE = "member.remove"
EMPLOYEE_CREATE = "employee.create"
EMPLOYEE_UPDATE = "employee.update"
REPO_CREATE = "repo.create"
REPO_DELETE = "repo.delete"
DOMAIN_CREATE = "domain.create"
DOMAIN_DELETE = "domain.delete"
SANDBOX_COMMAND = "sandbox.command"
SANDBOX_DESTROY = "sandbox.destroy"
#: A platform worker stopped a sandbox session that had gone idle. System
#: action, not a tenant one — the actor is the platform, not a user.
SANDBOX_REAP = "sandbox.reap"
APPROVAL_DECISION = "approval.decision"
BILLING_CREDIT = "billing.credit"
BILLING_PAYMENT = "billing.payment"
PROVIDER_CHANGE = "provider.change"
MODEL_CHANGE = "model.change"
ROUTING_CHANGE = "routing.change"
PROJECT_CREATE = "project.create"
PROJECT_DELETE = "project.delete"
TASK_CREATE = "task.create"
RUN_CANCEL = "run.cancel"
#: A platform owner triaged an error in the console. Auditable so "who
#: decided this bug was fixed?" has an answer.
ERROR_RESOLVE = "error.resolve"
@dataclass(slots=True, kw_only=True)
class AuditEvent:
action: str
organization_id: str | None = None
actor_user_id: str | None = None
target_type: str = ""
target_id: str = ""
metadata_json: dict = field(default_factory=dict)
ip_address: str = ""
user_agent: str = ""
id: str = field(default_factory=new_id)
created_at: datetime = field(default_factory=utcnow)
@dataclass(slots=True, kw_only=True)
class Trace:
organization_id: str
name: str = ""
run_id: str | None = None
id: str = field(default_factory=new_id)
created_at: datetime = field(default_factory=utcnow)
@dataclass(slots=True, kw_only=True)
class Span:
trace_id: str
name: str
kind: str = "internal"
parent_span_id: str | None = None
attributes_json: dict = field(default_factory=dict)
id: str = field(default_factory=new_id)
started_at: datetime = field(default_factory=utcnow)
ended_at: datetime | None = None
@property
def duration_ms(self) -> int | None:
if self.ended_at is None:
return None
return int((self.ended_at - self.started_at).total_seconds() * 1000)
@dataclass(slots=True, kw_only=True)
class ErrorEvent:
"""A persisted failure, recorded so it can be diagnosed later.
Deliberately *not* a domain aggregate: nothing in the business rules depends
on it. It is an operational record, which is why it carries transport-level
detail (method, path, status code) that no domain model would ever hold.
"""
kind: str
message: str
organization_id: str | None = None
run_id: str | None = None
stack: str = ""
metadata_json: dict = field(default_factory=dict)
#: Where the failure happened: ``http``, ``worker`` or ``startup``.
source: str = "http"
#: ``error`` for anything unexpected, ``warning`` for expected 4xx noise,
#: ``critical`` for startup/infrastructure failures.
severity: str = "error"
#: Exception class name (``ValueError``, ``IntegrityError``, …). Empty when
#: the failure was not an exception.
error_type: str = ""
#: Stable hash of the failure's identity, so a thousand occurrences of the
#: same bug group into one row in the console instead of a thousand.
fingerprint: str = ""
status_code: int | None = None
method: str = ""
path: str = ""
user_id: str | None = None
#: Correlates this record with the response the caller received and with
#: every log line written while handling the same request.
request_id: str = ""
ip: str = ""
user_agent: str = ""
resolved_at: datetime | None = None
resolved_note: str = ""
id: str = field(default_factory=new_id)
created_at: datetime = field(default_factory=utcnow)
class ErrorSource:
"""Where an error was caught. Kept as strings so a new source needs no
migration."""
HTTP = "http"
WORKER = "worker"
STARTUP = "startup"
class ErrorSeverity:
ERROR = "error"
WARNING = "warning"
CRITICAL = "critical"
@dataclass(slots=True, kw_only=True)
class QualityMetric:
organization_id: str
name: str
value: float
dimensions_json: dict = field(default_factory=dict)
id: str = field(default_factory=new_id)
created_at: datetime = field(default_factory=utcnow)