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

327 lines
10 KiB
Python

"""CRM 商机产品关联 CRUD"""
from __future__ import annotations
import math
from datetime import datetime
from decimal import Decimal
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.opportunity import _ensure_opportunity_in_scope
from app.models.crm_models import CrmOpportunity, CrmOpportunityProduct, CrmProduct
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 _decimal_value(value: Any, default: Decimal = Decimal("0")) -> Decimal:
if value is None or value == "":
return default
return Decimal(str(value))
def _calc_subtotal(quantity: Decimal, price: Decimal, discount: Decimal) -> Decimal:
qty = quantity or Decimal("0")
pr = price or Decimal("0")
disc = discount or Decimal("0")
if disc <= 1:
multiplier = Decimal("1") - disc
else:
multiplier = (Decimal("100") - disc) / Decimal("100")
return (qty * pr * multiplier).quantize(Decimal("0.01"))
def _row_to_dict(row: CrmOpportunityProduct) -> Dict[str, Any]:
return {
"id": row.id,
"opportunityId": row.opportunity_id or "",
"productId": row.product_id or "",
"productName": row.product_name or "",
"productCode": row.product_no or "",
"productNo": row.product_no or "",
"categoryId": row.category_id or "",
"categoryName": row.category_name or "",
"model": row.model or "",
"unit": row.unit or "",
"quantity": float(row.quantity) if row.quantity is not None else 0,
"price": float(row.price) if row.price is not None else 0,
"discount": float(row.discount) if row.discount is not None else 0,
"subtotal": float(row.subtotal) if row.subtotal is not None else 0,
"sortOrder": row.sort if row.sort is not None else 0,
"sort": row.sort if row.sort is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime(_FMT) if row.create_time else "",
}
def _recalc_product_count(db: Session, opportunity_id: str) -> None:
opp = (
db.query(CrmOpportunity)
.filter(CrmOpportunity.id == opportunity_id, CrmOpportunity.del_flag == 0)
.first()
)
if not opp:
return
count = (
db.query(CrmOpportunityProduct)
.filter(
CrmOpportunityProduct.opportunity_id == opportunity_id,
CrmOpportunityProduct.del_flag == 0,
)
.count()
)
opp.product_count = count
opp.update_time = datetime.now()
def _fill_product_redundant(db: Session, entity: CrmOpportunityProduct, product_id: str) -> None:
product = (
db.query(CrmProduct)
.filter(CrmProduct.id == product_id, CrmProduct.del_flag == 0)
.first()
)
if product:
entity.product_name = entity.product_name or product.product_name
entity.product_no = entity.product_no or product.product_no
entity.category_id = entity.category_id or product.category_id
entity.category_name = entity.category_name or product.category_name
entity.model = entity.model or product.model
entity.unit = entity.unit or product.unit
def _get_opportunity_for_product(
db: Session, opportunity_id: str, tenant_no: str, user_info=None
) -> 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_products(
db: Session,
*,
opportunity_id: str = None,
product_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:
_get_opportunity_for_product(db, opportunity_id, tenant_no, user_info)
q = db.query(CrmOpportunityProduct).filter(CrmOpportunityProduct.del_flag == 0)
if tenant_no:
q = q.filter(CrmOpportunityProduct.tenant_no == tenant_no)
if opportunity_id:
q = q.filter(CrmOpportunityProduct.opportunity_id == opportunity_id)
if product_id:
q = q.filter(CrmOpportunityProduct.product_id == product_id)
total = q.count()
rows = (
q.order_by(CrmOpportunityProduct.sort.asc(), CrmOpportunityProduct.create_time.asc())
.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_products_by_opportunity(
db: Session,
opportunity_id: str,
tenant_no: str = None,
user_info=None,
) -> List[Dict[str, Any]]:
rows, _ = list_opportunity_products(
db,
opportunity_id=opportunity_id,
page=1,
page_size=10000,
tenant_no=tenant_no,
user_info=user_info,
)
return rows
def get_opportunity_product(
db: Session,
product_row_id: str,
tenant_no: str = None,
user_info=None,
) -> Optional[Dict[str, Any]]:
q = db.query(CrmOpportunityProduct).filter(
CrmOpportunityProduct.id == product_row_id,
CrmOpportunityProduct.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityProduct.tenant_no == tenant_no)
row = q.first()
if not row:
return None
if tenant_no:
_get_opportunity_for_product(db, row.opportunity_id, tenant_no, user_info)
return _row_to_dict(row)
def create_opportunity_product(
db: Session,
tenant_no: str,
data: dict,
user_id: str = None,
user_info=None,
) -> Dict[str, Any]:
opp_id = data.get("opportunity_id")
_get_opportunity_for_product(db, opp_id, tenant_no, user_info)
qty = _decimal_value(data.get("quantity"))
price = _decimal_value(data.get("price"))
discount = _decimal_value(data.get("discount"), Decimal("0"))
subtotal = data.get("subtotal")
if subtotal is not None:
sub = _decimal_value(subtotal)
else:
sub = _calc_subtotal(qty, price, discount)
now = datetime.now()
row = CrmOpportunityProduct(
id=generate_uuid(),
opportunity_id=opp_id,
product_id=data["product_id"],
product_name=data.get("product_name") or data.get("productName"),
product_no=data.get("product_no") or data.get("productCode"),
category_id=data.get("category_id"),
category_name=data.get("category_name"),
model=data.get("model"),
unit=data.get("unit") or "件",
quantity=qty,
price=price,
discount=discount,
subtotal=sub,
sort=data.get("sort") or data.get("sort_order") or 0,
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=now,
update_by=user_id,
update_time=now,
del_flag=0,
)
_fill_product_redundant(db, row, data["product_id"])
db.add(row)
_recalc_product_count(db, opp_id)
db.commit()
db.refresh(row)
return _row_to_dict(row)
def batch_add_opportunity_products(
db: Session,
tenant_no: str,
opportunity_id: str,
product_list: List[dict],
user_id: str = None,
user_info=None,
) -> int:
if not product_list:
raise ValueError("产品列表不能为空")
_get_opportunity_for_product(db, opportunity_id, tenant_no, user_info)
count = 0
for item in product_list:
item = dict(item)
item["opportunity_id"] = opportunity_id
create_opportunity_product(db, tenant_no, item, user_id, user_info=user_info)
count += 1
return count
def update_opportunity_product(
db: Session,
product_row_id: str,
data: dict,
user_id: str = None,
tenant_no: str = None,
user_info=None,
) -> Dict[str, Any]:
q = db.query(CrmOpportunityProduct).filter(
CrmOpportunityProduct.id == product_row_id,
CrmOpportunityProduct.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityProduct.tenant_no == tenant_no)
row = q.first()
if not row:
raise ValueError("商机产品不存在")
if tenant_no:
_get_opportunity_for_product(db, row.opportunity_id, tenant_no, user_info)
if data.get("quantity") is not None:
row.quantity = _decimal_value(data["quantity"])
if data.get("price") is not None:
row.price = _decimal_value(data["price"])
if data.get("discount") is not None:
row.discount = _decimal_value(data["discount"])
if data.get("product_name") is not None:
row.product_name = data["product_name"]
if data.get("remark") is not None:
row.remark = data["remark"]
if data.get("sort") is not None or data.get("sort_order") is not None:
row.sort = data.get("sort") or data.get("sort_order")
row.subtotal = _calc_subtotal(row.quantity, row.price, row.discount)
row.update_by = user_id
row.update_time = datetime.now()
db.commit()
db.refresh(row)
return _row_to_dict(row)
def soft_delete_opportunity_products(
db: Session,
ids: List[str],
user_id: str = None,
tenant_no: str = None,
user_info=None,
) -> int:
q = db.query(CrmOpportunityProduct).filter(
CrmOpportunityProduct.id.in_(ids),
CrmOpportunityProduct.del_flag == 0,
)
if tenant_no:
q = q.filter(CrmOpportunityProduct.tenant_no == tenant_no)
rows = q.all()
if not rows:
return 0
opp_id = rows[0].opportunity_id
if tenant_no:
_get_opportunity_for_product(db, opp_id, tenant_no, user_info)
now = datetime.now()
for row in rows:
assert_row_deletable_by_creator(row, user_info, user_id=user_id)
row.del_flag = 1
row.update_by = user_id
row.update_time = now
_recalc_product_count(db, opp_id)
db.commit()
return len(rows)