378 lines
13 KiB
Python
378 lines
13 KiB
Python
"""CRM 调价函档案 CRUD"""
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
import re
|
|
from datetime import date, datetime
|
|
from decimal import Decimal
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
from sqlalchemy import func, or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.utils import generate_uuid
|
|
from app.crud.crm.customer import get_customer
|
|
from app.crud.crm.data_scope_helpers import (
|
|
apply_crm_create_by_scope,
|
|
ensure_crm_create_by_row_in_scope,
|
|
)
|
|
from app.crud.crm.product import get_product
|
|
from app.models.crm_models import CrmPriceLetter
|
|
|
|
LETTER_TYPE_RECEIVE = "receive"
|
|
LETTER_TYPE_SEND = "send"
|
|
STATUS_NORMAL = "normal"
|
|
STATUS_INVALID = "invalid"
|
|
|
|
|
|
def total_pages(total: int, page_size: int) -> int:
|
|
if page_size <= 0:
|
|
return 0
|
|
return math.ceil(total / page_size)
|
|
|
|
|
|
def _parse_date(value: Any) -> Optional[date]:
|
|
if value is None or value == "":
|
|
return None
|
|
if isinstance(value, datetime):
|
|
return value.date()
|
|
if isinstance(value, date):
|
|
return value
|
|
text = str(value).strip()
|
|
if not text:
|
|
return None
|
|
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y-%m-%d %H:%M:%S"):
|
|
try:
|
|
return datetime.strptime(text[:19] if " " in text else text[:10], fmt).date()
|
|
except ValueError:
|
|
continue
|
|
raise ValueError(f"日期格式无效: {value}")
|
|
|
|
|
|
def _strip_html(text: Optional[str]) -> str:
|
|
if not text:
|
|
return ""
|
|
return re.sub(r"<[^>]+>", "", text).replace(" ", " ").strip()
|
|
|
|
|
|
def _row_to_dict(row: CrmPriceLetter) -> Dict[str, Any]:
|
|
return {
|
|
"id": row.id,
|
|
"letterType": row.letter_type or "",
|
|
"adjustDate": row.adjust_date.strftime("%Y-%m-%d") if row.adjust_date else "",
|
|
"customerId": row.customer_id or "",
|
|
"customerName": row.customer_name or "",
|
|
"productId": row.product_id or "",
|
|
"productName": row.product_name or "",
|
|
"price": float(row.price) if row.price is not None else None,
|
|
"billPrice": float(row.bill_price) if row.bill_price is not None else None,
|
|
"content": row.content or "",
|
|
"attachmentUrls": row.attachment_urls or "",
|
|
"status": row.status or STATUS_NORMAL,
|
|
"invalidReason": row.invalid_reason or "",
|
|
"invalidTime": row.invalid_time.strftime("%Y-%m-%d %H:%M:%S") if row.invalid_time else "",
|
|
"invalidBy": row.invalid_by or "",
|
|
"orderNum": row.order_num if row.order_num is not None else 0,
|
|
"remark": row.remark or "",
|
|
"createBy": row.create_by or "",
|
|
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
|
|
"updateBy": row.update_by or "",
|
|
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
|
|
}
|
|
|
|
|
|
def _validate_letter_payload(
|
|
*,
|
|
letter_type: str,
|
|
content: Optional[str],
|
|
attachment_urls: Optional[str],
|
|
) -> None:
|
|
lt = (letter_type or "").strip()
|
|
if lt not in (LETTER_TYPE_RECEIVE, LETTER_TYPE_SEND):
|
|
raise ValueError("调价函类型无效,仅支持 receive 或 send")
|
|
att = (attachment_urls or "").strip()
|
|
has_att = bool(att)
|
|
has_content = bool(_strip_html(content))
|
|
if lt == LETTER_TYPE_RECEIVE:
|
|
if not has_att:
|
|
raise ValueError("接受调价函须上传附件")
|
|
elif lt == LETTER_TYPE_SEND:
|
|
if not has_content and not has_att:
|
|
raise ValueError("发出调价函须填写富文本内容或上传附件")
|
|
|
|
|
|
def list_price_letters(
|
|
db: Session,
|
|
tenant_no: str,
|
|
*,
|
|
page: int = 1,
|
|
page_size: int = 10,
|
|
letter_type: Optional[str] = None,
|
|
customer_name: Optional[str] = None,
|
|
product_name: Optional[str] = None,
|
|
status: Optional[str] = None,
|
|
exclude_status: Optional[str] = None,
|
|
adjust_date_from: Optional[str] = None,
|
|
adjust_date_to: Optional[str] = None,
|
|
keyword: Optional[str] = None,
|
|
user_info=None,
|
|
) -> Tuple[List[Dict[str, Any]], int]:
|
|
q = db.query(CrmPriceLetter).filter(
|
|
CrmPriceLetter.tenant_no == tenant_no,
|
|
CrmPriceLetter.del_flag == 0,
|
|
)
|
|
if user_info:
|
|
q = apply_crm_create_by_scope(q, CrmPriceLetter, user_info, db, tenant_no)
|
|
|
|
if letter_type:
|
|
q = q.filter(CrmPriceLetter.letter_type == letter_type.strip())
|
|
cn = (customer_name or "").strip()
|
|
if cn:
|
|
q = q.filter(CrmPriceLetter.customer_name.like(f"%{cn}%"))
|
|
pn = (product_name or "").strip()
|
|
if pn:
|
|
q = q.filter(CrmPriceLetter.product_name.like(f"%{pn}%"))
|
|
if status:
|
|
q = q.filter(CrmPriceLetter.status == status.strip())
|
|
if exclude_status:
|
|
q = q.filter(CrmPriceLetter.status != exclude_status.strip())
|
|
|
|
d_from = _parse_date(adjust_date_from) if adjust_date_from else None
|
|
d_to = _parse_date(adjust_date_to) if adjust_date_to else None
|
|
if d_from:
|
|
q = q.filter(CrmPriceLetter.adjust_date >= d_from)
|
|
if d_to:
|
|
q = q.filter(CrmPriceLetter.adjust_date <= d_to)
|
|
|
|
kw = (keyword or "").strip()
|
|
if kw:
|
|
like = f"%{kw}%"
|
|
q = q.filter(
|
|
or_(
|
|
CrmPriceLetter.customer_name.like(like),
|
|
CrmPriceLetter.product_name.like(like),
|
|
CrmPriceLetter.remark.like(like),
|
|
)
|
|
)
|
|
|
|
total = q.order_by(None).with_entities(func.count(CrmPriceLetter.id)).scalar() or 0
|
|
page = max(1, page)
|
|
page_size = min(max(1, page_size), 500)
|
|
rows = (
|
|
q.order_by(CrmPriceLetter.create_time.desc())
|
|
.offset((page - 1) * page_size)
|
|
.limit(page_size)
|
|
.all()
|
|
)
|
|
return [_row_to_dict(r) for r in rows], int(total)
|
|
|
|
|
|
def get_price_letter(db: Session, letter_id: str) -> Optional[CrmPriceLetter]:
|
|
if not letter_id:
|
|
return None
|
|
return (
|
|
db.query(CrmPriceLetter)
|
|
.filter(CrmPriceLetter.id == letter_id, CrmPriceLetter.del_flag == 0)
|
|
.first()
|
|
)
|
|
|
|
|
|
def create_price_letter(
|
|
db: Session,
|
|
*,
|
|
tenant_no: str,
|
|
user_id: str = None,
|
|
dept_id: str = "",
|
|
**kwargs,
|
|
) -> CrmPriceLetter:
|
|
letter_type = (kwargs.get("letter_type") or "").strip()
|
|
content = kwargs.get("content")
|
|
attachment_urls = kwargs.get("attachment_urls")
|
|
_validate_letter_payload(
|
|
letter_type=letter_type, content=content, attachment_urls=attachment_urls
|
|
)
|
|
|
|
customer_id = (kwargs.get("customer_id") or "").strip()
|
|
product_id = (kwargs.get("product_id") or "").strip()
|
|
if not customer_id:
|
|
raise ValueError("请选择客户")
|
|
if not product_id:
|
|
raise ValueError("请选择产品")
|
|
|
|
customer_name = (kwargs.get("customer_name") or "").strip()
|
|
product_name = (kwargs.get("product_name") or "").strip()
|
|
cust = get_customer(db, customer_id)
|
|
if not cust or cust.tenant_no != tenant_no or int(cust.del_flag or 0) != 0:
|
|
raise ValueError("客户不存在")
|
|
if not customer_name:
|
|
customer_name = cust.customer_name or ""
|
|
prod = get_product(db, product_id)
|
|
if not prod or prod.tenant_no != tenant_no or int(prod.del_flag or 0) != 0:
|
|
raise ValueError("产品不存在")
|
|
if not product_name:
|
|
product_name = prod.product_name or ""
|
|
|
|
adjust_date = _parse_date(kwargs.get("adjust_date"))
|
|
if not adjust_date:
|
|
raise ValueError("请选择调价日期")
|
|
price = kwargs.get("price")
|
|
if price is None:
|
|
raise ValueError("请填写调整后现金价格")
|
|
try:
|
|
price_val = Decimal(str(price))
|
|
except Exception as exc:
|
|
raise ValueError("调整后现金价格格式无效") from exc
|
|
if price_val < 0:
|
|
raise ValueError("调整后现金价格不能为负数")
|
|
|
|
bill_price = kwargs.get("bill_price")
|
|
if bill_price is None:
|
|
raise ValueError("请填写调整后汇票价格")
|
|
try:
|
|
bill_price_val = Decimal(str(bill_price))
|
|
except Exception as exc:
|
|
raise ValueError("调整后汇票价格格式无效") from exc
|
|
if bill_price_val < 0:
|
|
raise ValueError("调整后汇票价格不能为负数")
|
|
|
|
# receive: clear rich text; send: keep content
|
|
saved_content = "" if letter_type == LETTER_TYPE_RECEIVE else (content or "")
|
|
|
|
obj = CrmPriceLetter(
|
|
id=generate_uuid(),
|
|
letter_type=letter_type,
|
|
adjust_date=adjust_date,
|
|
customer_id=customer_id,
|
|
customer_name=customer_name,
|
|
product_id=product_id,
|
|
product_name=product_name,
|
|
price=price_val,
|
|
bill_price=bill_price_val,
|
|
content=saved_content,
|
|
attachment_urls=(attachment_urls or "").strip() or None,
|
|
status=STATUS_NORMAL,
|
|
tenant_no=tenant_no,
|
|
remark=kwargs.get("remark"),
|
|
create_by=user_id,
|
|
create_dept_id=dept_id or "",
|
|
update_by=user_id,
|
|
)
|
|
db.add(obj)
|
|
db.commit()
|
|
db.refresh(obj)
|
|
return obj
|
|
|
|
|
|
def update_price_letter(
|
|
db: Session,
|
|
letter_id: str,
|
|
*,
|
|
tenant_no: str,
|
|
user_id: str = None,
|
|
user_info=None,
|
|
**kwargs,
|
|
) -> CrmPriceLetter:
|
|
obj = get_price_letter(db, letter_id)
|
|
if not obj or obj.tenant_no != tenant_no:
|
|
raise ValueError("调价函不存在")
|
|
ensure_crm_create_by_row_in_scope(db, obj, user_info, tenant_no, message="无权操作该调价函")
|
|
if obj.status == STATUS_INVALID:
|
|
raise ValueError("已作废的调价函不可编辑")
|
|
|
|
letter_type = (kwargs.get("letter_type") if "letter_type" in kwargs else obj.letter_type) or ""
|
|
letter_type = str(letter_type).strip()
|
|
content = kwargs.get("content") if "content" in kwargs else obj.content
|
|
attachment_urls = (
|
|
kwargs.get("attachment_urls") if "attachment_urls" in kwargs else obj.attachment_urls
|
|
)
|
|
_validate_letter_payload(
|
|
letter_type=letter_type, content=content, attachment_urls=attachment_urls
|
|
)
|
|
|
|
if "customer_id" in kwargs and kwargs.get("customer_id"):
|
|
customer_id = str(kwargs.get("customer_id")).strip()
|
|
cust = get_customer(db, customer_id)
|
|
if not cust or cust.tenant_no != tenant_no or int(cust.del_flag or 0) != 0:
|
|
raise ValueError("客户不存在")
|
|
obj.customer_id = customer_id
|
|
obj.customer_name = (kwargs.get("customer_name") or "").strip() or (cust.customer_name or "")
|
|
elif "customer_name" in kwargs and kwargs.get("customer_name"):
|
|
obj.customer_name = str(kwargs.get("customer_name")).strip()
|
|
|
|
if "product_id" in kwargs and kwargs.get("product_id"):
|
|
product_id = str(kwargs.get("product_id")).strip()
|
|
prod = get_product(db, product_id)
|
|
if not prod or prod.tenant_no != tenant_no or int(prod.del_flag or 0) != 0:
|
|
raise ValueError("产品不存在")
|
|
obj.product_id = product_id
|
|
obj.product_name = (kwargs.get("product_name") or "").strip() or (prod.product_name or "")
|
|
elif "product_name" in kwargs and kwargs.get("product_name"):
|
|
obj.product_name = str(kwargs.get("product_name")).strip()
|
|
|
|
if "adjust_date" in kwargs:
|
|
d = _parse_date(kwargs.get("adjust_date"))
|
|
if not d:
|
|
raise ValueError("请选择调价日期")
|
|
obj.adjust_date = d
|
|
if "price" in kwargs and kwargs.get("price") is not None:
|
|
try:
|
|
price_val = Decimal(str(kwargs.get("price")))
|
|
except Exception as exc:
|
|
raise ValueError("调整后现金价格格式无效") from exc
|
|
if price_val < 0:
|
|
raise ValueError("调整后现金价格不能为负数")
|
|
obj.price = price_val
|
|
if "bill_price" in kwargs and kwargs.get("bill_price") is not None:
|
|
try:
|
|
bill_price_val = Decimal(str(kwargs.get("bill_price")))
|
|
except Exception as exc:
|
|
raise ValueError("调整后汇票价格格式无效") from exc
|
|
if bill_price_val < 0:
|
|
raise ValueError("调整后汇票价格不能为负数")
|
|
obj.bill_price = bill_price_val
|
|
|
|
obj.letter_type = letter_type
|
|
if letter_type == LETTER_TYPE_RECEIVE:
|
|
obj.content = ""
|
|
else:
|
|
obj.content = content or ""
|
|
obj.attachment_urls = (attachment_urls or "").strip() or None
|
|
if "remark" in kwargs:
|
|
obj.remark = kwargs.get("remark")
|
|
obj.update_by = user_id
|
|
obj.update_time = datetime.now()
|
|
db.commit()
|
|
db.refresh(obj)
|
|
return obj
|
|
|
|
|
|
def void_price_letter(
|
|
db: Session,
|
|
letter_id: str,
|
|
*,
|
|
tenant_no: str,
|
|
invalid_reason: str,
|
|
remark: str = "",
|
|
user_id: str = None,
|
|
user_info=None,
|
|
) -> CrmPriceLetter:
|
|
if not (invalid_reason or "").strip():
|
|
raise ValueError("作废原因不能为空")
|
|
obj = get_price_letter(db, letter_id)
|
|
if not obj or obj.tenant_no != tenant_no:
|
|
raise ValueError("调价函不存在")
|
|
ensure_crm_create_by_row_in_scope(db, obj, user_info, tenant_no, message="无权操作该调价函")
|
|
if obj.status == STATUS_INVALID:
|
|
raise ValueError("该调价函已作废")
|
|
obj.status = STATUS_INVALID
|
|
obj.invalid_reason = invalid_reason.strip()
|
|
obj.invalid_time = datetime.now()
|
|
obj.invalid_by = user_id
|
|
if remark:
|
|
obj.remark = remark
|
|
obj.update_by = user_id
|
|
obj.update_time = datetime.now()
|
|
db.commit()
|
|
db.refresh(obj)
|
|
return obj
|