cdbe59e97f
- visits: search沟通内容/客户需求/拜访人/客户名 - daily_notes: search内容 - work_plans: search计划内容/客户名 - mini_business: search产品/跟进/客户名 - key_visits: search描述/拜访人/客户名 Co-Authored-By: Claude <noreply@anthropic.com>
142 lines
5.9 KiB
Python
142 lines
5.9 KiB
Python
import uuid
|
|
from typing import Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select, or_
|
|
from app.database import get_db
|
|
from app.middleware.auth import get_current_user, require_any_role
|
|
from app.models.mini_business import MiniBusiness
|
|
from app.models.customer import Customer
|
|
from app.models.user import User
|
|
from app.schemas.mini_business import MiniBusinessCreate, MiniBusinessUpdate, MiniBusinessOut
|
|
from app.utils.edit_log import compute_diff, append_entry, init_entry
|
|
|
|
router = APIRouter(prefix="/mini-business", tags=["MiniBusiness"])
|
|
|
|
|
|
async def _enrich(m: MiniBusiness, db: AsyncSession) -> dict:
|
|
cust = await db.execute(select(Customer.name).where(Customer.id == m.customer_id))
|
|
mgr = await db.execute(select(User.name).where(User.id == m.manager_id))
|
|
return {
|
|
"id": str(m.id),
|
|
"customer_id": str(m.customer_id),
|
|
"customer_name": cust.scalar_one_or_none(),
|
|
"product_type": m.product_type,
|
|
"amount": m.amount,
|
|
"follow_up_detail": m.follow_up_detail,
|
|
"status": m.status,
|
|
"manager_id": str(m.manager_id),
|
|
"manager_name": mgr.scalar_one_or_none(),
|
|
"edit_log": m.edit_log or [],
|
|
"expected_revenue_date": m.expected_revenue_date,
|
|
}
|
|
|
|
|
|
@router.get("/")
|
|
async def list_mini_business(
|
|
customer_id: Optional[str] = Query(None),
|
|
customer_type: Optional[str] = Query(None),
|
|
search: Optional[str] = Query(None),
|
|
current_user: dict = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
query = select(MiniBusiness)
|
|
if current_user["role"] == "manager":
|
|
query = query.where(MiniBusiness.manager_id == uuid.UUID(current_user["user_id"]))
|
|
if customer_id:
|
|
query = query.where(MiniBusiness.customer_id == uuid.UUID(customer_id))
|
|
if customer_type:
|
|
query = query.join(Customer, MiniBusiness.customer_id == Customer.id).where(Customer.customer_type == customer_type)
|
|
if search:
|
|
query = query.outerjoin(Customer, MiniBusiness.customer_id == Customer.id).where(
|
|
or_(MiniBusiness.product_type.ilike(f"%{search}%"), MiniBusiness.follow_up_detail.ilike(f"%{search}%"), Customer.name.ilike(f"%{search}%"))
|
|
)
|
|
query = query.order_by(MiniBusiness.expected_revenue_date.desc()).limit(200)
|
|
result = await db.execute(query)
|
|
return [await _enrich(m, db) for m in result.scalars().all()]
|
|
|
|
|
|
@router.get("/{item_id}")
|
|
async def get_mini_business(
|
|
item_id: str,
|
|
current_user: dict = Depends(get_current_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(select(MiniBusiness).where(MiniBusiness.id == item_id))
|
|
m = result.scalar_one_or_none()
|
|
if not m:
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
if current_user["role"] == "manager" and str(m.manager_id) != current_user["user_id"]:
|
|
raise HTTPException(status_code=403, detail="Access denied")
|
|
return await _enrich(m, db)
|
|
|
|
|
|
@router.post("/")
|
|
async def create_mini_business(
|
|
data: MiniBusinessCreate,
|
|
current_user: dict = Depends(require_any_role),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
m = MiniBusiness(
|
|
customer_id=data.customer_id,
|
|
product_type=data.product_type,
|
|
amount=data.amount,
|
|
follow_up_detail=data.follow_up_detail,
|
|
status=data.status,
|
|
manager_id=data.manager_id if (current_user["role"] in ("director", "leader") and data.manager_id) else uuid.UUID(current_user["user_id"]),
|
|
expected_revenue_date=data.expected_revenue_date,
|
|
)
|
|
init_entry(m, current_user["name"])
|
|
db.add(m)
|
|
await db.commit()
|
|
await db.refresh(m)
|
|
return await _enrich(m, db)
|
|
|
|
|
|
@router.put("/{item_id}")
|
|
async def update_mini_business(
|
|
item_id: str, data: MiniBusinessUpdate,
|
|
current_user: dict = Depends(require_any_role),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(select(MiniBusiness).where(MiniBusiness.id == item_id))
|
|
m = result.scalar_one_or_none()
|
|
if not m:
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
if current_user["role"] == "manager" and str(m.manager_id) != current_user["user_id"]:
|
|
raise HTTPException(status_code=403, detail="Access denied")
|
|
|
|
old_snapshot = {"customer_id": str(m.customer_id), "product_type": m.product_type, "amount": m.amount, "follow_up_detail": m.follow_up_detail, "status": m.status, "expected_revenue_date": m.expected_revenue_date}
|
|
update_data = data.model_dump(exclude_unset=True)
|
|
if current_user["role"] not in ("director", "leader"):
|
|
update_data.pop("manager_id", None)
|
|
for k, v in update_data.items():
|
|
setattr(m, k, v)
|
|
# Auto-clear expected revenue date when status becomes 已流失
|
|
if m.status == "已流失" and m.expected_revenue_date:
|
|
m.expected_revenue_date = ""
|
|
new_snapshot = {"customer_id": str(m.customer_id), "product_type": m.product_type, "amount": m.amount, "follow_up_detail": m.follow_up_detail, "status": m.status, "expected_revenue_date": m.expected_revenue_date}
|
|
changes = compute_diff(old_snapshot, new_snapshot)
|
|
if changes:
|
|
append_entry(m, current_user["name"], changes, getattr(data, "edit_reason", None))
|
|
await db.commit()
|
|
await db.refresh(m)
|
|
return await _enrich(m, db)
|
|
|
|
|
|
@router.delete("/{item_id}")
|
|
async def delete_mini_business(
|
|
item_id: str,
|
|
current_user: dict = Depends(require_any_role),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(select(MiniBusiness).where(MiniBusiness.id == item_id))
|
|
m = result.scalar_one_or_none()
|
|
if not m:
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
if current_user["role"] == "manager" and str(m.manager_id) != current_user["user_id"]:
|
|
raise HTTPException(status_code=403, detail="Access denied")
|
|
await db.delete(m)
|
|
await db.commit()
|
|
return {"detail": "deleted"}
|