拆分物品库存与借出登记
This commit is contained in:
+40
-14
@@ -32,7 +32,7 @@ class ItemIn(BaseModel):
|
||||
return value.strip()
|
||||
|
||||
|
||||
class LoanIn(BaseModel):
|
||||
class LoanBaseIn(BaseModel):
|
||||
quantity: int = Field(ge=1, le=100000)
|
||||
reason: str = Field(min_length=1, max_length=500)
|
||||
contact: str = Field(min_length=1, max_length=200)
|
||||
@@ -44,6 +44,16 @@ class LoanIn(BaseModel):
|
||||
return value.strip()
|
||||
|
||||
|
||||
class LoanIn(LoanBaseIn):
|
||||
item_name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator('item_name')
|
||||
@classmethod
|
||||
def clean_item_name(cls, value):
|
||||
if not value.strip(): raise ValueError('借出物品不能为空')
|
||||
return value.strip()
|
||||
|
||||
|
||||
class CheckIn(BaseModel):
|
||||
quantities: dict[str, int]
|
||||
note: str = Field(default='', max_length=1000)
|
||||
@@ -308,24 +318,40 @@ def install(app, get_db, current_user, photo_root, visible_clause):
|
||||
await db.execute(insert(center_items).values(id=key, **payload.model_dump(), created_at=now_ms())); await db.commit()
|
||||
return {'id': key}
|
||||
|
||||
@app.post('/api/center/items/{item_id}/loans')
|
||||
async def borrow(item_id: str, payload: LoanIn, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
await db.execute(text('BEGIN IMMEDIATE'))
|
||||
item=(await db.execute(select(center_items).where(center_items.c.id==item_id))).mappings().first()
|
||||
if not item: raise HTTPException(404,'物品不存在')
|
||||
used=(await db.execute(select(func.coalesce(func.sum(center_loans.c.quantity),0)).where(center_loans.c.item_id==item_id, center_loans.c.status=='approved', center_loans.c.returned_at.is_(None)))).scalar()
|
||||
if payload.quantity > item['quantity']-used: raise HTTPException(409,'可借数量不足,请刷新')
|
||||
@app.post('/api/center/loans')
|
||||
async def record_loan(payload: LoanIn, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
"""仅记录借出,不扣减库存,也不要求物品已加入库存清单。"""
|
||||
key=uuid.uuid4().hex
|
||||
await db.execute(insert(center_loans).values(
|
||||
id=key,item_id=item_id,user_id=viewer['id'],**payload.model_dump(),
|
||||
status='approved',created_at=now_ms()
|
||||
id=key,item_id=None,user_id=viewer['id'],**payload.model_dump(),
|
||||
status='recorded',created_at=now_ms()
|
||||
))
|
||||
await db.commit(); return {'id':key,'status':'approved'}
|
||||
await db.commit(); return {'id':key,'status':'recorded'}
|
||||
|
||||
@app.post('/api/center/items/{item_id}/loans')
|
||||
async def record_linked_loan_compat(item_id: str, payload: LoanBaseIn, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
"""兼容旧调用:仍关联库存名称,但只登记,不再占用库存。"""
|
||||
item=(await db.execute(select(center_items).where(center_items.c.id==item_id))).mappings().first()
|
||||
if not item: raise HTTPException(404,'物品不存在')
|
||||
key=uuid.uuid4().hex
|
||||
await db.execute(insert(center_loans).values(
|
||||
id=key,item_id=item_id,item_name=None,user_id=viewer['id'],**payload.model_dump(),
|
||||
status='recorded',created_at=now_ms()
|
||||
))
|
||||
await db.commit(); return {'id':key,'status':'recorded'}
|
||||
|
||||
@app.get('/api/center/loans')
|
||||
async def loans(status: str='all', db=Depends(get_db), viewer=Depends(current_user)):
|
||||
stmt=select(center_loans,center_items.c.name.label('item_name'),users.c.display_name).select_from(center_loans).join(center_items,center_items.c.id==center_loans.c.item_id).join(users,users.c.id==center_loans.c.user_id)
|
||||
if status=='borrowed':stmt=stmt.where(center_loans.c.status=='approved')
|
||||
stmt=select(
|
||||
center_loans.c.id, center_loans.c.item_id,
|
||||
func.coalesce(center_loans.c.item_name,center_items.c.name).label('item_name'),
|
||||
center_loans.c.user_id, center_loans.c.quantity, center_loans.c.reason,
|
||||
center_loans.c.contact, center_loans.c.created_at, center_loans.c.returned_at,
|
||||
center_loans.c.status, center_loans.c.reviewer_id, center_loans.c.reviewed_at,
|
||||
center_loans.c.review_note, users.c.display_name,
|
||||
).select_from(center_loans).outerjoin(center_items,center_items.c.id==center_loans.c.item_id).join(users,users.c.id==center_loans.c.user_id)
|
||||
if status=='recorded':stmt=stmt.where(center_loans.c.status=='recorded')
|
||||
elif status in ('approved','borrowed'):stmt=stmt.where(center_loans.c.status=='approved')
|
||||
elif status=='returned':stmt=stmt.where(center_loans.c.status==status)
|
||||
elif status!='all':raise HTTPException(422,'无效借用状态')
|
||||
rows=(await db.execute(stmt.order_by(center_loans.c.created_at.desc()).limit(200))).mappings().all()
|
||||
@@ -337,7 +363,7 @@ def install(app, get_db, current_user, photo_root, visible_clause):
|
||||
if not row:raise HTTPException(404,'借用记录不存在')
|
||||
if row['user_id']!=viewer['id']:raise HTTPException(403,'仅借用人可以登记归还')
|
||||
if row['status']=='returned':return {'ok':True}
|
||||
if row['status']!='approved':raise HTTPException(409,'仅已批准的借用可归还')
|
||||
if row['status']!='approved':raise HTTPException(409,'仅历史库存借出记录可归还')
|
||||
await db.execute(update(center_loans).where(center_loans.c.id==loan_id,center_loans.c.returned_at.is_(None)).values(returned_at=now_ms(),status='returned'))
|
||||
await db.commit(); return {'ok':True}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from . import center
|
||||
from .models import activities, users, center_activity_meta, center_items, center_loans, center_checks
|
||||
|
||||
Dataset = Literal['all', 'activities', 'items', 'loans', 'checks']
|
||||
LoanStatus = Literal['all', 'approved', 'borrowed', 'returned']
|
||||
LoanStatus = Literal['all', 'recorded', 'approved', 'borrowed', 'returned']
|
||||
FIELDS = {
|
||||
'activities': ['id','title','start_at','location','description','visibility','organizer_name','photo_ids','photo_urls','material_id','material_url','materials','created_at','updated_at'],
|
||||
'items': ['id','name','quantity','borrowed','available','created_at'],
|
||||
@@ -53,7 +53,7 @@ def install(app, get_db, current_user, visible_clause):
|
||||
@app.get('/api/center/schema')
|
||||
async def schema(viewer=Depends(current_user)):
|
||||
return {
|
||||
'schema_version':1, 'name':'赋能中心一楼(双创一楼)', 'timezone':'Asia/Shanghai',
|
||||
'schema_version':2, 'name':'赋能中心一楼(双创一楼)', 'timezone':'Asia/Shanghai',
|
||||
'authentication':'Authorization: Bearer <当前登录会话令牌>',
|
||||
'read_endpoint':'/api/center/data', 'export_endpoint':'/api/center/export',
|
||||
'datasets':{key:{'label':NAMES[key],'fields':fields} for key,fields in FIELDS.items()},
|
||||
@@ -66,8 +66,8 @@ def install(app, get_db, current_user, visible_clause):
|
||||
'zip_entry_max_mb':center.MAX_ZIP_ENTRY_BYTES // 1024 // 1024,
|
||||
'zip_expanded_max_mb':center.MAX_ZIP_EXPANDED_BYTES // 1024 // 1024,
|
||||
},
|
||||
'filters':{'dataset':['all',*FIELDS], 'q':'活动主题/地点/描述,物品名称,借用物品/理由,清点备注/日期', 'date_from':'YYYY-MM-DD,含当日,北京时间', 'date_to':'YYYY-MM-DD,含当日,北京时间', 'loan_status':['all','approved','borrowed','returned']},
|
||||
'semantics':{'timestamps':'数据行中的 *_at 为 Unix 毫秒时间戳,空值为null;generated_at 为带时区的 ISO 8601 字符串', 'inventory':'quantity=物品总数,borrowed=当前未归还数量,available=quantity-borrowed;登录成员登记借出后立即占用库存', 'date_filter':'活动按开始时间、借用按登记时间、清点按清点日期筛选;库存是当前状态,不受日期筛选影响', 'photos':'materials包含原材料和成员补充材料、上传人及关联时间;照片ID合并全部材料,下载需登录;旧照片记录的material_id可为null', 'privacy':'一楼活动全体登录成员可见,仅作记录,不参与参加和发起统计;借用联系方式、账号邮箱和手机号均不导出', 'checks':'details 中 expected=应在库,actual=实点在库,borrowed=当时已借出'},
|
||||
'filters':{'dataset':['all',*FIELDS], 'q':'活动主题/地点/描述,物品名称,借用物品/理由,清点备注/日期', 'date_from':'YYYY-MM-DD,含当日,北京时间', 'date_to':'YYYY-MM-DD,含当日,北京时间', 'loan_status':['all','recorded','approved','borrowed','returned']},
|
||||
'semantics':{'timestamps':'数据行中的 *_at 为 Unix 毫秒时间戳,空值为null;generated_at 为带时区的 ISO 8601 字符串', 'inventory':'quantity=物品总数,borrowed/available只统计升级前的历史库存借出记录;新的借出登记与物品库存完全独立', 'loans':'status=recorded 表示仅登记借出;item_id 为空时 item_name 为登记人填写的物品名称;新登记不扣减库存,也不要求物品已加入库存清单', 'date_filter':'活动按开始时间、借用按登记时间、清点按清点日期筛选;库存是当前状态,不受日期筛选影响', 'photos':'materials包含原材料和成员补充材料、上传人及关联时间;照片ID合并全部材料,下载需登录;旧照片记录的material_id可为null', 'privacy':'一楼活动全体登录成员可见,仅作记录,不参与参加和发起统计;借用联系方式、账号邮箱和手机号均不导出', 'checks':'details 中 expected=应在库,actual=实点在库;历史 borrowed 为当时占用的库存数量'},
|
||||
'download':{'json':'完整匹配数据,不受分页参数影响;all包含四个数据集','csv':'单一数据集为CSV;all为ZIP,内含四个CSV,UTF-8 BOM;嵌套字段为JSON字符串'},
|
||||
}
|
||||
|
||||
@@ -77,11 +77,11 @@ def install(app, get_db, current_user, visible_clause):
|
||||
queries={
|
||||
'activities':select(activities,center_activity_meta.c.photo_ids,center_activity_meta.c.material_id,users.c.display_name.label('organizer_name')).select_from(activities).join(center_activity_meta,center_activity_meta.c.activity_id==activities.c.id).join(users,users.c.id==activities.c.organizer_id).where(visible_clause(viewer['id'])),
|
||||
'items':select(center_items),
|
||||
'loans':select(center_loans.c.id,center_loans.c.item_id,center_items.c.name.label('item_name'),users.c.display_name.label('borrower_name'),center_loans.c.quantity,center_loans.c.reason,center_loans.c.status,center_loans.c.created_at,center_loans.c.reviewed_at,center_loans.c.review_note,center_loans.c.returned_at).select_from(center_loans).join(center_items,center_items.c.id==center_loans.c.item_id).join(users,users.c.id==center_loans.c.user_id),
|
||||
'loans':select(center_loans.c.id,center_loans.c.item_id,func.coalesce(center_loans.c.item_name,center_items.c.name).label('item_name'),users.c.display_name.label('borrower_name'),center_loans.c.quantity,center_loans.c.reason,center_loans.c.status,center_loans.c.created_at,center_loans.c.reviewed_at,center_loans.c.review_note,center_loans.c.returned_at).select_from(center_loans).outerjoin(center_items,center_items.c.id==center_loans.c.item_id).join(users,users.c.id==center_loans.c.user_id),
|
||||
'checks':select(center_checks.c.day,users.c.display_name.label('checker_name'),center_checks.c.details,center_checks.c.note,center_checks.c.created_at).select_from(center_checks).join(users,users.c.id==center_checks.c.user_id),
|
||||
}
|
||||
dates={'activities':activities.c.start_at,'loans':center_loans.c.created_at}
|
||||
search={'activities':[activities.c.title,activities.c.location,activities.c.description],'items':[center_items.c.name],'loans':[center_items.c.name,center_loans.c.reason],'checks':[center_checks.c.note,center_checks.c.day]}
|
||||
search={'activities':[activities.c.title,activities.c.location,activities.c.description],'items':[center_items.c.name],'loans':[func.coalesce(center_loans.c.item_name,center_items.c.name),center_loans.c.reason],'checks':[center_checks.c.note,center_checks.c.day]}
|
||||
for key in FIELDS if dataset=='all' else [dataset]:
|
||||
stmt=queries[key]
|
||||
if q.strip():stmt=stmt.where(or_(*(col.like('%'+q.strip()+'%') for col in search[key])))
|
||||
@@ -113,7 +113,7 @@ def install(app, get_db, current_user, visible_clause):
|
||||
elif key=='checks':
|
||||
for r in rows:r['details']=json.loads(r['details'])
|
||||
result[key]=rows
|
||||
return {'schema_version':1,'name':'赋能中心一楼(双创一楼)','generated_at':datetime.now(BEIJING).isoformat(),'timezone':'Asia/Shanghai','contacts_included':False,'filters':{'dataset':dataset,'q':q,'date_from':start.isoformat() if start else None,'date_to':end.isoformat() if end else None,'loan_status':loan_status},'data':result,'pagination':{key:{'total':totals[key],'offset':offset if limit is not None else 0,'limit':limit,'next_offset':offset+limit if limit is not None and offset+limit<totals[key] else None} for key in result}}
|
||||
return {'schema_version':2,'name':'赋能中心一楼(双创一楼)','generated_at':datetime.now(BEIJING).isoformat(),'timezone':'Asia/Shanghai','contacts_included':False,'filters':{'dataset':dataset,'q':q,'date_from':start.isoformat() if start else None,'date_to':end.isoformat() if end else None,'loan_status':loan_status},'data':result,'pagination':{key:{'total':totals[key],'offset':offset if limit is not None else 0,'limit':limit,'next_offset':offset+limit if limit is not None and offset+limit<totals[key] else None} for key in result}}
|
||||
|
||||
@app.get('/api/center/data')
|
||||
async def data(dataset:Dataset='all',q:str=Query('',max_length=200),date_from:Optional[date]=None,date_to:Optional[date]=None,loan_status:LoanStatus='all',limit:int=Query(100,ge=1,le=500),offset:int=Query(0,ge=0),db=Depends(get_db),viewer=Depends(current_user)):
|
||||
|
||||
+39
-1
@@ -687,7 +687,8 @@ async def _migrate_legacy(conn) -> None:
|
||||
|
||||
|
||||
async def _migrate_center_loans(conn) -> None:
|
||||
"""把旧待审批借用按提交顺序转为已借出,库存不足的保留为历史未借出。"""
|
||||
"""扩展借出记录以支持与库存无关的登记,并迁移旧待审批记录。"""
|
||||
await _migrate_center_loan_schema(conn)
|
||||
rows = (await conn.execute(
|
||||
select(center_loans)
|
||||
.where(center_loans.c.status == 'pending')
|
||||
@@ -724,6 +725,43 @@ async def _migrate_center_loans(conn) -> None:
|
||||
)
|
||||
|
||||
|
||||
async def _migrate_center_loan_schema(conn) -> None:
|
||||
"""SQLite 中把 item_id 改为可空,并增加独立的物品名称字段。"""
|
||||
def _inspect(sync_conn):
|
||||
columns = {column["name"]: column for column in inspect(sync_conn).get_columns("center_loans")}
|
||||
item_id = columns.get("item_id")
|
||||
if not item_id:
|
||||
return False
|
||||
return "item_name" not in columns or not item_id.get("nullable", False)
|
||||
|
||||
if not await conn.run_sync(_inspect):
|
||||
return
|
||||
|
||||
legacy = "center_loans_legacy_schema"
|
||||
await conn.execute(text(f"ALTER TABLE center_loans RENAME TO {legacy}"))
|
||||
await conn.run_sync(center_loans.create)
|
||||
source_columns = {
|
||||
column["name"]
|
||||
for column in await conn.run_sync(lambda c: inspect(c).get_columns(legacy))
|
||||
}
|
||||
|
||||
def source(name, fallback="NULL"):
|
||||
return name if name in source_columns else fallback
|
||||
|
||||
await conn.execute(text(f"""
|
||||
INSERT INTO center_loans (
|
||||
id, item_id, item_name, user_id, quantity, reason, contact, created_at,
|
||||
returned_at, status, reviewer_id, reviewed_at, review_note
|
||||
)
|
||||
SELECT
|
||||
id, item_id, {source('item_name')}, user_id, quantity, reason, contact, created_at,
|
||||
{source('returned_at')}, {source('status', "'approved'")},
|
||||
{source('reviewer_id')}, {source('reviewed_at')}, {source('review_note', "''")}
|
||||
FROM {legacy}
|
||||
"""))
|
||||
await conn.execute(text(f"DROP TABLE {legacy}"))
|
||||
|
||||
|
||||
app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
|
||||
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
|
||||
center_export.install(app, get_db, current_user, visible_clause)
|
||||
|
||||
+2
-1
@@ -150,7 +150,8 @@ center_items = Table('center_items', metadata,
|
||||
Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True),
|
||||
Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False))
|
||||
center_loans = Table('center_loans', metadata,
|
||||
Column('id', String(32), primary_key=True), Column('item_id', String(32), ForeignKey('center_items.id'), nullable=False),
|
||||
Column('id', String(32), primary_key=True), Column('item_id', String(32), ForeignKey('center_items.id'), nullable=True),
|
||||
Column('item_name', String(100), nullable=True),
|
||||
Column('user_id', String(36), ForeignKey('users.id'), nullable=False), Column('quantity', Integer, nullable=False),
|
||||
Column('reason', String(500), nullable=False), Column('contact', String(200), nullable=False),
|
||||
Column('created_at', Integer, nullable=False), Column('returned_at', Integer, nullable=True),
|
||||
|
||||
Reference in New Issue
Block a user