Files
shanxia2.0/backend/app/crud/crm/opportunity_follow.py
T
2026-08-21 16:50:47 +08:00

313 lines
9.8 KiB
Python

"""CRM 商机跟进记录 CRUD"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy.orm import Session
from app.core.delete_guard import assert_row_deletable_by_creator
from app.core.utils import generate_uuid
from app.crud.crm.data_scope_helpers import apply_crm_create_by_scope, ensure_crm_create_by_row_in_scope
from app.crud.crm.opportunity import _ensure_opportunity_in_scope
from app.models.crm_models import CrmOpportunity, CrmOpportunityFollow
def total_pages(total: int, page_size: int) -> int:
if page_size <= 0:
return 0
return math.ceil(total / page_size)
_FMT = "%Y-%m-%d %H:%M:%S"
def _parse_optional_datetime(value: Any) -> Optional[datetime]:
if value is None:
return None
if isinstance(value, datetime):
return value
text = str(value).strip()
if not text:
return None
for fmt in (_FMT, "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
raise ValueError(f"日期时间格式无效: {text}")
def _row_to_dict(row: CrmOpportunityFollow) -> Dict[str, Any]:
follow_time = row.follow_time or row.create_time
next_plan = row.next_content or ""
return {
"id": row.id,
"opportunityId": row.opportunity_id or "",
"followType": row.follow_type or "",
"followContent": row.follow_content or "",
"followTime": follow_time.strftime(_FMT) if follow_time else "",
"createTime": row.create_time.strftime(_FMT) if row.create_time else "",
"stage": row.stage or "",
"stagePercent": row.stage_percent if row.stage_percent is not None else 0,
"nextTime": row.next_time.strftime(_FMT) if row.next_time else "",
"nextPlan": next_plan,
"nextContent": next_plan,
"attachments": row.attachments or "",
"contactId": row.contact_id or "",
"contactName": row.contact_name or "",
"location": row.location or "",
"duration": row.duration,
"followBy": row.follow_by or row.create_by or "",
"createBy": row.create_by or "",
"remark": row.remark or "",
"orderNum": row.order_num if row.order_num is not None else 0,
"updateBy": row.update_by or "",
"updateTime": row.update_time.strftime(_FMT) if row.update_time else "",
}
def _recalc_opportunity_follow_stats(db: Session, opportunity_id: str) -> None:
opp = (
db.query(CrmOpportunity)
.filter(CrmOpportunity.id == opportunity_id, CrmOpportunity.del_flag == 0)
.first()
)
if not opp:
return
# 统计前 flush,确保当前事务内新增/软删的跟进记录已写入,避免 follow_count 少 1
db.flush()
remaining = (
db.query(CrmOpportunityFollow)
.filter(
CrmOpportunityFollow.opportunity_id == opportunity_id,
CrmOpportunityFollow.del_flag == 0,
)
.count()
)
opp.follow_count = remaining
latest = (
db.query(CrmOpportunityFollow)
.filter(
CrmOpportunityFollow.opportunity_id == opportunity_id,
CrmOpportunityFollow.del_flag == 0,
)
.order_by(
CrmOpportunityFollow.follow_time.desc(),
CrmOpportunityFollow.create_time.desc(),
)
.first()
)
if latest:
opp.last_time = latest.follow_time or latest.create_time
if latest.next_time:
opp.next_time = latest.next_time
else:
opp.last_time = None
opp.update_time = datetime.now()
def _ensure_parent_opportunity(
db: Session, opportunity_id: str, tenant_no: str, user_info
) -> CrmOpportunity:
opp = (
db.query(CrmOpportunity)
.filter(
CrmOpportunity.id == opportunity_id,
CrmOpportunity.tenant_no == tenant_no,
CrmOpportunity.del_flag == 0,
)
.first()
)
if not opp:
raise ValueError("商机不存在")
_ensure_opportunity_in_scope(db, opp, user_info, tenant_no)
return opp
def list_opportunity_follows(
db: Session,
*,
opportunity_id: str = None,
page: int = 1,
page_size: int = 10,
tenant_no: str = None,
user_info=None,
) -> Tuple[List[Dict[str, Any]], int]:
if opportunity_id and tenant_no:
_ensure_parent_opportunity(db, opportunity_id, tenant_no, user_info)
q = db.query(CrmOpportunityFollow).filter(CrmOpportunityFollow.del_flag == 0)
if tenant_no:
q = q.filter(CrmOpportunityFollow.tenant_no == tenant_no)
if opportunity_id:
q = q.filter(CrmOpportunityFollow.opportunity_id == opportunity_id)
if user_info and tenant_no:
q = apply_crm_create_by_scope(q, CrmOpportunityFollow, user_info, db, tenant_no)
total = q.count()
rows = (
q.order_by(CrmOpportunityFollow.create_time.desc())
.offset((max(1, page) - 1) * page_size)
.limit(min(max(1, page_size), 500))
.all()
)
return [_row_to_dict(r) for r in rows], total
def list_follows_by_opportunity(
db: Session,
opportunity_id: str,
tenant_no: str = None,
user_info=None,
) -> List[Dict[str, Any]]:
rows, _ = list_opportunity_follows(
db,
opportunity_id=opportunity_id,
page=1,
page_size=10000,
tenant_no=tenant_no,
user_info=user_info,
)
return rows
def get_opportunity_follow(
db: Session,
follow_id: str,
tenant_no: str = None,
user_info=None,
) -> Optional[Dict[str, Any]]:
q = db.query(CrmOpportunityFollow).filter(
CrmOpportunityFollow.id == follow_id,
CrmOpportunityFollow.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityFollow.tenant_no == tenant_no)
row = q.first()
if not row:
return None
ensure_crm_create_by_row_in_scope(
db, row, user_info, row.tenant_no, message="无权访问该跟进记录"
)
return _row_to_dict(row)
def create_opportunity_follow(
db: Session,
tenant_no: str,
data: dict,
user_id: str = None,
user_info=None,
) -> Dict[str, Any]:
opp = _ensure_parent_opportunity(db, data.get("opportunity_id"), tenant_no, user_info)
if opp.status in ("won", "lost"):
raise ValueError("已赢单或已输单的商机不允许添加跟进")
now = datetime.now()
follow_time = _parse_optional_datetime(data.get("follow_time")) or now
row = CrmOpportunityFollow(
id=generate_uuid(),
opportunity_id=data["opportunity_id"],
follow_type=data["follow_type"],
follow_content=data["follow_content"],
follow_time=follow_time,
stage=data.get("stage") or opp.stage,
stage_percent=data.get("stage_percent") or opp.stage_percent,
next_time=_parse_optional_datetime(data.get("next_time")),
next_content=data.get("next_content") or data.get("next_plan") or "",
attachments=data.get("attachments") or "",
contact_id=data.get("contact_id"),
contact_name=data.get("contact_name"),
location=data.get("location"),
duration=data.get("duration"),
follow_by=user_id,
tenant_no=tenant_no,
order_num=data.get("order_num") or 0,
remark=data.get("remark") or "",
create_by=user_id,
create_dept_id="",
create_time=follow_time,
update_by=user_id,
update_time=now,
del_flag=0,
)
db.add(row)
_recalc_opportunity_follow_stats(db, opp.id)
db.commit()
db.refresh(row)
return _row_to_dict(row)
def update_opportunity_follow(
db: Session,
follow_id: str,
data: dict,
user_id: str = None,
tenant_no: str = None,
user_info=None,
) -> Dict[str, Any]:
q = db.query(CrmOpportunityFollow).filter(
CrmOpportunityFollow.id == follow_id,
CrmOpportunityFollow.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityFollow.tenant_no == tenant_no)
row = q.first()
if not row:
raise ValueError("跟进记录不存在")
ensure_crm_create_by_row_in_scope(
db, row, user_info, row.tenant_no, message="无权访问该跟进记录"
)
if data.get("follow_type") is not None:
row.follow_type = data["follow_type"]
if data.get("follow_content") is not None:
row.follow_content = data["follow_content"]
if data.get("attachments") is not None:
row.attachments = data["attachments"]
if data.get("remark") is not None:
row.remark = data["remark"]
if data.get("next_content") is not None or data.get("next_plan") is not None:
row.next_content = data.get("next_content") or data.get("next_plan") or ""
if data.get("next_time") is not None:
row.next_time = _parse_optional_datetime(data["next_time"])
if data.get("follow_time") is not None:
row.follow_time = _parse_optional_datetime(data["follow_time"])
row.update_by = user_id
row.update_time = datetime.now()
_recalc_opportunity_follow_stats(db, row.opportunity_id)
db.commit()
db.refresh(row)
return _row_to_dict(row)
def soft_delete_opportunity_follow(
db: Session,
follow_id: str,
user_id: str = None,
tenant_no: str = None,
user_info=None,
) -> bool:
q = db.query(CrmOpportunityFollow).filter(
CrmOpportunityFollow.id == follow_id,
CrmOpportunityFollow.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityFollow.tenant_no == tenant_no)
row = q.first()
if not row:
return False
ensure_crm_create_by_row_in_scope(
db, row, user_info, row.tenant_no, message="无权访问该跟进记录"
)
assert_row_deletable_by_creator(row, user_info, user_id=user_id)
row.del_flag = 1
row.update_by = user_id
row.update_time = datetime.now()
_recalc_opportunity_follow_stats(db, row.opportunity_id)
db.commit()
return True