Задача 039: статус устройства и сведения об устройстве в списке адресов
Статус устройства (Активен / Выключен / На обслуживании), назначается вручную на экране устройств: колонка «Статус», выбор в диалоге, смена — в журнал. Миграция 0016, существующие устройства — «Активен». В списке адресов префикса колонки «Тип устройства», «Устройство», «Статус устройства» (join без N+1). pytest не прогнан: учётная запись admin из .env отключена на стенде. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aeb89dbded
commit
7d998066f5
10 files changed
+199
-19
No files matched your search
+30
-8
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import Address, AddressStatus, Device, Organization, Prefix, PrefixStatus, User, Vrf
|
||||
from app.models import Address, AddressStatus, Device, DeviceType, Organization, Prefix, PrefixStatus, User, Vrf
|
||||
from app.security import admin_user, current_user
|
||||
from app.services import (
|
||||
MAX_OFFSET, apply_update, audit, blockers, capacity, commit, count, flush, contains, free_page, get_or_404, network_role, next_free_address, next_free_subnet, refuse_delete,
|
||||
@@ -346,14 +346,30 @@ def delete_prefix(id: int, force: bool = False, db: Session = Depends(get_db), u
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- addresses
|
||||
def _addr_out(a: Address, device_name: str | None = None) -> s.AddressOut:
|
||||
def _addr_out(
|
||||
a: Address, device_name: str | None = None, device_type_name: str | None = None, device_status: str | None = None,
|
||||
) -> s.AddressOut: # изменение 039: device_type_name, device_status
|
||||
return s.AddressOut(
|
||||
id=a.id, prefix_id=a.prefix_id, address=s.ip_text(a.address), status=a.status.value,
|
||||
dns_name=a.dns_name, description=a.description, device_id=a.device_id, device_name=device_name,
|
||||
device_type_name=device_type_name, device_status=device_status,
|
||||
note=a.note, updated_at=a.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _device_info(db: Session, device_id: int | None) -> tuple[str | None, str | None, str | None]:
|
||||
"""(имя, тип, статус) устройства одним запросом — для одиночных ответов (создание/правка/автоназначение адреса).
|
||||
В списке (list_addresses) те же поля даёт join, без запроса на каждую строку (изменение 039)."""
|
||||
if device_id is None:
|
||||
return None, None, None
|
||||
row = db.execute(
|
||||
select(Device.name, DeviceType.name, Device.status)
|
||||
.join(DeviceType, DeviceType.id == Device.device_type_id)
|
||||
.where(Device.id == device_id)
|
||||
).first()
|
||||
return (row[0], row[1], row[2].value) if row else (None, None, None)
|
||||
|
||||
|
||||
def _check_device(db: Session, user: User, prefix: Prefix, device_id: int | None):
|
||||
if device_id is not None:
|
||||
d = get_or_404(db, Device, device_id, "Устройство")
|
||||
@@ -396,15 +412,21 @@ def list_addresses(
|
||||
flt.append(Address.status == AddressStatus(status))
|
||||
if q:
|
||||
flt.append(or_(contains(func.host(Address.address), q), contains(Address.dns_name, q), contains(Address.description, q)))
|
||||
stmt = select(Address, Device.name).outerjoin(Device, Device.id == Address.device_id).where(*flt)
|
||||
# изменение 039: тип и статус устройства — тем же join, без запроса на каждую строку
|
||||
stmt = (
|
||||
select(Address, Device.name, DeviceType.name, Device.status)
|
||||
.outerjoin(Device, Device.id == Address.device_id)
|
||||
.outerjoin(DeviceType, DeviceType.id == Device.device_type_id)
|
||||
.where(*flt)
|
||||
)
|
||||
mixed = not status and not q and cap <= FREE_LISTING_LIMIT # малая подсеть: занятые и свободные вперемешку (список ограничен размером подсети)
|
||||
if mixed:
|
||||
rows = [_addr_out(a, dn) for a, dn in db.execute(stmt.order_by(Address.address)).all()]
|
||||
rows = [_addr_out(a, dn, dtn, ds.value if ds else None) for a, dn, dtn, ds in db.execute(stmt.order_by(Address.address)).all()]
|
||||
rows = sorted(rows + free_rows(free_page(net, occupied(), 0, cap)), key=lambda r: ipaddress.ip_address(r.address))
|
||||
return s.AddressPage(items=rows[offset:offset + limit], total=len(rows), summary=summary)
|
||||
total = count(db, select(Address.id).where(*flt))
|
||||
page = db.execute(stmt.order_by(Address.address).limit(limit).offset(offset)).all()
|
||||
return s.AddressPage(items=[_addr_out(a, dn) for a, dn in page], total=total, summary=summary)
|
||||
return s.AddressPage(items=[_addr_out(a, dn, dtn, ds.value if ds else None) for a, dn, dtn, ds in page], total=total, summary=summary)
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses", response_model=s.AddressOut, status_code=201)
|
||||
@@ -427,7 +449,7 @@ def create_address(id: int, body: s.AddressIn, db: Session = Depends(get_db), us
|
||||
audit(db, user, "address", a, "assigned" if a.status == AddressStatus.assigned else "created", body.address, organization_id=p.organization_id) # изменение 032: organization_id
|
||||
commit(db, "Адрес уже есть в этом префиксе")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
return _addr_out(a, *_device_info(db, a.device_id)) # изменение 039
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses/next", response_model=s.AddressOut, status_code=201)
|
||||
@@ -450,7 +472,7 @@ def allocate_next(
|
||||
audit(db, user, "address", a, "assigned", ip, organization_id=p.organization_id) # изменение 032: organization_id
|
||||
commit(db, "Адрес уже занят, повторите запрос")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
return _addr_out(a, *_device_info(db, a.device_id)) # изменение 039
|
||||
|
||||
|
||||
@router.patch("/addresses/{id}", response_model=s.AddressOut)
|
||||
@@ -466,7 +488,7 @@ def update_address(id: int, body: s.AddressUpdate, db: Session = Depends(get_db)
|
||||
audit(db, user, "address", a, "updated", s.ip_text(a.address), {k: str(v) for k, v in changed.items()}, organization_id=p.organization_id) # изменение 032: organization_id
|
||||
commit(db)
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
return _addr_out(a, *_device_info(db, a.device_id)) # изменение 039
|
||||
|
||||
|
||||
@router.delete("/addresses/{id}", status_code=204)
|
||||
|
||||
+1
-1
@@ -228,7 +228,7 @@ def _device_outs(db: Session, devices: list[Device]) -> list[s.DeviceOut]:
|
||||
rows = by_device.get(d.id, [])
|
||||
out.append(s.DeviceOut(
|
||||
id=d.id, name=d.name, device_type_id=d.device_type_id, device_type_name=type_names[d.device_type_id],
|
||||
organization_id=d.organization_id, mac=d.mac, note=d.note,
|
||||
organization_id=d.organization_id, mac=d.mac, note=d.note, status=d.status, # изменение 039
|
||||
ip_addresses=[s.ip_text(r[0]) for r in rows], first_prefix_id=rows[0][1] if rows else None,
|
||||
all_deprecated=bool(rows) and all(r[2] == AddressStatus.deprecated for r in rows),
|
||||
))
|
||||
|
||||
@@ -32,6 +32,12 @@ class Role(str, enum.Enum):
|
||||
viewer = "viewer"
|
||||
|
||||
|
||||
class DeviceStatus(str, enum.Enum): # изменение 039: эксплуатационный статус устройства, назначается вручную
|
||||
active = "active"
|
||||
off = "off"
|
||||
maintenance = "maintenance"
|
||||
|
||||
|
||||
class Organization(Base):
|
||||
__tablename__ = "organizations"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -114,6 +120,7 @@ class Device(Base):
|
||||
organization_id: Mapped[int] = mapped_column(ForeignKey("organizations.id"), index=True)
|
||||
mac: Mapped[str] = mapped_column(String(17), default="")
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
status: Mapped[DeviceStatus] = mapped_column(Enum(DeviceStatus, name="device_status"), default=DeviceStatus.active, server_default="active") # изменение 039
|
||||
|
||||
|
||||
class Address(Base):
|
||||
|
||||
+6
-1
@@ -5,7 +5,7 @@ from typing import Annotated, Generic, TypeVar
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, EmailStr, Field, field_validator, model_validator
|
||||
|
||||
from app.models import AddressStatus, PrefixStatus, Role
|
||||
from app.models import AddressStatus, DeviceStatus, PrefixStatus, Role
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
@@ -240,6 +240,7 @@ class DeviceIn(BaseModel):
|
||||
organization_id: int
|
||||
mac: str = ""
|
||||
note: str = ""
|
||||
status: DeviceStatus = DeviceStatus.active # изменение 039
|
||||
|
||||
_name_valid = field_validator("name")(_device_name)
|
||||
_mac_valid = field_validator("mac")(_device_mac)
|
||||
@@ -250,6 +251,7 @@ class DeviceUpdate(BaseModel):
|
||||
device_type_id: int | None = None
|
||||
mac: str | None = None
|
||||
note: str | None = None
|
||||
status: DeviceStatus | None = None # изменение 039
|
||||
|
||||
_blank_text = field_validator("mac", "note")(_blank) # сначала null → "", затем проверка формата
|
||||
_name_valid = field_validator("name")(_device_name)
|
||||
@@ -264,6 +266,7 @@ class DeviceOut(ORM):
|
||||
organization_id: int
|
||||
mac: str
|
||||
note: str
|
||||
status: DeviceStatus = DeviceStatus.active # изменение 039
|
||||
ip_addresses: list[str] = []
|
||||
first_prefix_id: int | None = None
|
||||
all_deprecated: bool = False
|
||||
@@ -388,6 +391,8 @@ class AddressOut(BaseModel):
|
||||
description: str = ""
|
||||
device_id: int | None = None
|
||||
device_name: str | None = None
|
||||
device_type_name: str | None = None # изменение 039
|
||||
device_status: str | None = None # изменение 039
|
||||
note: str = ""
|
||||
updated_at: datetime | None = None
|
||||
|
||||
|
||||
Reference in new issue
Block a user