Initial commit: migrate badge-admin from /tmp to /home/gpsystem

via HAPI (https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>
This commit is contained in:
2026-03-17 01:14:40 +00:00
commit 8a18a5ff16
61 changed files with 13106 additions and 0 deletions

0
app/services/__init__.py Normal file
View File

Binary file not shown.

View File

@@ -0,0 +1,94 @@
"""
Beacon Service - 蓝牙信标管理服务
Provides CRUD operations for Bluetooth beacon configuration.
"""
from datetime import datetime, timezone
from sqlalchemy import func, select, or_
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import BeaconConfig
from app.schemas import BeaconConfigCreate, BeaconConfigUpdate
async def get_beacons(
db: AsyncSession,
page: int = 1,
page_size: int = 20,
status_filter: str | None = None,
search: str | None = None,
) -> tuple[list[BeaconConfig], int]:
"""Get paginated beacon list with optional filters."""
query = select(BeaconConfig)
count_query = select(func.count(BeaconConfig.id))
if status_filter:
query = query.where(BeaconConfig.status == status_filter)
count_query = count_query.where(BeaconConfig.status == status_filter)
if search:
like = f"%{search}%"
cond = or_(
BeaconConfig.beacon_mac.ilike(like),
BeaconConfig.name.ilike(like),
BeaconConfig.area.ilike(like),
)
query = query.where(cond)
count_query = count_query.where(cond)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
offset = (page - 1) * page_size
query = query.order_by(BeaconConfig.created_at.desc()).offset(offset).limit(page_size)
result = await db.execute(query)
return list(result.scalars().all()), total
async def get_beacon(db: AsyncSession, beacon_id: int) -> BeaconConfig | None:
result = await db.execute(
select(BeaconConfig).where(BeaconConfig.id == beacon_id)
)
return result.scalar_one_or_none()
async def get_beacon_by_mac(db: AsyncSession, mac: str) -> BeaconConfig | None:
result = await db.execute(
select(BeaconConfig).where(BeaconConfig.beacon_mac == mac)
)
return result.scalar_one_or_none()
async def create_beacon(db: AsyncSession, data: BeaconConfigCreate) -> BeaconConfig:
beacon = BeaconConfig(**data.model_dump())
db.add(beacon)
await db.flush()
await db.refresh(beacon)
return beacon
async def update_beacon(
db: AsyncSession, beacon_id: int, data: BeaconConfigUpdate
) -> BeaconConfig | None:
beacon = await get_beacon(db, beacon_id)
if beacon is None:
return None
update_data = data.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(beacon, key, value)
beacon.updated_at = datetime.now(timezone.utc)
await db.flush()
await db.refresh(beacon)
return beacon
async def delete_beacon(db: AsyncSession, beacon_id: int) -> bool:
beacon = await get_beacon(db, beacon_id)
if beacon is None:
return False
await db.delete(beacon)
await db.flush()
return True

View File

@@ -0,0 +1,123 @@
"""
Command Service - 指令管理服务
Provides CRUD operations for device command logs.
"""
from datetime import datetime, timezone
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import CommandLog
async def get_commands(
db: AsyncSession,
device_id: int | None = None,
status: str | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[CommandLog], int]:
"""
获取指令列表(分页)/ Get paginated command logs.
Parameters
----------
db : AsyncSession
Database session.
device_id : int, optional
Filter by device ID.
status : str, optional
Filter by command status (pending, sent, success, failed).
page : int
Page number (1-indexed).
page_size : int
Number of items per page.
Returns
-------
tuple[list[CommandLog], int]
(list of command logs, total count)
"""
query = select(CommandLog)
count_query = select(func.count(CommandLog.id))
if device_id is not None:
query = query.where(CommandLog.device_id == device_id)
count_query = count_query.where(CommandLog.device_id == device_id)
if status:
query = query.where(CommandLog.status == status)
count_query = count_query.where(CommandLog.status == status)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
offset = (page - 1) * page_size
query = query.order_by(CommandLog.created_at.desc()).offset(offset).limit(page_size)
result = await db.execute(query)
commands = list(result.scalars().all())
return commands, total
async def create_command(
db: AsyncSession,
device_id: int,
command_type: str,
command_content: str,
server_flag: str = "badge_admin",
) -> CommandLog:
"""
创建指令记录 / Create a new command log entry.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Target device ID.
command_type : str
Type of command.
command_content : str
Command payload content.
server_flag : str
Server flag identifier.
Returns
-------
CommandLog
The newly created command log.
"""
command = CommandLog(
device_id=device_id,
command_type=command_type,
command_content=command_content,
server_flag=server_flag,
status="pending",
)
db.add(command)
await db.flush()
await db.refresh(command)
return command
async def get_command(db: AsyncSession, command_id: int) -> CommandLog | None:
"""
按ID获取指令 / Get command log by ID.
Parameters
----------
db : AsyncSession
Database session.
command_id : int
Command log primary key.
Returns
-------
CommandLog | None
"""
result = await db.execute(
select(CommandLog).where(CommandLog.id == command_id)
)
return result.scalar_one_or_none()

View File

@@ -0,0 +1,215 @@
"""
Device Service - 设备管理服务
Provides CRUD operations and statistics for badge devices.
"""
from datetime import datetime, timezone
from sqlalchemy import func, select, or_
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Device
from app.schemas import DeviceCreate, DeviceUpdate
async def get_devices(
db: AsyncSession,
page: int = 1,
page_size: int = 20,
status_filter: str | None = None,
search: str | None = None,
) -> tuple[list[Device], int]:
"""
获取设备列表(分页)/ Get paginated device list.
Parameters
----------
db : AsyncSession
Database session.
page : int
Page number (1-indexed).
page_size : int
Number of items per page.
status_filter : str, optional
Filter by device status (online / offline).
search : str, optional
Search by IMEI or device name.
Returns
-------
tuple[list[Device], int]
(list of devices, total count)
"""
query = select(Device)
count_query = select(func.count(Device.id))
if status_filter:
query = query.where(Device.status == status_filter)
count_query = count_query.where(Device.status == status_filter)
if search:
pattern = f"%{search}%"
search_clause = or_(
Device.imei.ilike(pattern),
Device.name.ilike(pattern),
)
query = query.where(search_clause)
count_query = count_query.where(search_clause)
# Total count
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
# Paginated results
offset = (page - 1) * page_size
query = query.order_by(Device.updated_at.desc()).offset(offset).limit(page_size)
result = await db.execute(query)
devices = list(result.scalars().all())
return devices, total
async def get_device(db: AsyncSession, device_id: int) -> Device | None:
"""
按ID获取设备 / Get device by ID.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Device primary key.
Returns
-------
Device | None
"""
result = await db.execute(select(Device).where(Device.id == device_id))
return result.scalar_one_or_none()
async def get_device_by_imei(db: AsyncSession, imei: str) -> Device | None:
"""
按IMEI获取设备 / Get device by IMEI number.
Parameters
----------
db : AsyncSession
Database session.
imei : str
Device IMEI number.
Returns
-------
Device | None
"""
result = await db.execute(select(Device).where(Device.imei == imei))
return result.scalar_one_or_none()
async def create_device(db: AsyncSession, device_data: DeviceCreate) -> Device:
"""
创建设备 / Create a new device.
Parameters
----------
db : AsyncSession
Database session.
device_data : DeviceCreate
Device creation data.
Returns
-------
Device
The newly created device.
"""
device = Device(**device_data.model_dump())
db.add(device)
await db.flush()
await db.refresh(device)
return device
async def update_device(
db: AsyncSession, device_id: int, device_data: DeviceUpdate
) -> Device | None:
"""
更新设备信息 / Update device information.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Device primary key.
device_data : DeviceUpdate
Fields to update (only non-None fields are applied).
Returns
-------
Device | None
The updated device, or None if not found.
"""
device = await get_device(db, device_id)
if device is None:
return None
update_fields = device_data.model_dump(exclude_unset=True)
for field, value in update_fields.items():
setattr(device, field, value)
device.updated_at = datetime.now(timezone.utc)
await db.flush()
await db.refresh(device)
return device
async def delete_device(db: AsyncSession, device_id: int) -> bool:
"""
删除设备 / Delete a device.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Device primary key.
Returns
-------
bool
True if the device was deleted, False if not found.
"""
device = await get_device(db, device_id)
if device is None:
return False
await db.delete(device)
await db.flush()
return True
async def get_device_stats(db: AsyncSession) -> dict:
"""
获取设备统计信息 / Get device statistics.
Returns
-------
dict
{"total": int, "online": int, "offline": int}
"""
total_result = await db.execute(select(func.count(Device.id)))
total = total_result.scalar() or 0
online_result = await db.execute(
select(func.count(Device.id)).where(Device.status == "online")
)
online = online_result.scalar() or 0
offline = total - online
return {
"total": total,
"online": online,
"offline": offline,
}

View File

@@ -0,0 +1,138 @@
"""
Location Service - 位置数据服务
Provides query operations for GPS / LBS / WIFI location records.
"""
from datetime import datetime
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import LocationRecord
async def get_locations(
db: AsyncSession,
device_id: int | None = None,
location_type: str | None = None,
start_time: datetime | None = None,
end_time: datetime | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[LocationRecord], int]:
"""
获取位置记录列表(分页)/ Get paginated location records.
Parameters
----------
db : AsyncSession
Database session.
device_id : int, optional
Filter by device ID.
location_type : str, optional
Filter by location type (gps, lbs, wifi, gps_4g, lbs_4g, wifi_4g).
start_time : datetime, optional
Filter records after this time.
end_time : datetime, optional
Filter records before this time.
page : int
Page number (1-indexed).
page_size : int
Number of items per page.
Returns
-------
tuple[list[LocationRecord], int]
(list of location records, total count)
"""
query = select(LocationRecord)
count_query = select(func.count(LocationRecord.id))
if device_id is not None:
query = query.where(LocationRecord.device_id == device_id)
count_query = count_query.where(LocationRecord.device_id == device_id)
if location_type:
query = query.where(LocationRecord.location_type == location_type)
count_query = count_query.where(LocationRecord.location_type == location_type)
if start_time:
query = query.where(LocationRecord.recorded_at >= start_time)
count_query = count_query.where(LocationRecord.recorded_at >= start_time)
if end_time:
query = query.where(LocationRecord.recorded_at <= end_time)
count_query = count_query.where(LocationRecord.recorded_at <= end_time)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
offset = (page - 1) * page_size
query = query.order_by(LocationRecord.recorded_at.desc()).offset(offset).limit(page_size)
result = await db.execute(query)
records = list(result.scalars().all())
return records, total
async def get_latest_location(
db: AsyncSession, device_id: int
) -> LocationRecord | None:
"""
获取设备最新位置 / Get the most recent location for a device.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Device ID.
Returns
-------
LocationRecord | None
"""
result = await db.execute(
select(LocationRecord)
.where(LocationRecord.device_id == device_id)
.order_by(LocationRecord.recorded_at.desc())
.limit(1)
)
return result.scalar_one_or_none()
async def get_device_track(
db: AsyncSession,
device_id: int,
start_time: datetime,
end_time: datetime,
) -> list[LocationRecord]:
"""
获取设备轨迹 / Get device movement track within a time range.
Parameters
----------
db : AsyncSession
Database session.
device_id : int
Device ID.
start_time : datetime
Start of time range.
end_time : datetime
End of time range.
Returns
-------
list[LocationRecord]
Location records ordered by recorded_at ascending (chronological).
"""
result = await db.execute(
select(LocationRecord)
.where(
LocationRecord.device_id == device_id,
LocationRecord.recorded_at >= start_time,
LocationRecord.recorded_at <= end_time,
)
.order_by(LocationRecord.recorded_at.asc())
)
return list(result.scalars().all())