Compare commits
17
Commits
55e5810e65
...
fe3ca11d8f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe3ca11d8f | ||
|
|
86c399f2da | ||
|
|
2a845e8b8d | ||
|
|
97742d4716 | ||
|
|
e47db12e4d | ||
|
|
bed156ae94 | ||
|
|
8e84f41924 | ||
|
|
167f23a99f | ||
|
|
ec46655e13 | ||
|
|
28a361314a | ||
|
|
bc02d28169 | ||
|
|
5ffe05206c | ||
|
|
1dbda03209 | ||
|
|
1ac27986cb | ||
|
|
21c0ffbe75 | ||
|
|
e74929e7f7 | ||
|
|
2fc4b88a80 |
No files matched your search
@@ -21,7 +21,7 @@ class ExternalReviewError(ValueError):
|
||||
|
||||
def map_observation(
|
||||
session: Session, observation: ExternalObservation, fish: Fish, waterbody: Waterbody,
|
||||
*, note: str | None = None,
|
||||
*, note: str | None = None, commit: bool = True,
|
||||
) -> ExternalObservation:
|
||||
if observation.status == "published":
|
||||
raise ExternalReviewError("published observation cannot be remapped")
|
||||
@@ -43,6 +43,7 @@ def map_observation(
|
||||
observation.status = "ready" if _complete(observation) else "mapped"
|
||||
_save_alias(session, observation, "fish", observation.fish_external_id or observation.fish_name, fish=fish)
|
||||
_save_alias(session, observation, "waterbody", observation.waterbody_external_id or observation.waterbody_name, waterbody=waterbody)
|
||||
if commit:
|
||||
session.commit()
|
||||
return observation
|
||||
|
||||
@@ -61,17 +62,22 @@ def suggest_aliases(session: Session, observation: ExternalObservation) -> tuple
|
||||
return (fish_alias.fish if fish_alias else None, waterbody_alias.waterbody if waterbody_alias else None)
|
||||
|
||||
|
||||
def reject_observation(session: Session, observation: ExternalObservation, *, reason: str) -> ExternalObservation:
|
||||
def reject_observation(
|
||||
session: Session, observation: ExternalObservation, *, reason: str, commit: bool = True,
|
||||
) -> ExternalObservation:
|
||||
if observation.status == "published":
|
||||
raise ExternalReviewError("published observation cannot be rejected")
|
||||
observation.status = "rejected"
|
||||
observation.review_note = reason
|
||||
observation.reviewed_at = datetime.now(timezone.utc)
|
||||
if commit:
|
||||
session.commit()
|
||||
return observation
|
||||
|
||||
|
||||
def publish_observation(session: Session, observation: ExternalObservation) -> CatchReport:
|
||||
def publish_observation(
|
||||
session: Session, observation: ExternalObservation, *, commit: bool = True,
|
||||
) -> CatchReport:
|
||||
if observation.catch_report is not None and observation.status == "published":
|
||||
return observation.catch_report
|
||||
if observation.status == "rejected":
|
||||
@@ -134,6 +140,7 @@ def publish_observation(session: Session, observation: ExternalObservation) -> C
|
||||
observation.catch_report = report
|
||||
observation.status = "published"
|
||||
observation.reviewed_at = now
|
||||
if commit:
|
||||
session.commit()
|
||||
return report
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ from rf4_research.media_assets import publish_quality_upgrades, rollback_quality
|
||||
from ..media_catalog import MEDIA_ROOT, review_assets, review_file
|
||||
from ..models import CatchReport, CommunityImportRun, DataSource, ExternalObservation, Fish, ModerationEvent, ModerationStatus, OfficialRecordImport, SourceType, Waterbody
|
||||
from ..public_cache import public_cache
|
||||
from ..schemas import AdminCatchReportOut, AdminMediaDecision, AdminMediaReviewOut, AdminMediaRollback, AdminModerationHistoryOut, AdminSourceStatusOut, CatchReportCreated, ExternalAliasSuggestionOut, ExternalObservationAction, ExternalObservationDecision, ExternalObservationMapping, ExternalObservationOut, ExternalObservationPublished, ImportRunOut, ModerationUpdate
|
||||
from ..schemas import AdminCatchReportOut, AdminMediaDecision, AdminMediaReviewOut, AdminMediaRollback, AdminModerationHistoryOut, AdminSourceStatusOut, CatchReportCreated, ExternalAliasSuggestionOut, ExternalObservationAction, ExternalObservationBulkAction, ExternalObservationBulkDecision, ExternalObservationBulkMapping, ExternalObservationBulkResult, ExternalObservationDecision, ExternalObservationMapping, ExternalObservationOut, ExternalObservationPublished, ImportRunOut, ModerationBulkResult, ModerationBulkUpdate, ModerationUpdate
|
||||
from ..storage import delete_screenshot, signed_screenshot_url
|
||||
from ..time_utils import aware
|
||||
|
||||
@@ -343,6 +343,34 @@ def admin_map_external_observation(
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.patch("/api/v1/admin/external-observations/bulk-mapping", response_model=ExternalObservationBulkResult)
|
||||
def admin_map_external_observations_bulk(
|
||||
payload: ExternalObservationBulkMapping, db: Db, _: Annotated[str, Depends(_admin)],
|
||||
) -> ExternalObservationBulkResult:
|
||||
ids = [item.id for item in payload.items]
|
||||
observations = list(db.scalars(select(ExternalObservation).where(ExternalObservation.id.in_(ids)).with_for_update()))
|
||||
by_id = {item.id: item for item in observations}
|
||||
expected = {item.id: item.expected_version for item in payload.items}
|
||||
if len(by_id) != len(ids) or any(
|
||||
item.status in {"published", "withdrawn"} or item.moderation_version != expected[item.id]
|
||||
for item in observations
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="one or more observations changed; reload the queue")
|
||||
fish = db.scalar(select(Fish).where(Fish.slug == payload.fish_slug))
|
||||
waterbody = db.scalar(select(Waterbody).where(Waterbody.slug == payload.waterbody_slug))
|
||||
if fish is None or waterbody is None:
|
||||
raise HTTPException(status_code=422, detail="unknown fish or waterbody")
|
||||
try:
|
||||
for item in observations:
|
||||
item.moderation_version += 1
|
||||
map_observation(db, item, fish, waterbody, note=payload.note, commit=False)
|
||||
db.commit()
|
||||
except ExternalReviewError as exc:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return ExternalObservationBulkResult(updated=len(observations))
|
||||
|
||||
|
||||
@router.post("/api/v1/admin/external-observations/{observation_id}/publish", response_model=ExternalObservationPublished)
|
||||
def admin_publish_external_observation(
|
||||
observation_id: UUID, payload: ExternalObservationAction, db: Db, _: Annotated[str, Depends(_admin)],
|
||||
@@ -361,6 +389,30 @@ def admin_publish_external_observation(
|
||||
return ExternalObservationPublished(observation_id=observation.id, catch_report_id=report.id, status=observation.status)
|
||||
|
||||
|
||||
@router.post("/api/v1/admin/external-observations/bulk-publish", response_model=ExternalObservationBulkResult)
|
||||
def admin_publish_external_observations_bulk(
|
||||
payload: ExternalObservationBulkAction, db: Db, _: Annotated[str, Depends(_admin)],
|
||||
) -> ExternalObservationBulkResult:
|
||||
ids = [item.id for item in payload.items]
|
||||
observations = list(db.scalars(select(ExternalObservation).where(ExternalObservation.id.in_(ids)).with_for_update()))
|
||||
expected = {item.id: item.expected_version for item in payload.items}
|
||||
if len({item.id for item in observations}) != len(ids) or any(
|
||||
item.status in {"rejected", "withdrawn"} or item.moderation_version != expected[item.id]
|
||||
for item in observations
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="one or more observations changed; reload the queue")
|
||||
try:
|
||||
for item in observations:
|
||||
item.moderation_version += 1
|
||||
publish_observation(db, item, commit=False)
|
||||
db.commit()
|
||||
except ExternalReviewError as exc:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
public_cache.invalidate()
|
||||
return ExternalObservationBulkResult(updated=len(observations))
|
||||
|
||||
|
||||
@router.patch("/api/v1/admin/external-observations/{observation_id}/reject", response_model=ExternalObservationOut)
|
||||
def admin_reject_external_observation(
|
||||
observation_id: UUID, payload: ExternalObservationDecision, db: Db,
|
||||
@@ -378,6 +430,21 @@ def admin_reject_external_observation(
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.patch("/api/v1/admin/external-observations/bulk-reject", response_model=ExternalObservationBulkResult)
|
||||
def admin_reject_external_observations_bulk(payload: ExternalObservationBulkDecision, db: Db, _: Annotated[str, Depends(_admin)]) -> ExternalObservationBulkResult:
|
||||
ids = [item.id for item in payload.items]
|
||||
observations = list(db.scalars(select(ExternalObservation).where(ExternalObservation.id.in_(ids)).with_for_update()))
|
||||
by_id = {item.id: item for item in observations}
|
||||
expected = {item.id: item.expected_version for item in payload.items}
|
||||
if len(by_id) != len(ids) or any(item.status in {"published", "rejected", "withdrawn"} or item.moderation_version != expected[item.id] for item in observations):
|
||||
raise HTTPException(status_code=409, detail="one or more observations changed; reload the queue")
|
||||
for item in observations:
|
||||
item.moderation_version += 1
|
||||
reject_observation(db, item, reason=payload.reason, commit=False)
|
||||
db.commit()
|
||||
return ExternalObservationBulkResult(updated=len(observations))
|
||||
|
||||
|
||||
@router.get("/api/v1/admin/catch-reports", response_model=list[AdminCatchReportOut])
|
||||
def admin_reports(db: Db, _: Annotated[str, Depends(_admin)], status: ModerationStatus = ModerationStatus.pending, limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)) -> list[AdminCatchReportOut]:
|
||||
reports = list(db.scalars(select(CatchReport).options(joinedload(CatchReport.fish), joinedload(CatchReport.waterbody), joinedload(CatchReport.spot), joinedload(CatchReport.bait)).where(CatchReport.source_type == SourceType.user, CatchReport.moderation_status == status, CatchReport.deleted_at.is_(None)).order_by(CatchReport.reported_at, CatchReport.id).offset(offset).limit(limit)))
|
||||
@@ -400,6 +467,27 @@ def moderate_report(report_id: UUID, payload: ModerationUpdate, db: Db, moderato
|
||||
return CatchReportCreated(id=report.id, moderation_status=report.moderation_status.value)
|
||||
|
||||
|
||||
@router.post("/api/v1/admin/catch-reports/bulk", response_model=ModerationBulkResult)
|
||||
def moderate_reports_bulk(payload: ModerationBulkUpdate, db: Db, moderator: Annotated[str, Depends(_admin)]) -> ModerationBulkResult:
|
||||
if payload.status == "rejected" and not (payload.reason or "").strip():
|
||||
raise HTTPException(status_code=422, detail="rejection reason required")
|
||||
ids = [item.id for item in payload.items]
|
||||
reports = list(db.scalars(select(CatchReport).where(CatchReport.id.in_(ids)).with_for_update()))
|
||||
by_id = {report.id: report for report in reports}
|
||||
if len(by_id) != len(ids) or any(report.source_type != SourceType.user or report.deleted_at is not None or report.moderation_status != ModerationStatus.pending for report in reports):
|
||||
raise HTTPException(status_code=409, detail="one or more reports are no longer pending")
|
||||
expected = {item.id: item.expected_version for item in payload.items}
|
||||
if any(report.moderation_version != expected[report.id] for report in reports):
|
||||
raise HTTPException(status_code=409, detail="one or more reports changed; reload the queue")
|
||||
for report in reports:
|
||||
previous = report.moderation_status
|
||||
report.moderation_status = ModerationStatus(payload.status)
|
||||
report.moderation_version += 1
|
||||
db.add(ModerationEvent(catch_report=report, created_at=datetime.now(timezone.utc), previous_status=previous, new_status=report.moderation_status, moderator=moderator, reason=payload.reason))
|
||||
db.commit(); public_cache.invalidate()
|
||||
return ModerationBulkResult(updated=len(reports))
|
||||
|
||||
|
||||
@router.delete("/api/v1/admin/catch-reports/{report_id}", status_code=204, response_class=Response)
|
||||
def delete_report(report_id: UUID, db: Db, moderator: Annotated[str, Depends(_admin)], expected_version: int = Query(ge=0)) -> Response:
|
||||
report = db.scalar(select(CatchReport).where(CatchReport.id == report_id).with_for_update())
|
||||
|
||||
@@ -326,6 +326,28 @@ class ModerationUpdate(BaseModel):
|
||||
return value
|
||||
|
||||
|
||||
class ModerationBulkItem(BaseModel):
|
||||
id: UUID
|
||||
expected_version: int = Field(ge=0)
|
||||
|
||||
|
||||
class ModerationBulkUpdate(BaseModel):
|
||||
status: str
|
||||
reason: str | None = Field(default=None, max_length=1000)
|
||||
items: list[ModerationBulkItem] = Field(min_length=1, max_length=50)
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def known_bulk_status(cls, value: str) -> str:
|
||||
if value not in {"approved", "rejected", "pending"}:
|
||||
raise ValueError("unknown moderation status")
|
||||
return value
|
||||
|
||||
|
||||
class ModerationBulkResult(BaseModel):
|
||||
updated: int
|
||||
|
||||
|
||||
class ExternalObservationOut(BaseModel):
|
||||
id: UUID
|
||||
source_system: str
|
||||
@@ -381,6 +403,31 @@ class ExternalObservationDecision(BaseModel):
|
||||
expected_version: int = Field(ge=0)
|
||||
|
||||
|
||||
class ExternalObservationBulkItem(BaseModel):
|
||||
id: UUID
|
||||
expected_version: int = Field(ge=0)
|
||||
|
||||
|
||||
class ExternalObservationBulkDecision(BaseModel):
|
||||
reason: str = Field(min_length=1, max_length=1000)
|
||||
items: list[ExternalObservationBulkItem] = Field(min_length=1, max_length=50)
|
||||
|
||||
|
||||
class ExternalObservationBulkAction(BaseModel):
|
||||
items: list[ExternalObservationBulkItem] = Field(min_length=1, max_length=50)
|
||||
|
||||
|
||||
class ExternalObservationBulkMapping(BaseModel):
|
||||
fish_slug: str
|
||||
waterbody_slug: str
|
||||
note: str | None = Field(default=None, max_length=1000)
|
||||
items: list[ExternalObservationBulkItem] = Field(min_length=1, max_length=50)
|
||||
|
||||
|
||||
class ExternalObservationBulkResult(BaseModel):
|
||||
updated: int
|
||||
|
||||
|
||||
class ExternalObservationAction(BaseModel):
|
||||
expected_version: int = Field(ge=0)
|
||||
|
||||
|
||||
@@ -1093,6 +1093,122 @@
|
||||
"title": "ExternalObservationAction",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationBulkAction": {
|
||||
"properties": {
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkItem"
|
||||
},
|
||||
"maxItems": 50,
|
||||
"minItems": 1,
|
||||
"title": "Items",
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"items"
|
||||
],
|
||||
"title": "ExternalObservationBulkAction",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationBulkDecision": {
|
||||
"properties": {
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkItem"
|
||||
},
|
||||
"maxItems": 50,
|
||||
"minItems": 1,
|
||||
"title": "Items",
|
||||
"type": "array"
|
||||
},
|
||||
"reason": {
|
||||
"maxLength": 1000,
|
||||
"minLength": 1,
|
||||
"title": "Reason",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"reason",
|
||||
"items"
|
||||
],
|
||||
"title": "ExternalObservationBulkDecision",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationBulkItem": {
|
||||
"properties": {
|
||||
"expected_version": {
|
||||
"minimum": 0.0,
|
||||
"title": "Expected Version",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"format": "uuid",
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"expected_version"
|
||||
],
|
||||
"title": "ExternalObservationBulkItem",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationBulkMapping": {
|
||||
"properties": {
|
||||
"fish_slug": {
|
||||
"title": "Fish Slug",
|
||||
"type": "string"
|
||||
},
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkItem"
|
||||
},
|
||||
"maxItems": 50,
|
||||
"minItems": 1,
|
||||
"title": "Items",
|
||||
"type": "array"
|
||||
},
|
||||
"note": {
|
||||
"anyOf": [
|
||||
{
|
||||
"maxLength": 1000,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Note"
|
||||
},
|
||||
"waterbody_slug": {
|
||||
"title": "Waterbody Slug",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"fish_slug",
|
||||
"waterbody_slug",
|
||||
"items"
|
||||
],
|
||||
"title": "ExternalObservationBulkMapping",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationBulkResult": {
|
||||
"properties": {
|
||||
"updated": {
|
||||
"title": "Updated",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"updated"
|
||||
],
|
||||
"title": "ExternalObservationBulkResult",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalObservationDecision": {
|
||||
"properties": {
|
||||
"expected_version": {
|
||||
@@ -1670,6 +1786,74 @@
|
||||
"title": "ImportRunPublicOut",
|
||||
"type": "object"
|
||||
},
|
||||
"ModerationBulkItem": {
|
||||
"properties": {
|
||||
"expected_version": {
|
||||
"minimum": 0.0,
|
||||
"title": "Expected Version",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"format": "uuid",
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"expected_version"
|
||||
],
|
||||
"title": "ModerationBulkItem",
|
||||
"type": "object"
|
||||
},
|
||||
"ModerationBulkResult": {
|
||||
"properties": {
|
||||
"updated": {
|
||||
"title": "Updated",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"updated"
|
||||
],
|
||||
"title": "ModerationBulkResult",
|
||||
"type": "object"
|
||||
},
|
||||
"ModerationBulkUpdate": {
|
||||
"properties": {
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ModerationBulkItem"
|
||||
},
|
||||
"maxItems": 50,
|
||||
"minItems": 1,
|
||||
"title": "Items",
|
||||
"type": "array"
|
||||
},
|
||||
"reason": {
|
||||
"anyOf": [
|
||||
{
|
||||
"maxLength": 1000,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Reason"
|
||||
},
|
||||
"status": {
|
||||
"title": "Status",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"items"
|
||||
],
|
||||
"title": "ModerationBulkUpdate",
|
||||
"type": "object"
|
||||
},
|
||||
"ModerationStatus": {
|
||||
"enum": [
|
||||
"pending",
|
||||
@@ -1879,6 +2063,37 @@
|
||||
"title": "PaginatedOfficialRecordOut",
|
||||
"type": "object"
|
||||
},
|
||||
"PaginatedRigOut": {
|
||||
"properties": {
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/RigSummaryOut"
|
||||
},
|
||||
"title": "Items",
|
||||
"type": "array"
|
||||
},
|
||||
"limit": {
|
||||
"title": "Limit",
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"title": "Offset",
|
||||
"type": "integer"
|
||||
},
|
||||
"total": {
|
||||
"title": "Total",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"items",
|
||||
"total",
|
||||
"limit",
|
||||
"offset"
|
||||
],
|
||||
"title": "PaginatedRigOut",
|
||||
"type": "object"
|
||||
},
|
||||
"PaginatedTackleItemOut": {
|
||||
"properties": {
|
||||
"items": {
|
||||
@@ -2136,6 +2351,86 @@
|
||||
"title": "RigOut",
|
||||
"type": "object"
|
||||
},
|
||||
"RigSummaryOut": {
|
||||
"properties": {
|
||||
"component_count": {
|
||||
"title": "Component Count",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"format": "uuid",
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
},
|
||||
"missing_fields": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"title": "Missing Fields",
|
||||
"type": "array"
|
||||
},
|
||||
"name": {
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"source_checked_at": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source Checked At"
|
||||
},
|
||||
"source_external_id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source External Id"
|
||||
},
|
||||
"source_system": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source System"
|
||||
},
|
||||
"source_url": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source Url"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"source_system",
|
||||
"source_external_id",
|
||||
"source_url",
|
||||
"source_checked_at",
|
||||
"component_count"
|
||||
],
|
||||
"title": "RigSummaryOut",
|
||||
"type": "object"
|
||||
},
|
||||
"SourceStatusOut": {
|
||||
"properties": {
|
||||
"last_started_at": {
|
||||
@@ -2300,6 +2595,18 @@
|
||||
"title": "Last Seen At",
|
||||
"type": "string"
|
||||
},
|
||||
"rig_id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Rig Id"
|
||||
},
|
||||
"role": {
|
||||
"title": "Role",
|
||||
"type": "string"
|
||||
@@ -2308,6 +2615,18 @@
|
||||
"title": "Status",
|
||||
"type": "string"
|
||||
},
|
||||
"tackle_item_id": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "uuid",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Tackle Item Id"
|
||||
},
|
||||
"unique_players": {
|
||||
"title": "Unique Players",
|
||||
"type": "integer"
|
||||
@@ -2374,6 +2693,13 @@
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"related_rigs": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/TackleItemRigOut"
|
||||
},
|
||||
"title": "Related Rigs",
|
||||
"type": "array"
|
||||
},
|
||||
"source_checked_at": {
|
||||
"anyOf": [
|
||||
{
|
||||
@@ -2458,6 +2784,55 @@
|
||||
"title": "TackleItemOut",
|
||||
"type": "object"
|
||||
},
|
||||
"TackleItemRigOut": {
|
||||
"properties": {
|
||||
"component_count": {
|
||||
"title": "Component Count",
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"format": "uuid",
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"source_checked_at": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source Checked At"
|
||||
},
|
||||
"source_system": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Source System"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"source_system",
|
||||
"source_checked_at",
|
||||
"component_count"
|
||||
],
|
||||
"title": "TackleItemRigOut",
|
||||
"type": "object"
|
||||
},
|
||||
"ValidationError": {
|
||||
"properties": {
|
||||
"loc": {
|
||||
@@ -2876,6 +3251,62 @@
|
||||
"summary": "Admin Reports"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/catch-reports/bulk": {
|
||||
"post": {
|
||||
"operationId": "moderate_reports_bulk_api_v1_admin_catch_reports_bulk_post",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "authorization",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Authorization"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ModerationBulkUpdate"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ModerationBulkResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"summary": "Moderate Reports Bulk"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/catch-reports/{report_id}": {
|
||||
"delete": {
|
||||
"operationId": "delete_report_api_v1_admin_catch_reports__report_id__delete",
|
||||
@@ -3204,6 +3635,174 @@
|
||||
"summary": "Admin External Observations"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/external-observations/bulk-mapping": {
|
||||
"patch": {
|
||||
"operationId": "admin_map_external_observations_bulk_api_v1_admin_external_observations_bulk_mapping_patch",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "authorization",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Authorization"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkMapping"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"summary": "Admin Map External Observations Bulk"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/external-observations/bulk-publish": {
|
||||
"post": {
|
||||
"operationId": "admin_publish_external_observations_bulk_api_v1_admin_external_observations_bulk_publish_post",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "authorization",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Authorization"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkAction"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"summary": "Admin Publish External Observations Bulk"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/external-observations/bulk-reject": {
|
||||
"patch": {
|
||||
"operationId": "admin_reject_external_observations_bulk_api_v1_admin_external_observations_bulk_reject_patch",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "authorization",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Authorization"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkDecision"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExternalObservationBulkResult"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"summary": "Admin Reject External Observations Bulk"
|
||||
}
|
||||
},
|
||||
"/api/v1/admin/external-observations/{observation_id}/alias-suggestions": {
|
||||
"get": {
|
||||
"operationId": "admin_external_alias_suggestions_api_v1_admin_external_observations__observation_id__alias_suggestions_get",
|
||||
@@ -4087,6 +4686,22 @@
|
||||
"title": "Method"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "role",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Role"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "hours",
|
||||
@@ -4580,6 +5195,23 @@
|
||||
],
|
||||
"title": "Entity Type"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "media_role",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"pattern": "^(waterbody_cover|waterbody_map|waterbody_depth_map|waterbody_screenshot|tackle_card|tackle_detail|rig_diagram|tackle_screenshot)$",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Media Role"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -4721,6 +5353,22 @@
|
||||
"title": "Category"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Q"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "limit",
|
||||
@@ -5026,6 +5674,22 @@
|
||||
"title": "Category"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Q"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "brand",
|
||||
@@ -5164,6 +5828,75 @@
|
||||
"summary": "Tackle Item"
|
||||
}
|
||||
},
|
||||
"/api/v1/tackle/rigs": {
|
||||
"get": {
|
||||
"operationId": "tackle_rigs_api_v1_tackle_rigs_get",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Q"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "limit",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"default": 48,
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
"title": "Limit",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "offset",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"default": 0,
|
||||
"minimum": 0,
|
||||
"title": "Offset",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PaginatedRigOut"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
},
|
||||
"422": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Validation Error"
|
||||
}
|
||||
},
|
||||
"summary": "Tackle Rigs"
|
||||
}
|
||||
},
|
||||
"/api/v1/tackle/rigs/{rig_id}": {
|
||||
"get": {
|
||||
"operationId": "rig_detail_api_v1_tackle_rigs__rig_id__get",
|
||||
|
||||
@@ -17,7 +17,7 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
<label>Порядок<select name="order"><option value="risk">Сначала требуют внимания</option><option value="newest">Сначала новые</option><option value="oldest">Сначала старые</option></select></label>
|
||||
<button data-action="primary" type="submit">Применить</button>
|
||||
</form>
|
||||
<div class="notice error" data-admin-error role="alert" hidden></div><div class="notice success" data-admin-status role="status" hidden></div><div class="moderation-list" data-external-list aria-live="polite"></div>
|
||||
<div class="notice error" data-admin-error role="alert" hidden></div><div class="notice success" data-admin-status role="status" hidden></div><label><input type="checkbox" data-external-select-all> Выбрать все записи на странице</label><div data-external-bulk hidden><strong data-external-bulk-count>0 выбрано</strong><label>Рыба<select data-external-bulk-fish><option value="">Выберите…</option></select></label><label>Водоём<select data-external-bulk-waterbody><option value="">Выберите…</option></select></label><textarea data-external-bulk-reason rows="1" maxlength="1000" placeholder="Примечание или причина отклонения"></textarea><button data-action="secondary" type="button" data-external-bulk-map>Сопоставить выбранные</button><button data-action="primary" type="button" data-external-bulk-publish>Опубликовать выбранные</button><button data-action="danger" type="button" data-external-bulk-reject>Отклонить выбранные</button></div><div class="moderation-list" data-external-list aria-live="polite"></div>
|
||||
<nav data-pages aria-label="Страницы очереди" hidden>
|
||||
<button data-action="secondary" type="button" data-previous>Предыдущая</button>
|
||||
<span data-page-number aria-live="polite"></span>
|
||||
@@ -40,6 +40,8 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const sessionBar = document.querySelector<HTMLElement>(".admin-session-bar");
|
||||
const logout = document.querySelector<HTMLButtonElement>("[data-admin-logout]");
|
||||
const filters = document.querySelector<HTMLFormElement>(".admin-queue-filters");
|
||||
const bulk = document.querySelector<HTMLElement>("[data-external-bulk]");
|
||||
const selectAll = document.querySelector<HTMLInputElement>("[data-external-select-all]");
|
||||
let offset = 0;
|
||||
let token = ""; let fishes: Record<string, string>[] = []; let waters: Record<string, string>[] = [];
|
||||
let sessionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -51,6 +53,14 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const succeed = (message: string) => { if (error) error.hidden = true; if (status) { status.textContent = message; status.hidden = false; } };
|
||||
const endSession = (message?: string) => { token = ""; if (sessionTimer) clearTimeout(sessionTimer); sessionTimer = undefined; if (login) { login.hidden = false; login.reset(); } if (sessionBar) sessionBar.hidden = true; if (filters) filters.hidden = true; if (list) list.innerHTML = ""; pages?.setAttribute("hidden", ""); if (message) fail(message); };
|
||||
const keepSession = () => { if (sessionTimer) clearTimeout(sessionTimer); sessionTimer = setTimeout(() => endSession("Сессия завершена после 15 минут бездействия. Введите токен снова."), 15 * 60 * 1000); };
|
||||
const syncBulk = () => { const inputs = [...(list?.querySelectorAll<HTMLInputElement>("[data-external-select]") ?? [])]; const selected = inputs.filter(input => input.checked).length; if (bulk) bulk.hidden = selected === 0; if (selectAll) { selectAll.checked = inputs.length > 0 && selected === inputs.length; selectAll.indeterminate = selected > 0 && selected < inputs.length; } const count = bulk?.querySelector<HTMLElement>("[data-external-bulk-count]"); if (count) count.textContent = `${selected} выбрано`; };
|
||||
const hydrateBulk = () => { list?.querySelectorAll<HTMLElement>("[data-observation-id]").forEach(card => { if (card.querySelector("[data-external-select]")) return; const label = document.createElement("label"); label.innerHTML = `<input type="checkbox" data-external-select aria-label="Выбрать наблюдение">`; card.prepend(label); }); const fishSelect = bulk?.querySelector<HTMLSelectElement>("[data-external-bulk-fish]"); const waterSelect = bulk?.querySelector<HTMLSelectElement>("[data-external-bulk-waterbody]"); if (fishSelect && fishSelect.options.length === 1 && fishes.length) fishSelect.innerHTML = '<option value="">Выберите…</option>' + options(fishes); if (waterSelect && waterSelect.options.length === 1 && waters.length) waterSelect.innerHTML = '<option value="">Выберите…</option>' + options(waters); syncBulk(); };
|
||||
const selectedCards = () => [...(list?.querySelectorAll<HTMLInputElement>("[data-external-select]:checked") ?? [])].map(input => input.closest<HTMLElement>("[data-observation-id]")).filter((card): card is HTMLElement => Boolean(card));
|
||||
bulk?.querySelector<HTMLButtonElement>("[data-external-bulk-map]")?.addEventListener("click", async () => { const cards = selectedCards(); const fish_slug = bulk.querySelector<HTMLSelectElement>("[data-external-bulk-fish]")?.value; const waterbody_slug = bulk.querySelector<HTMLSelectElement>("[data-external-bulk-waterbody]")?.value; if (!cards.length) return; if (!fish_slug || !waterbody_slug) { fail("Выберите каноническую рыбу и водоём."); return; } try { await json(`${root?.dataset.apiUrl}/api/v1/admin/external-observations/bulk-mapping`, {method:"PATCH",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({fish_slug,waterbody_slug,note:bulk.querySelector<HTMLTextAreaElement>("[data-external-bulk-reason]")?.value.trim() || null,items:cards.map(card => ({id:card.dataset.observationId,expected_version:Number(card.dataset.version)}))})}); await loadQueue(); succeed(`Сопоставлено наблюдений: ${cards.length}.`); } catch (cause) { fail(cause instanceof Error ? cause.message : "Ошибка пакетного сопоставления."); } });
|
||||
bulk?.querySelector<HTMLButtonElement>("[data-external-bulk-publish]")?.addEventListener("click", async () => { const cards = selectedCards(); if (!cards.length) return; try { await json(`${root?.dataset.apiUrl}/api/v1/admin/external-observations/bulk-publish`, {method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({items:cards.map(card => ({id:card.dataset.observationId,expected_version:Number(card.dataset.version)}))})}); await loadQueue(); succeed(`Опубликовано наблюдений: ${cards.length}.`); } catch (cause) { fail(cause instanceof Error ? cause.message : "Ошибка пакетной публикации."); } });
|
||||
bulk?.querySelector<HTMLButtonElement>("[data-external-bulk-reject]")?.addEventListener("click", async () => { const cards = selectedCards(); const reason = bulk.querySelector<HTMLTextAreaElement>("[data-external-bulk-reason]")?.value.trim(); if (!cards.length) return; if (!reason) { fail("Укажите причину отклонения."); return; } try { await json(`${root?.dataset.apiUrl}/api/v1/admin/external-observations/bulk-reject`, {method:"PATCH",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({reason,items:cards.map(card => ({id:card.dataset.observationId,expected_version:Number(card.dataset.version)}))})}); await loadQueue(); succeed(`Отклонено наблюдений: ${cards.length}.`); } catch (cause) { fail(cause instanceof Error ? cause.message : "Ошибка пакетного отклонения."); } });
|
||||
list?.addEventListener("change", event => { if ((event.target as HTMLElement).matches("[data-external-select]")) syncBulk(); });
|
||||
selectAll?.addEventListener("change", () => { list?.querySelectorAll<HTMLInputElement>("[data-external-select]").forEach(input => input.checked = selectAll.checked); syncBulk(); });
|
||||
const options = (items: Record<string, string>[], selected?: unknown) => items.map(item => `<option value="${esc(item.slug)}" ${item.slug === selected ? "selected" : ""}>${esc(item.name_ru)}</option>`).join("");
|
||||
async function json(url: string, init: RequestInit = {}) { const response = await fetch(url, init); if (response.status === 409) { await loadQueue(); throw new Error("Запись уже изменена в другой вкладке. Очередь обновлена."); } if (!response.ok) { if (adminEndsSession(response.status)) endSession(); throw new Error(adminErrorMessage(response.status, `Запрос завершился ошибкой ${response.status}.`)); } if ((init.headers as Record<string, string> | undefined)?.Authorization) keepSession(); return response.json(); }
|
||||
async function loadQueue() {
|
||||
@@ -68,6 +78,7 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
if (pageNumber) pageNumber.textContent = `Страница ${offset / 50 + 1}`;
|
||||
if (!pending.length) { list.innerHTML = '<div class="state"><h2>Очередь пуста</h2><p>Все внешние записи обработаны.</p></div>'; return; }
|
||||
list.innerHTML = pending.map((row: Record<string, unknown>) => { const complete = row.x != null && row.y != null && row.weight_g != null; const sourceUrl = safeHttpUrl(row.source_url); return `<article class="moderation-card" data-observation-id="${esc(row.id)}" data-version="${esc(row.moderation_version)}"><div class="moderation-summary"><span class="activity-pill"><i></i>${esc(row.source_system)} · ${esc(row.status)}</span><h2>${esc(row.fish_name)}</h2><p>${esc(row.waterbody_name)}</p><dl><div><dt>Координаты</dt><dd>${row.x == null || row.y == null ? "нет" : `${esc(row.x)}:${esc(row.y)}`}</dd></div><div><dt>Вес</dt><dd>${row.weight_g == null ? "нет" : `${esc(row.weight_g)} г`}</dd></div><div><dt>ID источника</dt><dd>${esc(row.source_external_id)}</dd></div><div><dt>Состояние</dt><dd>${complete ? "полная запись" : "неполная"}</dd></div></dl>${sourceUrl ? `<a href="${sourceUrl}" target="_blank" rel="noreferrer">Открыть первоисточник</a>` : '<span class="privacy">Ссылка источника имеет небезопасный формат</span>'}</div><div class="moderation-actions"><label>Каноническая рыба<select name="fish" required><option value="">Выберите…</option>${options(fishes, row.fish_slug)}</select></label><label>Канонический водоём<select name="waterbody" required><option value="">Выберите…</option>${options(waters, row.waterbody_slug)}</select></label><label>Примечание<textarea name="note" rows="2" maxlength="1000">${esc(row.review_note ?? "")}</textarea></label><p data-alias-message role="status"></p><div><button data-action="secondary" type="button" data-suggest>Подсказать соответствия</button><button data-action="secondary" type="button" data-map>Сопоставить</button><button data-action="primary" type="button" data-publish ${complete && row.status === "ready" ? "" : "disabled"}>Опубликовать</button><button data-action="danger" type="button" data-reject>Отклонить</button></div></div></article>`; }).join("");
|
||||
hydrateBulk();
|
||||
const payloadLabels: Record<string, string> = {bait:"Приманка",fishing_method:"Метод ловли",rig_type:"Оснастка",retrieve_method:"Проводка",retrieve_speed:"Скорость проводки",player_name:"Игрок",published_at:"Опубликовано источником",region:"Регион",category:"Категория"};
|
||||
const missingLabels: Record<string, string> = {coordinates:"координаты",weight_g:"вес"};
|
||||
pending.forEach((row: Record<string, unknown>, index: number) => {
|
||||
|
||||
@@ -27,6 +27,7 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
let sessionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let importCooldownUntil = 0;
|
||||
let importCooldownTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let importHistoryOffset = 5;
|
||||
const esc = (value: unknown) => String(value ?? "—").replace(/[&<>'"]/g, char => ({"&":"&","<":"<",">":">","'":"'",'"':"""}[char] ?? char));
|
||||
const fail = (message: string) => { if (error) { error.textContent = message; error.hidden = false; } };
|
||||
const succeed = (message: string) => { if (error) error.hidden = true; if (status) { status.textContent = message; status.hidden = false; } };
|
||||
@@ -34,9 +35,14 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const keepSession = () => { if (sessionTimer) clearTimeout(sessionTimer); sessionTimer = setTimeout(() => endSession("Сессия завершена после 15 минут бездействия. Введите токен снова."), 15 * 60 * 1000); };
|
||||
const syncImportButton = () => { const button = content?.querySelector<HTMLButtonElement>("[data-official-import]"); if (!button) return; const seconds = Math.max(0, Math.ceil((importCooldownUntil - Date.now()) / 1000)); button.disabled = seconds > 0; button.textContent = seconds > 0 ? `Повторить через ${seconds < 60 ? `${seconds} с` : `${Math.ceil(seconds / 60)} мин`}` : "Запустить импорт"; button.setAttribute("aria-disabled", String(seconds > 0)); };
|
||||
const startImportCooldown = (seconds: number) => { if (!Number.isFinite(seconds) || seconds <= 0) return; importCooldownUntil = Math.max(importCooldownUntil, Date.now() + Math.ceil(seconds) * 1000); if (importCooldownTimer) clearInterval(importCooldownTimer); syncImportButton(); importCooldownTimer = setInterval(() => { syncImportButton(); if (Date.now() >= importCooldownUntil && importCooldownTimer) { clearInterval(importCooldownTimer); importCooldownTimer = undefined; } }, 1000); };
|
||||
const importStatusLabels: Record<string, string> = {running:"Выполняется",success:"Успешно",partial:"Частично",failed:"Ошибка"};
|
||||
const importRow = (run: Record<string, unknown>) => { const state = String(run.status); const rows = Number(run.rows_seen ?? 0); const created = Number(run.rows_created ?? 0); const updated = Number(run.rows_updated ?? 0); const result = rows ? ` · ${rows} строк · +${created}/↻${updated}` : ""; const finished = run.finished_at ? ` · завершён ${new Date(String(run.finished_at)).toLocaleString("ru-RU")}` : ""; return `<li><span>${esc(importStatusLabels[state] ?? state)}<small>${esc(result)}</small></span><time>${esc(new Date(String(run.started_at)).toLocaleString("ru-RU"))}<small>${esc(finished)}</small></time></li>`; };
|
||||
const ensureImportMoreButton = () => { const section = content?.querySelector<HTMLElement>(".admin-dashboard-grid section:nth-child(2)"); const list = section?.querySelector<HTMLUListElement>("ul"); if (!section || !list || list.children.length < 5 || section.querySelector("[data-import-more]")) return; const button = document.createElement("button"); button.type = "button"; button.dataset.action = "quiet"; button.dataset.importMore = "true"; button.textContent = "Показать ещё импорты"; list.after(button); };
|
||||
window.setInterval(ensureImportMoreButton, 1000);
|
||||
async function authorizedJson(path: string) { const response = await fetch(`${root?.dataset.apiUrl}${path}`, {headers:{Authorization:`Bearer ${token}`}}); if (!response.ok) { if (adminEndsSession(response.status)) endSession(); throw new Error(adminErrorMessage(response.status, "Не удалось загрузить административные данные.")); } keepSession(); return response.json(); }
|
||||
async function loadDashboard() {
|
||||
if (!content) return;
|
||||
importHistoryOffset = 5;
|
||||
error?.setAttribute("hidden", ""); status?.setAttribute("hidden", ""); content.setAttribute("aria-busy", "true"); content.innerHTML = '<div class="loading-grid" aria-hidden="true"><div class="loading-card"></div><div class="loading-card"></div></div>';
|
||||
const diagnostics = await authorizedJson("/api/v1/admin/diagnostics");
|
||||
const [imports, sources, history] = await Promise.all([authorizedJson("/api/v1/admin/imports?limit=5"), authorizedJson("/api/v1/admin/source-status"), authorizedJson("/api/v1/admin/moderation-history?limit=8")]);
|
||||
@@ -52,7 +58,7 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const historyRows = (history as Record<string, unknown>[]).map(event => { const action = String(event.action); const type = String(event.entity_type); return `<li><span><b>${esc(typeLabels[type] ?? "Запись")}</b> · ${esc(actionLabels[action] ?? action)}${event.reason ? `<small>${esc(event.reason)}</small>` : ""}</span><time>${esc(new Date(String(event.decided_at)).toLocaleString("ru-RU"))}</time></li>`; }).join("");
|
||||
content.removeAttribute("aria-busy"); content.innerHTML = `<div class="admin-kpis"><a href="/admin/moderation"><span>Уловы на проверке</span><strong>${esc(reports.pending ?? 0)}</strong><small>Открыть очередь →</small></a><a href="/admin/external-sources"><span>Наблюдения в staging</span><strong>${esc((observations.staged ?? 0) + (observations.mapped ?? 0) + (observations.ready ?? 0))}</strong><small>Проверить источники →</small></a><article><span>Одобрено уловов</span><strong>${esc(reports.approved ?? 0)}</strong><small>Участвуют в статистике</small></article><article><span>Источников включено</span><strong>${esc(diagnostics.counts?.enabled_data_sources ?? 0)}</strong><small>из ${esc(diagnostics.counts?.data_sources ?? 0)}</small></article></div><div class="admin-dashboard-grid"><section><div class="admin-section-head"><h2>Состояние источников</h2><button type="button" data-action="secondary" data-refresh>Обновить</button></div><ul>${sourceRows || "<li>Нет данных</li>"}</ul><a href="/status">Публичная страница состояния →</a><br /><a href="/admin/media">Проверить медиа →</a></section><section><div class="admin-section-head"><h2>Последние импорты</h2><button type="button" data-action="secondary" data-official-import>Запустить импорт</button></div><ul>${importRows || "<li>Запусков пока нет</li>"}</ul><p class="privacy">Импорт обращается к официальному источнику и соблюдает cooldown.</p></section><section class="admin-history"><div class="admin-section-head"><h2>Последние решения</h2><button type="button" data-action="secondary" data-history-export>Экспорт JSON</button></div><ul>${historyRows || "<li>Решений пока нет</li>"}</ul><p class="privacy">Экспорт обезличен: без UUID, модератора, причин и исходных данных.</p></section></div>`;
|
||||
}
|
||||
login?.addEventListener("submit", async event => { event.preventDefault(); token = String(new FormData(login).get("token") || ""); try { await loadDashboard(); login.hidden = true; if (sessionBar) sessionBar.hidden = false; } catch (cause) { if (content) { content.removeAttribute("aria-busy"); content.innerHTML = ""; } fail(cause instanceof Error ? cause.message : "Ошибка загрузки."); } });
|
||||
login?.addEventListener("submit", async event => { event.preventDefault(); token = String(new FormData(login).get("token") || ""); try { await loadDashboard(); ensureImportMoreButton(); login.hidden = true; if (sessionBar) sessionBar.hidden = false; } catch (cause) { if (content) { content.removeAttribute("aria-busy"); content.innerHTML = ""; } fail(cause instanceof Error ? cause.message : "Ошибка загрузки."); } });
|
||||
logout?.addEventListener("click", () => endSession("Вы вышли из административной панели."));
|
||||
content?.addEventListener("click", async event => {
|
||||
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-official-import]");
|
||||
@@ -72,6 +78,19 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
} catch (cause) { fail(cause instanceof Error ? cause.message : "Операция не выполнена."); }
|
||||
finally { syncImportButton(); }
|
||||
}, true);
|
||||
content?.addEventListener("click", async event => {
|
||||
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-import-more]");
|
||||
if (!button) return;
|
||||
event.preventDefault(); event.stopImmediatePropagation(); button.disabled = true;
|
||||
try {
|
||||
const rows = await authorizedJson(`/api/v1/admin/imports?limit=5&offset=${importHistoryOffset}`) as Record<string, unknown>[];
|
||||
const list = content?.querySelector<HTMLUListElement>(".admin-dashboard-grid section:nth-child(2) ul");
|
||||
if (list) list.insertAdjacentHTML("beforeend", rows.map(importRow).join(""));
|
||||
importHistoryOffset += rows.length;
|
||||
if (rows.length < 5) button.remove(); else button.disabled = false;
|
||||
keepSession();
|
||||
} catch (cause) { button.disabled = false; fail(cause instanceof Error ? cause.message : "Не удалось загрузить историю импортов."); }
|
||||
}, true);
|
||||
content?.addEventListener("click", async event => {
|
||||
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-history-export],[data-official-import],[data-refresh]"); if (!button) return;
|
||||
button.disabled = true;
|
||||
|
||||
@@ -10,7 +10,7 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
<form class="admin-login" autocomplete="off"><label>Административный токен<input name="token" type="password" required autocomplete="off" /></label><button data-action="primary" type="submit">Открыть очередь</button></form>
|
||||
<p class="privacy">Токен хранится только в памяти страницы и не записывается в URL или localStorage.</p>
|
||||
<div class="admin-session-bar" hidden><span>Административная сессия активна</span><button data-action="secondary" type="button" data-admin-logout>Выйти</button></div>
|
||||
<div class="notice error" data-admin-error role="alert" hidden></div><div class="notice success" data-admin-status role="status" hidden></div><div class="moderation-list" data-moderation-list aria-live="polite"></div>
|
||||
<div class="notice error" data-admin-error role="alert" hidden></div><div class="notice success" data-admin-status role="status" hidden></div><label class="queue-select-all"><input type="checkbox" data-bulk-select-all> Выбрать все записи на странице</label><div class="moderation-bulk" data-bulk hidden><strong data-bulk-count>0 выбрано</strong><label>Причина отклонения<textarea data-bulk-reason rows="1" maxlength="1000"></textarea></label><button data-action="primary" type="button" data-bulk-approve>Одобрить выбранные</button><button data-action="danger" type="button" data-bulk-reject>Отклонить выбранные</button></div><div class="moderation-list" data-moderation-list aria-live="polite"></div>
|
||||
<nav data-pages aria-label="Страницы очереди" hidden><button data-action="secondary" type="button" data-previous>Предыдущая</button><span data-page-number aria-live="polite"></span><button data-action="secondary" type="button" data-next>Следующая</button><button data-action="secondary" type="button" data-refresh>Обновить</button></nav>
|
||||
<p class="admin-shortcuts"><kbd>A</kbd> одобрить карточку с фокусом · отклонение и удаление — только кнопками</p>
|
||||
</section>
|
||||
@@ -28,6 +28,8 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const pageNumber = document.querySelector<HTMLElement>("[data-page-number]");
|
||||
const sessionBar = document.querySelector<HTMLElement>(".admin-session-bar");
|
||||
const logout = document.querySelector<HTMLButtonElement>("[data-admin-logout]");
|
||||
const bulk = document.querySelector<HTMLElement>("[data-bulk]");
|
||||
const selectAll = document.querySelector<HTMLInputElement>("[data-bulk-select-all]");
|
||||
let token = "";
|
||||
let offset = 0;
|
||||
let sessionTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -39,6 +41,14 @@ const apiUrl = import.meta.env.PUBLIC_API_URL || "http://localhost:8000";
|
||||
const succeed = (message: string) => { if (error) error.hidden = true; if (status) { status.textContent = message; status.hidden = false; } };
|
||||
const endSession = (message?: string) => { token = ""; if (sessionTimer) clearTimeout(sessionTimer); sessionTimer = undefined; if (login) { login.hidden = false; login.reset(); } if (sessionBar) sessionBar.hidden = true; if (list) list.innerHTML = ""; if (message) fail(message); };
|
||||
const keepSession = () => { if (sessionTimer) clearTimeout(sessionTimer); sessionTimer = setTimeout(() => endSession("Сессия завершена после 15 минут бездействия. Введите токен снова."), 15 * 60 * 1000); };
|
||||
const syncBulk = () => { const inputs = [...(list?.querySelectorAll<HTMLInputElement>("[data-bulk-select]") ?? [])]; const cards = inputs.filter(input => input.checked); if (bulk) bulk.hidden = cards.length === 0; if (selectAll) { selectAll.checked = inputs.length > 0 && cards.length === inputs.length; selectAll.indeterminate = cards.length > 0 && cards.length < inputs.length; } const count = bulk?.querySelector<HTMLElement>("[data-bulk-count]"); if (count) count.textContent = `${cards.length} выбрано`; };
|
||||
const hydrateBulk = () => { list?.querySelectorAll<HTMLElement>("[data-report-id]").forEach(card => { if (card.querySelector("[data-bulk-select]")) return; const label = document.createElement("label"); label.className = "moderation-select"; label.innerHTML = `<input type="checkbox" data-bulk-select aria-label="Выбрать улов ${card.querySelector("h2")?.textContent ?? ""}">`; card.prepend(label); }); syncBulk(); };
|
||||
window.setInterval(hydrateBulk, 1000);
|
||||
async function runBulk(statusValue: "approved" | "rejected") { const selected = [...(list?.querySelectorAll<HTMLInputElement>("[data-bulk-select]:checked") ?? [])].map(input => input.closest<HTMLElement>("[data-report-id]")); const reason = bulk?.querySelector<HTMLTextAreaElement>("[data-bulk-reason]")?.value.trim() || null; if (!selected.length) return; if (statusValue === "rejected" && !reason) { fail("Укажите причину отклонения."); return; } const buttons = bulk?.querySelectorAll<HTMLButtonElement>("button") ?? []; buttons.forEach(button => button.disabled = true); try { const response = await fetch(`${root?.dataset.apiUrl}/api/v1/admin/catch-reports/bulk`, {method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({status:statusValue,reason,items:selected.map(card => ({id:card?.dataset.reportId,expected_version:Number(card?.dataset.version)}))})}); if (response.status === 409) { await loadQueue(); throw new Error("Часть выбранных записей уже изменена. Очередь обновлена."); } if (!response.ok) throw new Error(adminErrorMessage(response.status, "Не удалось применить пакетное решение.")); keepSession(); await loadQueue(); succeed(`Обработано записей: ${selected.length}.`); } catch (cause) { fail(cause instanceof Error ? cause.message : "Ошибка пакетного решения."); } finally { buttons.forEach(button => button.disabled = false); syncBulk(); } }
|
||||
bulk?.querySelector<HTMLButtonElement>("[data-bulk-approve]")?.addEventListener("click", () => runBulk("approved"));
|
||||
bulk?.querySelector<HTMLButtonElement>("[data-bulk-reject]")?.addEventListener("click", () => runBulk("rejected"));
|
||||
list?.addEventListener("change", event => { if ((event.target as HTMLElement).matches("[data-bulk-select]")) syncBulk(); });
|
||||
selectAll?.addEventListener("change", () => { list?.querySelectorAll<HTMLInputElement>("[data-bulk-select]").forEach(input => input.checked = selectAll.checked); syncBulk(); });
|
||||
async function loadQueue() {
|
||||
if (!root || !list) return;
|
||||
error?.setAttribute("hidden", ""); setLoading(true); list.innerHTML = loadingCards();
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
.admin-queue-filters{display:grid;grid-template-columns:1.3fr repeat(3,1fr) auto;gap:10px;align-items:end;margin:0 0 18px;padding:16px;border-radius:12px;background:var(--deep)}.admin-queue-filters[hidden]{display:none}.admin-queue-filters label{color:#b8c5c2;font-size:11px;text-transform:uppercase;letter-spacing:.08em}.admin-queue-filters input,.admin-queue-filters select{display:block;width:100%;height:42px;margin-top:6px;padding:0 10px;border:1px solid #ffffff29;border-radius:8px;background:#ffffff0c;color:#fff}.admin-queue-filters option{color:var(--ink)}.admin-queue-filters button{height:42px}
|
||||
.admin-shortcuts{margin:14px 0;color:var(--text-muted);font-size:12px}.admin-shortcuts kbd{padding:2px 6px;border:1px solid var(--line);border-bottom-width:2px;border-radius:5px;background:var(--surface);font:700 11px Inter,sans-serif}.moderation-card:focus-within{outline:2px solid var(--focus);outline-offset:3px}
|
||||
.moderation-provenance{margin-top:18px;border-top:1px solid var(--border-soft);padding-top:14px}.moderation-provenance summary{cursor:pointer;color:var(--deep);font-weight:700}.moderation-provenance dl{margin-top:14px}.moderation-provenance p{margin:12px 0 0;color:var(--text-muted);font-size:12px;line-height:1.5}
|
||||
.queue-select-all{display:inline-flex;align-items:center;gap:8px;margin:0 0 12px;color:var(--text-muted);font-size:13px}.moderation-select{display:block;grid-column:1/-1}.moderation-select input{width:18px;height:18px}.moderation-bulk,[data-external-bulk]{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin:0 0 18px;padding:14px;border:1px solid var(--border);border-radius:12px;background:var(--surface);color:var(--text)}.moderation-bulk strong,[data-external-bulk] strong{margin-right:auto}.moderation-bulk label,[data-external-bulk] label{min-width:180px;color:var(--text-muted);font-size:11px;text-transform:uppercase;letter-spacing:.08em}.moderation-bulk textarea,[data-external-bulk] textarea,.moderation-bulk select,[data-external-bulk] select{display:block;width:100%;margin-top:5px;padding:9px;border:1px solid var(--border);border-radius:7px;background:var(--surface-field);color:var(--text);resize:vertical}.moderation-bulk button,[data-external-bulk] button{min-height:42px;padding:0 15px;border:0;border-radius:8px;background:var(--lime);color:var(--deep);font-weight:750}.moderation-bulk button[data-action="danger"],[data-external-bulk] button[data-action="danger"]{background:var(--danger-soft);color:var(--danger)}
|
||||
@media(max-width:900px){.admin-queue-filters{grid-template-columns:1fr 1fr}}@media(max-width:520px){.admin-queue-filters{grid-template-columns:1fr}}
|
||||
.admin-dashboard{width:min(1120px,calc(100% - 64px));margin:0 auto 100px}.admin-dashboard>.privacy{margin:10px 4px 25px}.admin-kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}.admin-kpis>a,.admin-kpis>article,.admin-dashboard-grid>section{padding:22px;border:1px solid var(--line);border-radius:14px;background:var(--surface)}.admin-kpis>a{color:inherit;text-decoration:none}.admin-kpis span,.admin-kpis small{display:block;color:var(--text-muted)}.admin-kpis strong{display:block;margin:10px 0;font:400 42px Georgia,serif;color:var(--deep)}.admin-kpis>a:hover{border-color:var(--focus);transform:translateY(-2px)}.admin-dashboard-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:18px}.admin-dashboard-grid h2{margin:0 0 16px;font:400 25px Georgia,serif}.admin-dashboard-grid ul{list-style:none;margin:0 0 16px;padding:0}.admin-dashboard-grid li{display:flex;justify-content:space-between;gap:14px;padding:10px 0;border-bottom:1px solid var(--border-soft);font-size:13px}.admin-dashboard-grid li span{display:flex;align-items:center;gap:8px}.admin-dashboard-grid time{color:var(--text-muted)}
|
||||
@media(max-width:900px){.admin-kpis{grid-template-columns:1fr 1fr}}@media(max-width:720px){.admin-dashboard{width:calc(100% - 28px)}.admin-kpis,.admin-dashboard-grid{grid-template-columns:1fr}}
|
||||
|
||||
@@ -76,6 +76,7 @@
|
||||
|
||||
.active-filters span, .spot-card, .record-table, .report-form,
|
||||
.periods, .detail-grid aside, .screenshot-retry, .moderation-card,
|
||||
.moderation-bulk, [data-external-bulk],
|
||||
.admin-kpis > a, .admin-kpis > article, .admin-dashboard-grid > section,
|
||||
.source-health-grid article, .state, .load-more, .signal-more {
|
||||
background: var(--surface-elevated);
|
||||
@@ -88,7 +89,8 @@
|
||||
|
||||
.spot-card:hover { background: var(--surface-raised); border-color: var(--border-strong); box-shadow: 0 18px 40px var(--shadow-color); }
|
||||
.report-form input, .report-form textarea, .report-form select,
|
||||
.moderation-actions textarea { background: var(--surface-control); color: var(--text-primary); border-color: var(--border-strong); }
|
||||
.moderation-actions textarea, .moderation-bulk textarea, .moderation-bulk select,
|
||||
[data-external-bulk] textarea, [data-external-bulk] select { background: var(--surface-control); color: var(--text-primary); border-color: var(--border-strong); }
|
||||
.record-head, .no-proof { background: var(--surface-raised); }
|
||||
.record-row, .periods > div, .catch-list article, .detail-grid aside li,
|
||||
.bait-line, .spot-stats, .moderation-summary dl div,
|
||||
@@ -190,7 +192,7 @@
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.theme-switcher, .theme-switcher button, .spot-card, .record-table,
|
||||
.report-form, .moderation-card, .catalog-grid > a, .data-passport,
|
||||
.report-form, .moderation-card, .moderation-bulk, [data-external-bulk], .catalog-grid > a, .data-passport,
|
||||
.source-chip, .notice, .state { border: 1px solid CanvasText; }
|
||||
.theme-switcher button[aria-pressed="true"] { background: Highlight; color: HighlightText; }
|
||||
.source-chip i, .health-state i, .quality-chip i, .activity-pill i { forced-color-adjust: none; }
|
||||
|
||||
+1
-1
@@ -128,7 +128,7 @@
|
||||
|
||||
- [x] **M01 · Усиление административного входа.** Сохранён двойной барьер Caddy Basic Auth + API Bearer; внешние ссылки ограничены `http/https`, UI завершает сессию после 15 минут бездействия, предоставляет явный выход и возвращает вход после `401`. Неуспешная API-авторизация ограничена постоянным счётчиком по HMAC-идентификатору клиента с учётом доверенного proxy; успешный вход очищает ошибки клиента. Bearer-токен не сохраняется в URL, cookie или browser storage.
|
||||
- [x] **M02 · Единый dashboard.** `/admin` показывает счётчики pending-уловов и staging-наблюдений, число активных источников, их безопасные публичные статусы, последние импорты и быстрые переходы в очереди. Dashboard использует тот же memory-only токен и 15-минутную сессию, не выводит секреты, внутренние URL и полные тексты исключений.
|
||||
- [x] **M03 · Эффективность очередей.** Очередь внешних наблюдений получила серверные фильтры по источнику и полноте, безопасный поиск по рыбе/водоёму и сортировку по свежести или риску; проблемный порядок поднимает неполные и несопоставленные записи, а параметры работают до пагинации. Обе очереди блокируют всю карточку на время решения, сохраняют введённую причину при ошибке, явно подтверждают успех и переводят фокус к следующей записи. Безопасные горячие клавиши работают только внутри карточки с фокусом и отключены в полях ввода; отклонение и удаление намеренно оставлены только на кнопках.
|
||||
- [x] **M03 · Эффективность очередей.** Очередь внешних наблюдений получила серверные фильтры по источнику и полноте, безопасный поиск по рыбе/водоёму и сортировку по свежести или риску; проблемный порядок поднимает неполные и несопоставленные записи, а параметры работают до пагинации. Обе очереди блокируют всю карточку на время решения, сохраняют введённую причину при ошибке, явно подтверждают успех и переводят фокус к следующей записи. Для внешних наблюдений добавлены пакетное сопоставление, публикация и отклонение выбранных записей с общей заметкой/причиной, проверкой `moderation_version`, одной транзакцией и выбором всех записей текущей страницы; пользовательская очередь получила такой же выбор всей страницы. Массовая публикация использует те же проверки полноты, координат и канонических связей, что и одиночная операция, и инвалидирует публичный cache после общего commit. Bulk-панели используют семантические theme-токены, mobile reflow и forced-colors границы. Безопасные горячие клавиши работают только внутри карточки с фокусом и отключены в полях ввода; отклонение и удаление намеренно оставлены только на кнопках.
|
||||
- [x] **M04 · Полный provenance и история решений.** Admin API отдаёт время первого/последнего обнаружения и проверки, явный список missing fields и allowlist безопасных скалярных полей исходной записи; карточка показывает их перед публикацией. Единый read-only журнал объединяет решения по пользовательским и внешним записям без ников, URL и исходных payload и отображается на dashboard. Отдельный JSON-экспорт исключает также UUID сущностей, оператора и свободный текст причины; токен остаётся только в памяти вкладки.
|
||||
- [x] **M05 · Защита от параллельных решений.** Обе очереди отдают `moderation_version`; mapping/publish/reject/approve/delete требуют увиденную версию и повторно сверяют её под row lock. Успешное решение атомарно увеличивает version, а устаревшая вкладка получает понятный `409` и автоматически перезагружает очередь. Схема обновляется линейной миграцией `0015`.
|
||||
- [ ] **M06 · Персональные роли — после пилота.** Если модераторов станет больше одного, заменить общий токен индивидуальными аккаунтами, короткими сессиями, отзывом доступа и ролями; писать идентификатор оператора в аудит. Для одного владельца альфы не добавлять отдельный auth-сервис заранее.
|
||||
|
||||
Reference in new issue
Block a user