提交
This commit is contained in:
1 parent
4611dbc2b2
commit
ebf006eeff
46 files changed
+36802
-20974
No files matched your search
+61
-108
@@ -63,10 +63,15 @@ from app.schemas.pl.plan import (
|
||||
PlanRead,
|
||||
PlanSideContractsUpdateBody,
|
||||
PlanSiteFeedbackUpdateBody,
|
||||
PlanStopContractsUpdateBody,
|
||||
PlanUpdate,
|
||||
PlanWithProducts,
|
||||
)
|
||||
from app.services.pl_plan_contract_gap import list_plan_contract_gaps, update_plan_side_contracts
|
||||
from app.services.pl_plan_contract_gap import (
|
||||
list_plan_contract_gaps,
|
||||
update_plan_side_contracts,
|
||||
update_plan_stop_contracts,
|
||||
)
|
||||
from app.services.pl_brand_archive import load_brand_qtys_by_plan_product_ids
|
||||
from app.services.pl_product_display import (
|
||||
load_crm_product_alias_maps,
|
||||
@@ -93,6 +98,7 @@ from app.services.pl_plan_archive_stop_service import (
|
||||
sum_delivery_outbound_qty,
|
||||
sync_plan_products_from_stop_archive,
|
||||
)
|
||||
from app.services.pl_plan_archive_export import build_plan_archive_export_rows
|
||||
from app.services.pl_plan_list_attachments import load_plan_document_attachments_by_plan_ids
|
||||
from app.services.pl_plan_print_service import get_delivery_slip_print_context
|
||||
from app.services.pl_plan_stop_service import (
|
||||
@@ -345,6 +351,11 @@ def list_plans(
|
||||
alias="certUploadStatus",
|
||||
description="incomplete=至少一张必需危化证书未上传",
|
||||
),
|
||||
hazard_cert_ready: Optional[int] = Query(
|
||||
default=None,
|
||||
alias="hazardCertReady",
|
||||
description="0=未确认齐备 1=已确认齐备",
|
||||
),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=500, alias="pageSize"),
|
||||
db: Session = Depends(get_db),
|
||||
@@ -411,6 +422,9 @@ def list_plans(
|
||||
if (cert_upload_status or "").strip().lower() == "incomplete":
|
||||
query = query.filter(plan_has_incomplete_hazard_cert_exists(tenant_no))
|
||||
|
||||
if hazard_cert_ready is not None:
|
||||
query = query.filter(PlPlan.hazard_cert_ready == int(hazard_cert_ready))
|
||||
|
||||
query = apply_pl_scope(query, PlPlan, user, db, tenant_no)
|
||||
|
||||
# 统计总数
|
||||
@@ -537,37 +551,33 @@ PLAN_EXPORT_COLUMNS = [
|
||||
|
||||
PLAN_ARCHIVE_EXPORT_COLUMNS = [
|
||||
ExportColumn(title="序号", field="rowNo"),
|
||||
ExportColumn(title="到货日期", field="deliveryDate"),
|
||||
ExportColumn(title="供方名称", field="supplierName"),
|
||||
ExportColumn(title="需方名称", field="customerName"),
|
||||
ExportColumn(title="计划编号", field="planNo"),
|
||||
ExportColumn(title="计划日期", field="planDate"),
|
||||
ExportColumn(title="归档状态", field="archiveStatus"),
|
||||
ExportColumn(title="跟进状态", field="followStatus"),
|
||||
ExportColumn(title="单据类型", field="planType"),
|
||||
ExportColumn(title="段次", field="stopKind"),
|
||||
ExportColumn(title="客户", field="stopCustomer"),
|
||||
ExportColumn(title="地址", field="stopAddress"),
|
||||
ExportColumn(title="段次时间", field="stopTime"),
|
||||
ExportColumn(title="产品名称", field="productName"),
|
||||
ExportColumn(title="型号/规格", field="model"),
|
||||
ExportColumn(title="包装", field="packageSpec"),
|
||||
ExportColumn(title="单位", field="unit"),
|
||||
ExportColumn(title="入库数", field="inboundQty"),
|
||||
ExportColumn(title="入库价", field="inboundPrice"),
|
||||
ExportColumn(title="入库金额", field="inboundAmount"),
|
||||
ExportColumn(title="出库数", field="outboundQty"),
|
||||
ExportColumn(title="出库价", field="outboundPrice"),
|
||||
ExportColumn(title="出库金额", field="outboundAmount"),
|
||||
ExportColumn(title="计划数量", field="planQty"),
|
||||
ExportColumn(title="实际数量", field="actualQty"),
|
||||
ExportColumn(title="入库数量", field="inboundQty"),
|
||||
ExportColumn(title="出库数量", field="outboundQty"),
|
||||
ExportColumn(title="单价(元)", field="unitPrice"),
|
||||
ExportColumn(title="金额(元)", field="amount"),
|
||||
ExportColumn(title="车牌号", field="licensePlate"),
|
||||
ExportColumn(title="运费单位", field="freightType"),
|
||||
ExportColumn(title="运费单价", field="freightPrice"),
|
||||
ExportColumn(title="运费金额", field="freightAmount"),
|
||||
ExportColumn(title="ERP", field="erpEntered"),
|
||||
ExportColumn(title="备注", field="remark"),
|
||||
]
|
||||
|
||||
PLAN_ARCHIVE_FREIGHT_TYPE_LABELS = {
|
||||
"by_weight": "按重量",
|
||||
"by_trip": "按趟",
|
||||
}
|
||||
|
||||
|
||||
def _format_plan_delivery_date_for_export(plan: PlPlan) -> str:
|
||||
if plan.delivery_time is None:
|
||||
return ""
|
||||
return str(plan.delivery_time)[:10]
|
||||
|
||||
|
||||
def _load_transports_by_id(db: Session, tenant_no: str, transport_ids: list[str]) -> dict[str, PlTransport]:
|
||||
if not transport_ids:
|
||||
@@ -584,89 +594,6 @@ def _load_transports_by_id(db: Session, tenant_no: str, transport_ids: list[str]
|
||||
return {row.id: row for row in rows}
|
||||
|
||||
|
||||
def _load_products_by_plan_id(db: Session, tenant_no: str, plan_ids: list[str]) -> dict[str, list[PlPlanProduct]]:
|
||||
if not plan_ids:
|
||||
return {}
|
||||
products = (
|
||||
db.query(PlPlanProduct)
|
||||
.filter(
|
||||
PlPlanProduct.tenant_no == tenant_no,
|
||||
PlPlanProduct.del_flag == 0,
|
||||
PlPlanProduct.plan_id.in_(plan_ids),
|
||||
)
|
||||
.order_by(PlPlanProduct.order_num)
|
||||
.all()
|
||||
)
|
||||
grouped: dict[str, list[PlPlanProduct]] = {}
|
||||
for product in products:
|
||||
grouped.setdefault(product.plan_id, []).append(product)
|
||||
return grouped
|
||||
|
||||
|
||||
def _build_plan_archive_export_rows(
|
||||
plans: list[PlPlan],
|
||||
products_by_plan: dict[str, list[PlPlanProduct]],
|
||||
transports_by_id: dict[str, PlTransport],
|
||||
) -> list[dict]:
|
||||
rows: list[dict] = []
|
||||
row_no = 0
|
||||
for plan in plans:
|
||||
products = products_by_plan.get(plan.id, [])
|
||||
transport = transports_by_id.get(plan.transport_id) if plan.transport_id else None
|
||||
freight_type_raw = transport.freight_type if transport else "by_weight"
|
||||
freight_type_label = PLAN_ARCHIVE_FREIGHT_TYPE_LABELS.get(
|
||||
freight_type_raw, freight_type_raw or ""
|
||||
)
|
||||
freight_price = transport.freight_price if transport else None
|
||||
freight_amount = plan.freight_amount
|
||||
if freight_amount is None and transport is not None:
|
||||
freight_amount = transport.freight_amount
|
||||
plan_common = {
|
||||
"deliveryDate": _format_plan_delivery_date_for_export(plan),
|
||||
"supplierName": plan.supplier_name or "",
|
||||
"customerName": plan.customer_name or "",
|
||||
"licensePlate": plan.license_plate or "",
|
||||
"freightType": freight_type_label,
|
||||
"freightPrice": freight_price,
|
||||
"freightAmount": freight_amount,
|
||||
"remark": "",
|
||||
}
|
||||
product_rows = products or [None]
|
||||
for product in product_rows:
|
||||
row_no += 1
|
||||
row = {
|
||||
**plan_common,
|
||||
"rowNo": row_no,
|
||||
"productName": "",
|
||||
"model": "",
|
||||
"packageSpec": "",
|
||||
"unit": "",
|
||||
"inboundQty": None,
|
||||
"inboundPrice": None,
|
||||
"inboundAmount": None,
|
||||
"outboundQty": None,
|
||||
"outboundPrice": None,
|
||||
"outboundAmount": None,
|
||||
}
|
||||
if product is not None:
|
||||
row.update(
|
||||
{
|
||||
"productName": product.product_name or "",
|
||||
"model": product.model or "",
|
||||
"packageSpec": product.package_spec or "",
|
||||
"unit": product.unit or "",
|
||||
"inboundQty": product.inbound_qty,
|
||||
"inboundPrice": product.inbound_price,
|
||||
"inboundAmount": product.inbound_amount,
|
||||
"outboundQty": product.outbound_qty,
|
||||
"outboundPrice": product.outbound_price,
|
||||
"outboundAmount": product.outbound_amount,
|
||||
}
|
||||
)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
class PlanExportBody(BaseModel):
|
||||
q: Optional[str] = None
|
||||
plan_no: Optional[str] = Field(default=None, alias="planNo")
|
||||
@@ -681,6 +608,7 @@ class PlanExportBody(BaseModel):
|
||||
plan_date_to: Optional[date] = Field(default=None, alias="planDateTo")
|
||||
has_hazard_product: Optional[int] = Field(default=None, alias="hasHazardProduct")
|
||||
cert_upload_status: Optional[str] = Field(default=None, alias="certUploadStatus")
|
||||
hazard_cert_ready: Optional[int] = Field(default=None, alias="hazardCertReady")
|
||||
ids: Optional[List[str]] = None
|
||||
columns: Optional[List[str]] = None
|
||||
export_format: Optional[str] = Field(default=None, alias="exportFormat", description="archive=运输计划归档专用导出")
|
||||
@@ -743,6 +671,8 @@ def export_plans(
|
||||
query = query.filter(plan_has_hazard_product_exists(tenant_no))
|
||||
if (body.cert_upload_status or "").strip().lower() == "incomplete":
|
||||
query = query.filter(plan_has_incomplete_hazard_cert_exists(tenant_no))
|
||||
if body.hazard_cert_ready is not None:
|
||||
query = query.filter(PlPlan.hazard_cert_ready == int(body.hazard_cert_ready))
|
||||
if body.ids:
|
||||
query = query.filter(PlPlan.id.in_(body.ids))
|
||||
query = apply_pl_scope(query, PlPlan, user, db, tenant_no)
|
||||
@@ -750,12 +680,10 @@ def export_plans(
|
||||
date_str = datetime.now().strftime("%Y%m%d")
|
||||
is_archive_export = (body.export_format or "").strip().lower() == "archive"
|
||||
if is_archive_export:
|
||||
plan_ids = [plan.id for plan in plans]
|
||||
products_by_plan = _load_products_by_plan_id(db, tenant_no, plan_ids)
|
||||
transport_ids = [plan.transport_id for plan in plans if plan.transport_id]
|
||||
transports_by_id = _load_transports_by_id(db, tenant_no, transport_ids)
|
||||
items = _build_plan_archive_export_rows(plans, products_by_plan, transports_by_id)
|
||||
cols = PLAN_ARCHIVE_EXPORT_COLUMNS
|
||||
items = build_plan_archive_export_rows(db, tenant_no, plans, transports_by_id)
|
||||
cols = filter_export_columns(PLAN_ARCHIVE_EXPORT_COLUMNS, body.columns)
|
||||
sheet_title = "计划归档"
|
||||
filename_stem = f"计划归档_{date_str}"
|
||||
else:
|
||||
@@ -948,6 +876,31 @@ def export_contract_gaps(
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.put("/{id}/stop-contracts", response_model=PlanContractGapRead)
|
||||
def put_plan_stop_contracts(
|
||||
id: str,
|
||||
payload: PlanStopContractsUpdateBody,
|
||||
db: Session = Depends(get_db),
|
||||
user: DbUserContext = Depends(get_db_current_user),
|
||||
) -> PlanContractGapRead:
|
||||
"""保存某装货/送货段合同关联(合同补全)。"""
|
||||
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
|
||||
plan = _get_plan(db, tenant_no, id, user)
|
||||
result = update_plan_stop_contracts(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan=plan,
|
||||
stop_type=payload.stop_type,
|
||||
stop_id=payload.stop_id,
|
||||
contracts=payload.contracts,
|
||||
user_id=user.id,
|
||||
dept_id=user.dept_id,
|
||||
)
|
||||
plan.update_by = user.id
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.put("/{id}/contracts/{side}", response_model=PlanContractGapRead)
|
||||
def put_plan_side_contracts(
|
||||
id: str,
|
||||
|
||||
@@ -455,16 +455,22 @@ class PlPlanProduct(Base):
|
||||
|
||||
|
||||
class PlPlanProductBrandQty(Base):
|
||||
"""计划产品归档品牌数量 pl_plan_product_brand_qty"""
|
||||
"""计划产品归档品牌数量 pl_plan_product_brand_qty
|
||||
|
||||
stop_product_id 为空:计划产品级汇总;非空:装货/送货段产品行上的填写值。
|
||||
"""
|
||||
|
||||
__tablename__ = "pl_plan_product_brand_qty"
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="主键ID")
|
||||
plan_id = Column(String(64), nullable=False, comment="计划ID")
|
||||
plan_product_id = Column(String(64), nullable=False, comment="计划产品明细ID")
|
||||
stop_type = Column(String(20), nullable=True, comment="load/delivery,空=计划级汇总")
|
||||
stop_product_id = Column(String(64), nullable=True, comment="段产品行ID,空=计划级汇总")
|
||||
brand_id = Column(String(64), nullable=False, default="", comment="品牌ID,空串=无品牌键")
|
||||
brand_name = Column(String(100), nullable=True, comment="品牌名称")
|
||||
qty = Column(DECIMAL(15, 3), nullable=False, default=0, comment="本品牌归档实际数量")
|
||||
unit_price = Column(DECIMAL(15, 4), nullable=True, comment="本品牌归档单价")
|
||||
tenant_no = Column(String(64), nullable=False, default="shanxia2.0", comment="租户编号")
|
||||
order_num = Column(Integer, nullable=True, comment="排序号")
|
||||
remark = Column(String(512), nullable=True, comment="备注")
|
||||
|
||||
@@ -82,6 +82,7 @@ class PlanArchiveBrandQtyItem(BaseModel):
|
||||
brand_id: str = Field(default="", alias="brandId")
|
||||
brand_name: Optional[str] = Field(default=None, alias="brandName")
|
||||
qty: Decimal = Field(..., ge=0)
|
||||
unit_price: Optional[Decimal] = Field(default=None, alias="unitPrice", ge=0, description="本品牌单价")
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
@@ -129,6 +130,9 @@ class PlanStopProductRead(PlanStopProductBody):
|
||||
outbound_qty: Optional[Decimal] = Field(default=None, alias="outboundQty", description="出库数量(送货段归档)")
|
||||
outbound_price: Optional[Decimal] = Field(default=None, alias="outboundPrice", description="出库单价(送货段归档)")
|
||||
outbound_amount: Optional[Decimal] = Field(default=None, alias="outboundAmount", description="出库金额(送货段归档)")
|
||||
brand_qtys: Optional[list[PlanArchiveBrandQtyItem]] = Field(
|
||||
default=None, alias="brandQtys", description="本段归档品牌数量"
|
||||
)
|
||||
tenant_no: str = Field(alias="tenantNo")
|
||||
order_num: Optional[int] = Field(default=None, alias="orderNum")
|
||||
create_time: datetime = Field(alias="createTime")
|
||||
@@ -557,6 +561,9 @@ class PlanArchiveStopProductItem(BaseModel):
|
||||
inbound_price: Optional[Decimal] = Field(default=None, alias="inboundPrice", ge=0, description="入库单价(装货段)")
|
||||
outbound_qty: Optional[Decimal] = Field(default=None, alias="outboundQty", ge=0, description="出库数量(送货段)")
|
||||
outbound_price: Optional[Decimal] = Field(default=None, alias="outboundPrice", ge=0, description="出库单价(送货段)")
|
||||
brand_qtys: Optional[list[PlanArchiveBrandQtyItem]] = Field(
|
||||
default=None, alias="brandQtys", description="本段归档品牌数量(与归档弹窗填写一致)"
|
||||
)
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
@@ -642,6 +649,13 @@ class PlanSideContractsUpdateBody(BaseModel):
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
class PlanStopContractsUpdateBody(BaseModel):
|
||||
stop_type: str = Field(..., alias="stopType", description="load | delivery")
|
||||
stop_id: str = Field(..., alias="stopId", description="装货/送货段ID")
|
||||
contracts: list[PlanContractLink] = Field(default_factory=list)
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
class PlanContractGapRead(BaseModel):
|
||||
id: str
|
||||
plan_no: str = Field(..., alias="planNo")
|
||||
@@ -658,6 +672,8 @@ class PlanContractGapRead(BaseModel):
|
||||
supplier_contracts: list[PlanContractLink] = Field(default_factory=list, alias="supplierContracts")
|
||||
demander_contracts: list[PlanContractLink] = Field(default_factory=list, alias="demanderContracts")
|
||||
products: list[PlanProductRead] = Field(default_factory=list, description="产品明细")
|
||||
load: Optional["PlanLoadRead"] = Field(default=None, description="装货段")
|
||||
deliveries: list["PlanDeliveryRead"] = Field(default_factory=list, alias="deliveries", description="送货段列表")
|
||||
model_config = {"populate_by_name": True, "from_attributes": True}
|
||||
|
||||
|
||||
|
||||
@@ -2,19 +2,46 @@
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.pl_models import PlPlanProductBrandQty
|
||||
|
||||
|
||||
def _is_plan_level_row(row: PlPlanProductBrandQty) -> bool:
|
||||
return not (getattr(row, "stop_product_id", None) or "").strip()
|
||||
|
||||
|
||||
def _row_to_brand_dict(row: PlPlanProductBrandQty) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {
|
||||
"brandId": row.brand_id or "",
|
||||
"brandName": row.brand_name,
|
||||
"qty": Decimal(str(row.qty or 0)),
|
||||
}
|
||||
if row.unit_price is not None:
|
||||
data["unitPrice"] = Decimal(str(row.unit_price))
|
||||
return data
|
||||
|
||||
|
||||
def _parse_unit_price(item: dict[str, Any]) -> Optional[Decimal]:
|
||||
raw = item.get("unitPrice")
|
||||
if raw is None:
|
||||
raw = item.get("unit_price")
|
||||
if raw is None:
|
||||
raw = item.get("price")
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
return Decimal(str(raw))
|
||||
|
||||
|
||||
def load_brand_qtys_by_plan_product_ids(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan_product_ids: list[str],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""按计划产品明细 ID 批量加载归档品牌数量(brandId/brandName/qty)。"""
|
||||
"""按计划产品明细 ID 批量加载计划级归档品牌数量(brandId/brandName/qty/unitPrice)。"""
|
||||
ids = [pid for pid in plan_product_ids if pid]
|
||||
if not ids:
|
||||
return {}
|
||||
@@ -24,6 +51,39 @@ def load_brand_qtys_by_plan_product_ids(
|
||||
PlPlanProductBrandQty.plan_product_id.in_(ids),
|
||||
PlPlanProductBrandQty.tenant_no == tenant_no,
|
||||
PlPlanProductBrandQty.del_flag == 0,
|
||||
or_(
|
||||
PlPlanProductBrandQty.stop_product_id.is_(None),
|
||||
PlPlanProductBrandQty.stop_product_id == "",
|
||||
),
|
||||
)
|
||||
.order_by(PlPlanProductBrandQty.order_num.asc())
|
||||
.all()
|
||||
)
|
||||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
qty = Decimal(str(row.qty or 0))
|
||||
if qty <= 0:
|
||||
continue
|
||||
grouped.setdefault(row.plan_product_id, []).append(_row_to_brand_dict(row))
|
||||
return grouped
|
||||
|
||||
|
||||
def load_brand_qtys_by_stop_product_ids(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
stop_product_ids: list[str],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""按装货/送货段产品行 ID 批量加载段级归档品牌数量。"""
|
||||
ids = [pid for pid in stop_product_ids if pid]
|
||||
if not ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(PlPlanProductBrandQty)
|
||||
.filter(
|
||||
PlPlanProductBrandQty.stop_product_id.in_(ids),
|
||||
PlPlanProductBrandQty.tenant_no == tenant_no,
|
||||
PlPlanProductBrandQty.del_flag == 0,
|
||||
)
|
||||
.order_by(PlPlanProductBrandQty.order_num.asc())
|
||||
.all()
|
||||
@@ -33,13 +93,10 @@ def load_brand_qtys_by_plan_product_ids(
|
||||
qty = Decimal(str(row.qty or 0))
|
||||
if qty <= 0:
|
||||
continue
|
||||
grouped.setdefault(row.plan_product_id, []).append(
|
||||
{
|
||||
"brandId": row.brand_id or "",
|
||||
"brandName": row.brand_name,
|
||||
"qty": qty,
|
||||
}
|
||||
)
|
||||
stop_id = (row.stop_product_id or "").strip()
|
||||
if not stop_id:
|
||||
continue
|
||||
grouped.setdefault(stop_id, []).append(_row_to_brand_dict(row))
|
||||
return grouped
|
||||
|
||||
|
||||
@@ -72,7 +129,7 @@ def persist_plan_product_brand_qtys(
|
||||
user_id: str,
|
||||
dept_id: str = "",
|
||||
) -> None:
|
||||
"""软删旧品牌量行后按归档结果插入;无品牌约定则只软删不插入。"""
|
||||
"""软删计划级旧品牌量行后按归档结果插入;无品牌约定则只软删不插入。不触碰段级行。"""
|
||||
existing = (
|
||||
db.query(PlPlanProductBrandQty)
|
||||
.filter(
|
||||
@@ -83,6 +140,8 @@ def persist_plan_product_brand_qtys(
|
||||
.all()
|
||||
)
|
||||
for row in existing:
|
||||
if not _is_plan_level_row(row):
|
||||
continue
|
||||
row.del_flag = 1
|
||||
row.update_by = user_id
|
||||
|
||||
@@ -101,9 +160,72 @@ def persist_plan_product_brand_qtys(
|
||||
tenant_no=tenant_no,
|
||||
plan_id=plan_id,
|
||||
plan_product_id=plan_product_id,
|
||||
stop_type=None,
|
||||
stop_product_id=None,
|
||||
brand_id=brand_id,
|
||||
brand_name=brand_name,
|
||||
qty=qty,
|
||||
unit_price=_parse_unit_price(item),
|
||||
order_num=idx,
|
||||
create_by=user_id,
|
||||
create_dept_id=dept_id or "",
|
||||
update_by=user_id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def persist_stop_product_brand_qtys(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan_id: str,
|
||||
plan_product_id: str,
|
||||
stop_type: str,
|
||||
stop_product_id: str,
|
||||
brand_mode: Optional[str],
|
||||
rows: list[dict[str, Any]],
|
||||
user_id: str,
|
||||
dept_id: str = "",
|
||||
) -> None:
|
||||
"""软删该段产品行旧品牌量后写入;无有效数量则只软删。"""
|
||||
stop_id = (stop_product_id or "").strip()
|
||||
if not stop_id:
|
||||
return
|
||||
existing = (
|
||||
db.query(PlPlanProductBrandQty)
|
||||
.filter(
|
||||
PlPlanProductBrandQty.stop_product_id == stop_id,
|
||||
PlPlanProductBrandQty.tenant_no == tenant_no,
|
||||
PlPlanProductBrandQty.del_flag == 0,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for row in existing:
|
||||
row.del_flag = 1
|
||||
row.update_by = user_id
|
||||
|
||||
positive = [item for item in rows if Decimal(str(item.get("qty") or 0)) > 0]
|
||||
if not brand_mode and not positive:
|
||||
return
|
||||
|
||||
for idx, item in enumerate(rows):
|
||||
qty = Decimal(str(item.get("qty") or 0))
|
||||
if qty <= 0:
|
||||
continue
|
||||
brand_id = item.get("brandId") or item.get("brand_id") or ""
|
||||
brand_name = item.get("brandName") or item.get("brand_name")
|
||||
db.add(
|
||||
PlPlanProductBrandQty(
|
||||
id=generate_uuid(),
|
||||
tenant_no=tenant_no,
|
||||
plan_id=plan_id,
|
||||
plan_product_id=plan_product_id,
|
||||
stop_type=stop_type,
|
||||
stop_product_id=stop_id,
|
||||
brand_id=brand_id,
|
||||
brand_name=brand_name,
|
||||
qty=qty,
|
||||
unit_price=_parse_unit_price(item),
|
||||
order_num=idx,
|
||||
create_by=user_id,
|
||||
create_dept_id=dept_id or "",
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.schemas.pl.plan import (
|
||||
PlanArchiveLoadBlock,
|
||||
PlanArchiveStopProductItem,
|
||||
)
|
||||
from app.services.pl_brand_archive import persist_stop_product_brand_qtys
|
||||
from app.services.pl_internal_customer import is_internal_customer_name
|
||||
|
||||
|
||||
@@ -60,6 +61,56 @@ def _apply_stop_product_archive(
|
||||
row.update_by = user_id
|
||||
|
||||
|
||||
def _brand_rows_from_item(item: PlanArchiveStopProductItem) -> list[dict]:
|
||||
if not item.brand_qtys:
|
||||
return []
|
||||
rows: list[dict] = []
|
||||
for bq in item.brand_qtys:
|
||||
row: dict = {
|
||||
"brandId": bq.brand_id or "",
|
||||
"brandName": bq.brand_name,
|
||||
"qty": bq.qty,
|
||||
}
|
||||
if bq.unit_price is not None:
|
||||
row["unitPrice"] = bq.unit_price
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def _persist_stop_brand_qtys(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan: PlPlan,
|
||||
stop_type: str,
|
||||
stop_row: PlPlanLoadProduct | PlPlanDeliveryProduct,
|
||||
item: PlanArchiveStopProductItem,
|
||||
user_id: str,
|
||||
) -> None:
|
||||
plan_product = (
|
||||
db.query(PlPlanProduct)
|
||||
.filter(
|
||||
PlPlanProduct.id == stop_row.plan_product_id,
|
||||
PlPlanProduct.tenant_no == tenant_no,
|
||||
PlPlanProduct.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
brand_mode = plan_product.brand_mode if plan_product else None
|
||||
persist_stop_product_brand_qtys(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan_id=plan.id,
|
||||
plan_product_id=stop_row.plan_product_id,
|
||||
stop_type=stop_type,
|
||||
stop_product_id=stop_row.id,
|
||||
brand_mode=brand_mode,
|
||||
rows=_brand_rows_from_item(item),
|
||||
user_id=user_id,
|
||||
dept_id=getattr(stop_row, "create_dept_id", "") or "",
|
||||
)
|
||||
|
||||
|
||||
def apply_archive_stop_quantities(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -102,6 +153,15 @@ def apply_archive_stop_quantities(
|
||||
_apply_stop_product_archive(
|
||||
row, item, mode="inbound", label="装货段", user_id=user_id
|
||||
)
|
||||
_persist_stop_brand_qtys(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan=plan,
|
||||
stop_type="load",
|
||||
stop_row=row,
|
||||
item=item,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
deliveries = (
|
||||
db.query(PlPlanDelivery)
|
||||
@@ -142,6 +202,15 @@ def apply_archive_stop_quantities(
|
||||
_apply_stop_product_archive(
|
||||
row, item, mode="outbound", label=label, user_id=user_id
|
||||
)
|
||||
_persist_stop_brand_qtys(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan=plan,
|
||||
stop_type="delivery",
|
||||
stop_row=row,
|
||||
item=item,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
|
||||
def sync_plan_products_from_stop_archive(
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, TYPE_CHECKING
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import and_, exists, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.pl_models import PlPlan, PlPlanContract, PlPlanProduct
|
||||
from app.schemas.pl.plan import PlanContractGapRead, PlanContractLink, PlanProductRead
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.pl_models import (
|
||||
PlPlan,
|
||||
PlPlanContract,
|
||||
PlPlanDelivery,
|
||||
PlPlanLoad,
|
||||
PlPlanProduct,
|
||||
)
|
||||
from app.schemas.pl.plan import (
|
||||
PlanContractGapRead,
|
||||
PlanContractLink,
|
||||
PlanDeliveryRead,
|
||||
PlanLoadRead,
|
||||
PlanProductRead,
|
||||
)
|
||||
from app.services.pl_data_scope import apply_pl_scope
|
||||
from app.services.pl_internal_customer import INTERNAL_CUSTOMER_NAMES, is_internal_customer_name
|
||||
from app.services.pl_plan_service import (
|
||||
@@ -19,11 +32,26 @@ from app.services.pl_plan_service import (
|
||||
load_plan_contracts_grouped,
|
||||
replace_plan_contracts,
|
||||
)
|
||||
from app.services.pl_plan_stop_service import (
|
||||
PLAN_CONTRACT_SIDE_DELIVERY,
|
||||
PLAN_CONTRACT_SIDE_LOAD,
|
||||
load_plan_stops_grouped,
|
||||
)
|
||||
from app.services.pl_product_display import load_crm_product_alias_maps, resolve_product_display_names
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.core.db_auth import DbUserContext
|
||||
|
||||
|
||||
def stop_contract_gap(customer_name: Optional[str], contract_count: int) -> bool:
|
||||
"""段次客户非内置且未关联合同时视为缺口。"""
|
||||
return not is_internal_customer_name(customer_name) and contract_count <= 0
|
||||
|
||||
|
||||
def side_is_exempt(name: Optional[str]) -> bool:
|
||||
return is_internal_customer_name(name)
|
||||
|
||||
|
||||
def compute_contract_gap_sides(
|
||||
*,
|
||||
supplier_name: Optional[str],
|
||||
@@ -32,57 +60,178 @@ def compute_contract_gap_sides(
|
||||
demander_contract_count: int,
|
||||
) -> List[str]:
|
||||
gaps: List[str] = []
|
||||
if not is_internal_customer_name(supplier_name) and supplier_contract_count <= 0:
|
||||
if stop_contract_gap(supplier_name, supplier_contract_count):
|
||||
gaps.append("supplier")
|
||||
if not is_internal_customer_name(customer_name) and demander_contract_count <= 0:
|
||||
if stop_contract_gap(customer_name, demander_contract_count):
|
||||
gaps.append("demander")
|
||||
return gaps
|
||||
|
||||
|
||||
def side_is_exempt(name: Optional[str]) -> bool:
|
||||
return is_internal_customer_name(name)
|
||||
def compute_plan_gap_sides_from_stops(
|
||||
load_read: Optional[PlanLoadRead],
|
||||
delivery_reads: list[PlanDeliveryRead],
|
||||
*,
|
||||
supplier_name: Optional[str] = None,
|
||||
customer_name: Optional[str] = None,
|
||||
supplier_contract_count: int = 0,
|
||||
demander_contract_count: int = 0,
|
||||
) -> list[str]:
|
||||
"""按段次汇总计划是否仍有合同缺口(supplier=装货侧,demander=送货侧)。"""
|
||||
has_load_gap = False
|
||||
has_delivery_gap = False
|
||||
|
||||
if load_read is not None:
|
||||
has_load_gap = stop_contract_gap(load_read.customer_name, len(load_read.contracts or []))
|
||||
elif stop_contract_gap(supplier_name, supplier_contract_count):
|
||||
has_load_gap = True
|
||||
|
||||
if delivery_reads:
|
||||
has_delivery_gap = any(
|
||||
stop_contract_gap(item.customer_name, len(item.contracts or []))
|
||||
for item in delivery_reads
|
||||
)
|
||||
elif stop_contract_gap(customer_name, demander_contract_count):
|
||||
has_delivery_gap = True
|
||||
|
||||
gaps: list[str] = []
|
||||
if has_load_gap:
|
||||
gaps.append("supplier")
|
||||
if has_delivery_gap:
|
||||
gaps.append("demander")
|
||||
return gaps
|
||||
|
||||
|
||||
def _side_contract_exists(tenant_no: str, side: str):
|
||||
def _stop_contract_exists(tenant_no: str, plan_id_expr, stop_id_expr, legacy_sides: tuple[str, ...]):
|
||||
return exists(
|
||||
select(PlPlanContract.id).where(
|
||||
PlPlanContract.plan_id == PlPlan.id,
|
||||
PlPlanContract.plan_id == plan_id_expr,
|
||||
PlPlanContract.tenant_no == tenant_no,
|
||||
PlPlanContract.del_flag == 0,
|
||||
PlPlanContract.side == side,
|
||||
or_(
|
||||
PlPlanContract.stop_id == stop_id_expr,
|
||||
and_(
|
||||
or_(PlPlanContract.stop_id.is_(None), PlPlanContract.stop_id == ""),
|
||||
PlPlanContract.side.in_(legacy_sides),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _supplier_gap_expr(tenant_no: str):
|
||||
def _load_stop_gap_expr(tenant_no: str):
|
||||
internal_names = tuple(INTERNAL_CUSTOMER_NAMES)
|
||||
customer_not_internal = or_(
|
||||
PlPlanLoad.customer_name.is_(None),
|
||||
PlPlanLoad.customer_name == "",
|
||||
~PlPlanLoad.customer_name.in_(internal_names),
|
||||
)
|
||||
return exists(
|
||||
select(PlPlanLoad.id).where(
|
||||
PlPlanLoad.plan_id == PlPlan.id,
|
||||
PlPlanLoad.tenant_no == tenant_no,
|
||||
PlPlanLoad.del_flag == 0,
|
||||
customer_not_internal,
|
||||
~_stop_contract_exists(
|
||||
tenant_no,
|
||||
PlPlan.id,
|
||||
PlPlanLoad.id,
|
||||
(PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_SUPPLIER),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _delivery_stop_gap_expr(tenant_no: str):
|
||||
internal_names = tuple(INTERNAL_CUSTOMER_NAMES)
|
||||
customer_not_internal = or_(
|
||||
PlPlanDelivery.customer_name.is_(None),
|
||||
PlPlanDelivery.customer_name == "",
|
||||
~PlPlanDelivery.customer_name.in_(internal_names),
|
||||
)
|
||||
return exists(
|
||||
select(PlPlanDelivery.id).where(
|
||||
PlPlanDelivery.plan_id == PlPlan.id,
|
||||
PlPlanDelivery.tenant_no == tenant_no,
|
||||
PlPlanDelivery.del_flag == 0,
|
||||
customer_not_internal,
|
||||
~_stop_contract_exists(
|
||||
tenant_no,
|
||||
PlPlan.id,
|
||||
PlPlanDelivery.id,
|
||||
(PLAN_CONTRACT_SIDE_DELIVERY, PLAN_CONTRACT_SIDE_DEMANDER),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _legacy_supplier_gap_expr(tenant_no: str):
|
||||
internal_names = tuple(INTERNAL_CUSTOMER_NAMES)
|
||||
has_load = exists(
|
||||
select(PlPlanLoad.id).where(
|
||||
PlPlanLoad.plan_id == PlPlan.id,
|
||||
PlPlanLoad.tenant_no == tenant_no,
|
||||
PlPlanLoad.del_flag == 0,
|
||||
)
|
||||
)
|
||||
supplier_not_internal = or_(
|
||||
PlPlan.supplier_name.is_(None),
|
||||
PlPlan.supplier_name == "",
|
||||
~PlPlan.supplier_name.in_(internal_names),
|
||||
)
|
||||
return and_(
|
||||
~has_load,
|
||||
supplier_not_internal,
|
||||
~_side_contract_exists(tenant_no, PLAN_CONTRACT_SIDE_SUPPLIER),
|
||||
~_stop_contract_exists(
|
||||
tenant_no,
|
||||
PlPlan.id,
|
||||
PlPlan.id,
|
||||
(PLAN_CONTRACT_SIDE_SUPPLIER,),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _demander_gap_expr(tenant_no: str):
|
||||
def _legacy_demander_gap_expr(tenant_no: str):
|
||||
internal_names = tuple(INTERNAL_CUSTOMER_NAMES)
|
||||
has_delivery = exists(
|
||||
select(PlPlanDelivery.id).where(
|
||||
PlPlanDelivery.plan_id == PlPlan.id,
|
||||
PlPlanDelivery.tenant_no == tenant_no,
|
||||
PlPlanDelivery.del_flag == 0,
|
||||
)
|
||||
)
|
||||
customer_not_internal = or_(
|
||||
PlPlan.customer_name.is_(None),
|
||||
PlPlan.customer_name == "",
|
||||
~PlPlan.customer_name.in_(internal_names),
|
||||
)
|
||||
return and_(
|
||||
~has_delivery,
|
||||
customer_not_internal,
|
||||
~_side_contract_exists(tenant_no, PLAN_CONTRACT_SIDE_DEMANDER),
|
||||
~_stop_contract_exists(
|
||||
tenant_no,
|
||||
PlPlan.id,
|
||||
PlPlan.id,
|
||||
(PLAN_CONTRACT_SIDE_DEMANDER,),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def plan_has_contract_gap_exists(tenant_no: str):
|
||||
"""列表筛选:计划存在合同缺口(非内置侧缺少有效 pl_plan_contract 关联)。"""
|
||||
return or_(_supplier_gap_expr(tenant_no), _demander_gap_expr(tenant_no))
|
||||
"""列表筛选:任一段次(或旧计划级)存在合同缺口。"""
|
||||
return or_(
|
||||
_load_stop_gap_expr(tenant_no),
|
||||
_delivery_stop_gap_expr(tenant_no),
|
||||
_legacy_supplier_gap_expr(tenant_no),
|
||||
_legacy_demander_gap_expr(tenant_no),
|
||||
)
|
||||
|
||||
|
||||
def _supplier_gap_expr(tenant_no: str):
|
||||
return or_(_load_stop_gap_expr(tenant_no), _legacy_supplier_gap_expr(tenant_no))
|
||||
|
||||
|
||||
def _demander_gap_expr(tenant_no: str):
|
||||
return or_(_delivery_stop_gap_expr(tenant_no), _legacy_demander_gap_expr(tenant_no))
|
||||
|
||||
|
||||
def build_plan_contract_gap_read(
|
||||
@@ -91,8 +240,13 @@ def build_plan_contract_gap_read(
|
||||
supplier_contracts: list[PlanContractLink],
|
||||
demander_contracts: list[PlanContractLink],
|
||||
products: Optional[list[PlanProductRead]] = None,
|
||||
load_read: Optional[PlanLoadRead] = None,
|
||||
delivery_reads: Optional[list[PlanDeliveryRead]] = None,
|
||||
) -> PlanContractGapRead:
|
||||
gap_sides = compute_contract_gap_sides(
|
||||
deliveries = list(delivery_reads or [])
|
||||
gap_sides = compute_plan_gap_sides_from_stops(
|
||||
load_read,
|
||||
deliveries,
|
||||
supplier_name=plan.supplier_name,
|
||||
customer_name=plan.customer_name,
|
||||
supplier_contract_count=len(supplier_contracts),
|
||||
@@ -114,12 +268,16 @@ def build_plan_contract_gap_read(
|
||||
supplierContracts=supplier_contracts,
|
||||
demanderContracts=demander_contracts,
|
||||
products=list(products or []),
|
||||
load=load_read,
|
||||
deliveries=deliveries,
|
||||
)
|
||||
|
||||
|
||||
def _load_products_by_plan_ids(
|
||||
db: Session,
|
||||
plan_ids: list[str],
|
||||
*,
|
||||
tenant_no: str,
|
||||
) -> dict[str, list[PlanProductRead]]:
|
||||
if not plan_ids:
|
||||
return {}
|
||||
@@ -132,9 +290,21 @@ def _load_products_by_plan_ids(
|
||||
.order_by(PlPlanProduct.order_num.asc(), PlPlanProduct.create_time.asc())
|
||||
.all()
|
||||
)
|
||||
product_ids = {(row.product_id or "").strip() for row in rows if (row.product_id or "").strip()}
|
||||
standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
|
||||
db, tenant_no=tenant_no, product_ids=product_ids
|
||||
)
|
||||
out: dict[str, list[PlanProductRead]] = {pid: [] for pid in plan_ids}
|
||||
for row in rows:
|
||||
out.setdefault(row.plan_id, []).append(PlanProductRead.model_validate(row))
|
||||
item = PlanProductRead.model_validate(row)
|
||||
display_name, _alias = resolve_product_display_names(
|
||||
saved_product_name=row.product_name,
|
||||
product_id=row.product_id,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
item.product_name = display_name or (row.product_name or "")
|
||||
out.setdefault(row.plan_id, []).append(item)
|
||||
return out
|
||||
|
||||
|
||||
@@ -179,10 +349,28 @@ def list_plan_contract_gaps(
|
||||
kw = customer_keyword.strip()
|
||||
if kw:
|
||||
kw_lower = kw.lower()
|
||||
load_match = exists(
|
||||
select(PlPlanLoad.id).where(
|
||||
PlPlanLoad.plan_id == PlPlan.id,
|
||||
PlPlanLoad.tenant_no == tenant_no,
|
||||
PlPlanLoad.del_flag == 0,
|
||||
func.lower(PlPlanLoad.customer_name).contains(kw_lower),
|
||||
)
|
||||
)
|
||||
delivery_match = exists(
|
||||
select(PlPlanDelivery.id).where(
|
||||
PlPlanDelivery.plan_id == PlPlan.id,
|
||||
PlPlanDelivery.tenant_no == tenant_no,
|
||||
PlPlanDelivery.del_flag == 0,
|
||||
func.lower(PlPlanDelivery.customer_name).contains(kw_lower),
|
||||
)
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
func.lower(PlPlan.supplier_name).contains(kw_lower),
|
||||
func.lower(PlPlan.customer_name).contains(kw_lower),
|
||||
load_match,
|
||||
delivery_match,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -196,11 +384,29 @@ def list_plan_contract_gaps(
|
||||
q_kw = q.strip()
|
||||
if q_kw:
|
||||
q_lower = q_kw.lower()
|
||||
load_match = exists(
|
||||
select(PlPlanLoad.id).where(
|
||||
PlPlanLoad.plan_id == PlPlan.id,
|
||||
PlPlanLoad.tenant_no == tenant_no,
|
||||
PlPlanLoad.del_flag == 0,
|
||||
func.lower(PlPlanLoad.customer_name).contains(q_lower),
|
||||
)
|
||||
)
|
||||
delivery_match = exists(
|
||||
select(PlPlanDelivery.id).where(
|
||||
PlPlanDelivery.plan_id == PlPlan.id,
|
||||
PlPlanDelivery.tenant_no == tenant_no,
|
||||
PlPlanDelivery.del_flag == 0,
|
||||
func.lower(PlPlanDelivery.customer_name).contains(q_lower),
|
||||
)
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
PlPlan.plan_no.contains(q_kw),
|
||||
func.lower(PlPlan.supplier_name).contains(q_lower),
|
||||
func.lower(PlPlan.customer_name).contains(q_lower),
|
||||
load_match,
|
||||
delivery_match,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -217,22 +423,200 @@ def list_plan_contract_gaps(
|
||||
|
||||
plan_ids = [plan.id for plan in plans]
|
||||
contracts_by_plan = load_plan_contracts_grouped(db, tenant_no, plan_ids)
|
||||
products_by_plan = _load_products_by_plan_ids(db, plan_ids)
|
||||
products_by_plan = _load_products_by_plan_ids(db, plan_ids, tenant_no=tenant_no)
|
||||
stops_by_plan = load_plan_stops_grouped(db, tenant_no, plan_ids)
|
||||
|
||||
items: list[PlanContractGapRead] = []
|
||||
for plan in plans:
|
||||
supplier_contracts, demander_contracts = contracts_by_plan.get(plan.id, ([], []))
|
||||
load_read, delivery_reads = stops_by_plan.get(plan.id, (None, []))
|
||||
items.append(
|
||||
build_plan_contract_gap_read(
|
||||
plan,
|
||||
supplier_contracts=supplier_contracts,
|
||||
demander_contracts=demander_contracts,
|
||||
products=products_by_plan.get(plan.id, []),
|
||||
load_read=load_read,
|
||||
delivery_reads=delivery_reads,
|
||||
)
|
||||
)
|
||||
return total, items
|
||||
|
||||
|
||||
def _write_stop_contract_rows(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan_id: str,
|
||||
stop_id: str,
|
||||
side: str,
|
||||
contracts: list[PlanContractLink],
|
||||
user_id: Optional[str],
|
||||
dept_id: Optional[str],
|
||||
) -> None:
|
||||
now = datetime.now()
|
||||
db.query(PlPlanContract).filter(
|
||||
PlPlanContract.plan_id == plan_id,
|
||||
PlPlanContract.tenant_no == tenant_no,
|
||||
PlPlanContract.del_flag == 0,
|
||||
PlPlanContract.stop_id == stop_id,
|
||||
).update(
|
||||
{"del_flag": 1, "update_by": user_id, "update_time": now},
|
||||
synchronize_session=False,
|
||||
)
|
||||
order_num = 0
|
||||
for link in contracts:
|
||||
order_num += 1
|
||||
db.add(
|
||||
PlPlanContract(
|
||||
id=generate_uuid(),
|
||||
plan_id=plan_id,
|
||||
side=side,
|
||||
stop_id=stop_id,
|
||||
contract_id=link.contract_id,
|
||||
contract_no=link.contract_no,
|
||||
tenant_no=tenant_no,
|
||||
order_num=order_num,
|
||||
create_by=user_id,
|
||||
create_dept_id=dept_id or "",
|
||||
create_time=now,
|
||||
update_by=user_id,
|
||||
update_time=now,
|
||||
del_flag=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _clear_legacy_side_contracts(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan_id: str,
|
||||
legacy_sides: tuple[str, ...],
|
||||
user_id: Optional[str],
|
||||
) -> None:
|
||||
now = datetime.now()
|
||||
db.query(PlPlanContract).filter(
|
||||
PlPlanContract.plan_id == plan_id,
|
||||
PlPlanContract.tenant_no == tenant_no,
|
||||
PlPlanContract.del_flag == 0,
|
||||
or_(PlPlanContract.stop_id.is_(None), PlPlanContract.stop_id == ""),
|
||||
PlPlanContract.side.in_(legacy_sides),
|
||||
).update(
|
||||
{"del_flag": 1, "update_by": user_id, "update_time": now},
|
||||
synchronize_session=False,
|
||||
)
|
||||
|
||||
|
||||
def update_plan_stop_contracts(
|
||||
db: Session,
|
||||
*,
|
||||
tenant_no: str,
|
||||
plan: PlPlan,
|
||||
stop_type: str,
|
||||
stop_id: str,
|
||||
contracts: list[PlanContractLink],
|
||||
user_id: Optional[str],
|
||||
dept_id: Optional[str],
|
||||
) -> PlanContractGapRead:
|
||||
"""保存某装货/送货段的合同关联。"""
|
||||
if plan.follow_status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="已作废的计划不能修改")
|
||||
|
||||
stop_type_norm = (stop_type or "").strip().lower()
|
||||
stop_id_norm = (stop_id or "").strip()
|
||||
if stop_type_norm not in ("load", "delivery") or not stop_id_norm:
|
||||
raise HTTPException(status_code=422, detail="stopType 必须为 load 或 delivery,且 stopId 不能为空")
|
||||
|
||||
if stop_type_norm == "load":
|
||||
stop = (
|
||||
db.query(PlPlanLoad)
|
||||
.filter(
|
||||
PlPlanLoad.id == stop_id_norm,
|
||||
PlPlanLoad.plan_id == plan.id,
|
||||
PlPlanLoad.tenant_no == tenant_no,
|
||||
PlPlanLoad.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
side = PLAN_CONTRACT_SIDE_LOAD
|
||||
legacy_sides = (PLAN_CONTRACT_SIDE_SUPPLIER,)
|
||||
side_label = "装货段合同"
|
||||
else:
|
||||
stop = (
|
||||
db.query(PlPlanDelivery)
|
||||
.filter(
|
||||
PlPlanDelivery.id == stop_id_norm,
|
||||
PlPlanDelivery.plan_id == plan.id,
|
||||
PlPlanDelivery.tenant_no == tenant_no,
|
||||
PlPlanDelivery.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
side = PLAN_CONTRACT_SIDE_DELIVERY
|
||||
legacy_sides = (PLAN_CONTRACT_SIDE_DEMANDER,)
|
||||
side_label = "送货段合同"
|
||||
|
||||
if not stop:
|
||||
raise HTTPException(status_code=404, detail="段次不存在")
|
||||
|
||||
if is_internal_customer_name(stop.customer_name):
|
||||
raise HTTPException(status_code=400, detail="内置客户无需补充合同")
|
||||
|
||||
links = _normalize_contract_links(contracts)
|
||||
expected_customer_id = stop.customer_id
|
||||
resolved: list[PlanContractLink] = []
|
||||
for link in links:
|
||||
contract = assert_contract_selectable_for_plan(
|
||||
db,
|
||||
link.contract_id,
|
||||
tenant_no,
|
||||
expected_customer_id=expected_customer_id,
|
||||
side_label=side_label,
|
||||
)
|
||||
resolved.append(
|
||||
PlanContractLink(
|
||||
contractId=contract.id,
|
||||
contractNo=contract.contract_no or link.contract_no,
|
||||
stopId=stop_id_norm,
|
||||
)
|
||||
)
|
||||
|
||||
_clear_legacy_side_contracts(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan_id=plan.id,
|
||||
legacy_sides=legacy_sides,
|
||||
user_id=user_id,
|
||||
)
|
||||
_write_stop_contract_rows(
|
||||
db,
|
||||
tenant_no=tenant_no,
|
||||
plan_id=plan.id,
|
||||
stop_id=stop_id_norm,
|
||||
side=side,
|
||||
contracts=resolved,
|
||||
user_id=user_id,
|
||||
dept_id=dept_id,
|
||||
)
|
||||
|
||||
supplier_contracts, demander_contracts = load_plan_contracts_grouped(
|
||||
db, tenant_no, [plan.id]
|
||||
).get(plan.id, ([], []))
|
||||
products = _load_products_by_plan_ids(db, [plan.id], tenant_no=tenant_no).get(plan.id, [])
|
||||
load_read, delivery_reads = load_plan_stops_grouped(db, tenant_no, [plan.id]).get(
|
||||
plan.id, (None, [])
|
||||
)
|
||||
return build_plan_contract_gap_read(
|
||||
plan,
|
||||
supplier_contracts=supplier_contracts,
|
||||
demander_contracts=demander_contracts,
|
||||
products=products,
|
||||
load_read=load_read,
|
||||
delivery_reads=delivery_reads,
|
||||
)
|
||||
|
||||
|
||||
def update_plan_side_contracts(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -243,7 +627,7 @@ def update_plan_side_contracts(
|
||||
user_id: Optional[str],
|
||||
dept_id: Optional[str],
|
||||
) -> PlanContractGapRead:
|
||||
"""单侧保存计划合同关联;允许空列表,不强制非内置侧必须有合同。"""
|
||||
"""单侧保存计划合同关联(旧计划级接口,兼容保留)。"""
|
||||
if plan.follow_status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="已作废的计划不能修改")
|
||||
if side not in (PLAN_CONTRACT_SIDE_SUPPLIER, PLAN_CONTRACT_SIDE_DEMANDER):
|
||||
@@ -288,10 +672,15 @@ def update_plan_side_contracts(
|
||||
supplier_contracts, demander_contracts = load_plan_contracts_grouped(
|
||||
db, tenant_no, [plan.id]
|
||||
).get(plan.id, ([], []))
|
||||
products = _load_products_by_plan_ids(db, [plan.id]).get(plan.id, [])
|
||||
products = _load_products_by_plan_ids(db, [plan.id], tenant_no=tenant_no).get(plan.id, [])
|
||||
load_read, delivery_reads = load_plan_stops_grouped(db, tenant_no, [plan.id]).get(
|
||||
plan.id, (None, [])
|
||||
)
|
||||
return build_plan_contract_gap_read(
|
||||
plan,
|
||||
supplier_contracts=supplier_contracts,
|
||||
demander_contracts=demander_contracts,
|
||||
products=products,
|
||||
load_read=load_read,
|
||||
delivery_reads=delivery_reads,
|
||||
)
|
||||
@@ -1435,6 +1435,7 @@ def apply_archive_product_quantities(
|
||||
"brandId": bq.brand_id or "",
|
||||
"brandName": bq.brand_name,
|
||||
"qty": bq.qty,
|
||||
**({"unitPrice": bq.unit_price} if bq.unit_price is not None else {}),
|
||||
}
|
||||
for bq in item.brand_qtys
|
||||
]
|
||||
@@ -1489,6 +1490,7 @@ def apply_archive_brand_qtys_only(
|
||||
"brandId": bq.brand_id or "",
|
||||
"brandName": bq.brand_name,
|
||||
"qty": bq.qty,
|
||||
**({"unitPrice": bq.unit_price} if bq.unit_price is not None else {}),
|
||||
}
|
||||
for bq in item.brand_qtys
|
||||
]
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.models.pl_models import (
|
||||
PlTransportAddress,
|
||||
)
|
||||
from app.schemas.pl.plan import (
|
||||
PlanArchiveBrandQtyItem,
|
||||
PlanContractLink,
|
||||
PlanDeliveryBody,
|
||||
PlanDeliveryRead,
|
||||
@@ -28,6 +29,7 @@ from app.schemas.pl.plan import (
|
||||
PlanStopProductBody,
|
||||
PlanStopProductRead,
|
||||
)
|
||||
from app.services.pl_brand_archive import load_brand_qtys_by_stop_product_ids
|
||||
from app.services.pl_internal_customer import is_internal_customer_name
|
||||
from app.services.pl_plan_stop_rules import resolve_stop_dibang_defaults, warn_qty_imbalance
|
||||
from app.services.pl_plan_service import (
|
||||
@@ -35,6 +37,7 @@ from app.services.pl_plan_service import (
|
||||
PLAN_CONTRACT_SIDE_SUPPLIER,
|
||||
assert_contract_selectable_for_plan,
|
||||
)
|
||||
from app.services.pl_product_display import load_crm_product_alias_maps, resolve_product_display_names
|
||||
|
||||
PLAN_CONTRACT_SIDE_LOAD = "load"
|
||||
PLAN_CONTRACT_SIDE_DELIVERY = "delivery"
|
||||
@@ -48,12 +51,86 @@ def _contract_link(row: PlPlanContract) -> PlanContractLink:
|
||||
)
|
||||
|
||||
|
||||
def _load_stop_product(row: PlPlanLoadProduct) -> PlanStopProductRead:
|
||||
return PlanStopProductRead.model_validate(row)
|
||||
def _attach_stop_brand_qtys(
|
||||
product: PlanStopProductRead,
|
||||
brand_qtys_by_stop: dict[str, list[dict]],
|
||||
) -> PlanStopProductRead:
|
||||
raw = brand_qtys_by_stop.get(product.id) or None
|
||||
if raw:
|
||||
product.brand_qtys = [PlanArchiveBrandQtyItem.model_validate(x) for x in raw]
|
||||
else:
|
||||
product.brand_qtys = None
|
||||
return product
|
||||
|
||||
|
||||
def _delivery_stop_product(row: PlPlanDeliveryProduct) -> PlanStopProductRead:
|
||||
return PlanStopProductRead.model_validate(row)
|
||||
def _resolve_stop_list_product_name(
|
||||
*,
|
||||
saved_product_name: Optional[str],
|
||||
product_id: Optional[str],
|
||||
standard_by_id: dict[str, str],
|
||||
alias_options_by_id: dict[str, list[str]],
|
||||
) -> str:
|
||||
"""列表展示用:优先 CRM 标准名,不展示别名。"""
|
||||
display_name, _alias = resolve_product_display_names(
|
||||
saved_product_name=saved_product_name,
|
||||
product_id=product_id,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
return display_name or (saved_product_name or "")
|
||||
|
||||
|
||||
def _apply_stop_list_product_name(
|
||||
product: PlanStopProductRead,
|
||||
*,
|
||||
standard_by_id: dict[str, str],
|
||||
alias_options_by_id: dict[str, list[str]],
|
||||
) -> PlanStopProductRead:
|
||||
product.product_name = _resolve_stop_list_product_name(
|
||||
saved_product_name=product.product_name,
|
||||
product_id=product.product_id,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
return product
|
||||
|
||||
|
||||
def _load_stop_product(
|
||||
row: PlPlanLoadProduct,
|
||||
brand_qtys_by_stop: dict[str, list[dict]] | None = None,
|
||||
*,
|
||||
standard_by_id: dict[str, str] | None = None,
|
||||
alias_options_by_id: dict[str, list[str]] | None = None,
|
||||
) -> PlanStopProductRead:
|
||||
product = PlanStopProductRead.model_validate(row)
|
||||
if standard_by_id is not None and alias_options_by_id is not None:
|
||||
product = _apply_stop_list_product_name(
|
||||
product,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
if brand_qtys_by_stop is not None:
|
||||
return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
|
||||
return product
|
||||
|
||||
|
||||
def _delivery_stop_product(
|
||||
row: PlPlanDeliveryProduct,
|
||||
brand_qtys_by_stop: dict[str, list[dict]] | None = None,
|
||||
*,
|
||||
standard_by_id: dict[str, str] | None = None,
|
||||
alias_options_by_id: dict[str, list[str]] | None = None,
|
||||
) -> PlanStopProductRead:
|
||||
product = PlanStopProductRead.model_validate(row)
|
||||
if standard_by_id is not None and alias_options_by_id is not None:
|
||||
product = _apply_stop_list_product_name(
|
||||
product,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
if brand_qtys_by_stop is not None:
|
||||
return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
|
||||
return product
|
||||
|
||||
|
||||
def load_stop_contract_rows_grouped(
|
||||
@@ -228,6 +305,27 @@ def load_plan_stops_grouped(
|
||||
):
|
||||
delivery_products[row.delivery_id].append(row)
|
||||
|
||||
stop_product_ids: list[str] = []
|
||||
crm_product_ids: set[str] = set()
|
||||
for rows in load_products.values():
|
||||
for p in rows:
|
||||
if p.id:
|
||||
stop_product_ids.append(p.id)
|
||||
if (p.product_id or "").strip():
|
||||
crm_product_ids.add(p.product_id.strip())
|
||||
for rows in delivery_products.values():
|
||||
for p in rows:
|
||||
if p.id:
|
||||
stop_product_ids.append(p.id)
|
||||
if (p.product_id or "").strip():
|
||||
crm_product_ids.add(p.product_id.strip())
|
||||
brand_qtys_by_stop = load_brand_qtys_by_stop_product_ids(
|
||||
db, tenant_no=tenant_no, stop_product_ids=stop_product_ids
|
||||
)
|
||||
standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
|
||||
db, tenant_no=tenant_no, product_ids=crm_product_ids
|
||||
)
|
||||
|
||||
contracts_by_plan = load_stop_contract_rows_grouped(db, tenant_no, plan_ids)
|
||||
|
||||
result: dict[str, tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]]] = {}
|
||||
@@ -246,7 +344,15 @@ def load_plan_stops_grouped(
|
||||
)
|
||||
if resolved_load_address:
|
||||
load_read.address = resolved_load_address
|
||||
load_read.products = [_load_stop_product(p) for p in load_products.get(load_row.id, [])]
|
||||
load_read.products = [
|
||||
_load_stop_product(
|
||||
p,
|
||||
brand_qtys_by_stop,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
for p in load_products.get(load_row.id, [])
|
||||
]
|
||||
load_read.contracts = _contracts_for_stop(
|
||||
contract_rows,
|
||||
load_row.id,
|
||||
@@ -267,7 +373,13 @@ def load_plan_stops_grouped(
|
||||
if resolved_delivery_address:
|
||||
delivery_read.address = resolved_delivery_address
|
||||
delivery_read.products = [
|
||||
_delivery_stop_product(p) for p in delivery_products.get(delivery_row.id, [])
|
||||
_delivery_stop_product(
|
||||
p,
|
||||
brand_qtys_by_stop,
|
||||
standard_by_id=standard_by_id,
|
||||
alias_options_by_id=alias_options_by_id,
|
||||
)
|
||||
for p in delivery_products.get(delivery_row.id, [])
|
||||
]
|
||||
legacy_sides = (PLAN_CONTRACT_SIDE_DELIVERY, PLAN_CONTRACT_SIDE_DEMANDER)
|
||||
# 未迁移合同仅挂到第一个送货段
|
||||
|
||||
Reference in new issue
Block a user