|
@@ -17,6 +17,8 @@ from app.schemas.settlement import (
|
|
|
SettlementPayoutItem,
|
|
SettlementPayoutItem,
|
|
|
SettlementOrderDetailOut,
|
|
SettlementOrderDetailOut,
|
|
|
)
|
|
)
|
|
|
|
|
+from app.models.payment import VasPayment
|
|
|
|
|
+from app.services.payment_service import PaymentService, convert_currency
|
|
|
from app.services.cost_service import CostService
|
|
from app.services.cost_service import CostService
|
|
|
from app.core.biz_exception import BizLogicError, NotFoundError
|
|
from app.core.biz_exception import BizLogicError, NotFoundError
|
|
|
from app.utils.pagination import paginate
|
|
from app.utils.pagination import paginate
|
|
@@ -61,11 +63,51 @@ class SettlementService:
|
|
|
orders = await SettlementService._query_eligible_orders(db, req.start_date, req.end_date)
|
|
orders = await SettlementService._query_eligible_orders(db, req.start_date, req.end_date)
|
|
|
costs_summary = await CostService.get_costs_summary_by_date(db, req.start_date, req.end_date)
|
|
costs_summary = await CostService.get_costs_summary_by_date(db, req.start_date, req.end_date)
|
|
|
|
|
|
|
|
- total_revenue = sum(o.final_amount for o in orders)
|
|
|
|
|
- total_cost = sum(costs_summary.values())
|
|
|
|
|
|
|
+ # 加载订单成功支付记录,按实际流水币种统计(是欧元就是欧元,是rmb就是rmb,不强制折算汇率)
|
|
|
|
|
+ order_ids = [o.id for o in orders]
|
|
|
|
|
+ payments_by_order: Dict[str, List[VasPayment]] = {}
|
|
|
|
|
+ if order_ids:
|
|
|
|
|
+ p_stmt = select(VasPayment).where(
|
|
|
|
|
+ VasPayment.order_id.in_(order_ids),
|
|
|
|
|
+ VasPayment.status.in_(["succeeded", "paid"]),
|
|
|
|
|
+ )
|
|
|
|
|
+ p_res = await db.execute(p_stmt)
|
|
|
|
|
+ for p in p_res.scalars().all():
|
|
|
|
|
+ payments_by_order.setdefault(p.order_id, []).append(p)
|
|
|
|
|
+
|
|
|
|
|
+ def resolve_order_payment(o: VasOrder) -> tuple[int, str]:
|
|
|
|
|
+ """
|
|
|
|
|
+ 按实际支付流水统计订单实收与币种
|
|
|
|
|
+ 返回: (amount, currency)
|
|
|
|
|
+ """
|
|
|
|
|
+ pays = payments_by_order.get(o.id, [])
|
|
|
|
|
+ if pays:
|
|
|
|
|
+ pay_cur = pays[0].currency or o.base_currency or "CNY"
|
|
|
|
|
+ total_amt = sum(p.amount for p in pays if p.currency == pay_cur)
|
|
|
|
|
+ if total_amt == 0:
|
|
|
|
|
+ total_amt = pays[0].amount
|
|
|
|
|
+ return total_amt, pay_cur
|
|
|
|
|
+ else:
|
|
|
|
|
+ return o.final_amount, (o.base_currency or "CNY")
|
|
|
|
|
+
|
|
|
|
|
+ revenue_by_currency: Dict[str, int] = {}
|
|
|
|
|
+ for o in orders:
|
|
|
|
|
+ amt, cur = resolve_order_payment(o)
|
|
|
|
|
+ revenue_by_currency[cur] = revenue_by_currency.get(cur, 0) + amt
|
|
|
|
|
+
|
|
|
total_orders = len(orders)
|
|
total_orders = len(orders)
|
|
|
- avg_cost = (total_cost // total_orders) if total_orders > 0 else 0
|
|
|
|
|
- net_profit = total_revenue - total_cost
|
|
|
|
|
|
|
+ total_cost = sum(costs_summary.values())
|
|
|
|
|
+ cny_orders_count = sum(1 for o in orders if resolve_order_payment(o)[1] == "CNY")
|
|
|
|
|
+ avg_cost_cny = (total_cost // cny_orders_count) if cny_orders_count > 0 else 0
|
|
|
|
|
+ total_revenue_cny = revenue_by_currency.get("CNY", 0)
|
|
|
|
|
+ net_profit_cny = max(0, total_revenue_cny - total_cost)
|
|
|
|
|
+
|
|
|
|
|
+ profit_by_currency: Dict[str, int] = {}
|
|
|
|
|
+ for cur, amt in revenue_by_currency.items():
|
|
|
|
|
+ if cur == "CNY":
|
|
|
|
|
+ profit_by_currency[cur] = net_profit_cny
|
|
|
|
|
+ else:
|
|
|
|
|
+ profit_by_currency[cur] = amt
|
|
|
|
|
|
|
|
# 加载所有系统用户,用于真实自然人账号对账与显示
|
|
# 加载所有系统用户,用于真实自然人账号对账与显示
|
|
|
u_stmt = select(VasUser)
|
|
u_stmt = select(VasUser)
|
|
@@ -159,16 +201,18 @@ class SettlementService:
|
|
|
f"Developer ID '{dev_candidate}' configured for plugin '{pl.name}' on product '{prod.title}' does not exist in system users table."
|
|
f"Developer ID '{dev_candidate}' configured for plugin '{pl.name}' on product '{prod.title}' does not exist in system users table."
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
- # 临时聚合各人的毛利润
|
|
|
|
|
- user_gross_map: Dict[str, Dict[str, int]] = {
|
|
|
|
|
- partner_a: {"pool": 0, "sales": 0, "tech": 0},
|
|
|
|
|
- partner_b: {"pool": 0, "sales": 0, "tech": 0},
|
|
|
|
|
|
|
+ # 临时聚合各人按币种的毛利润
|
|
|
|
|
+ user_gross_map: Dict[str, Dict[str, Dict[str, int]]] = {
|
|
|
|
|
+ partner_a: {},
|
|
|
|
|
+ partner_b: {},
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
order_details: List[SettlementOrderDetailOut] = []
|
|
order_details: List[SettlementOrderDetailOut] = []
|
|
|
|
|
|
|
|
for o in orders:
|
|
for o in orders:
|
|
|
- order_profit = o.final_amount - avg_cost
|
|
|
|
|
|
|
+ order_amt, order_cur = resolve_order_payment(o)
|
|
|
|
|
+ order_cost = avg_cost_cny if order_cur == "CNY" else 0
|
|
|
|
|
+ order_profit = max(0, order_amt - order_cost)
|
|
|
dev_id = resolve_order_developer(o)
|
|
dev_id = resolve_order_developer(o)
|
|
|
dev_user = users_map.get(dev_id)
|
|
dev_user = users_map.get(dev_id)
|
|
|
dev_name = dev_user.nickname if (dev_user and dev_user.nickname) else dev_id
|
|
dev_name = dev_user.nickname if (dev_user and dev_user.nickname) else dev_id
|
|
@@ -186,8 +230,11 @@ class SettlementService:
|
|
|
handler_name=h_name,
|
|
handler_name=h_name,
|
|
|
developer_id=dev_id,
|
|
developer_id=dev_id,
|
|
|
developer_name=dev_name,
|
|
developer_name=dev_name,
|
|
|
- order_amount=o.final_amount,
|
|
|
|
|
- avg_cost=avg_cost,
|
|
|
|
|
|
|
+ order_amount=order_amt,
|
|
|
|
|
+ currency=order_cur,
|
|
|
|
|
+ original_amount=o.final_amount,
|
|
|
|
|
+ original_currency=o.base_currency or order_cur,
|
|
|
|
|
+ avg_cost=order_cost,
|
|
|
net_profit=order_profit,
|
|
net_profit=order_profit,
|
|
|
tech_fee=0,
|
|
tech_fee=0,
|
|
|
sales_fee=0,
|
|
sales_fee=0,
|
|
@@ -198,30 +245,37 @@ class SettlementService:
|
|
|
continue
|
|
continue
|
|
|
|
|
|
|
|
tech_fee = int(order_profit * 0.20)
|
|
tech_fee = int(order_profit * 0.20)
|
|
|
- sales_fee = int(order_profit * 0.40)
|
|
|
|
|
- pool_fee = order_profit - tech_fee - sales_fee
|
|
|
|
|
|
|
+ sales_fee_total = int(order_profit * 0.40)
|
|
|
|
|
+ pool_fee = order_profit - tech_fee - sales_fee_total
|
|
|
|
|
|
|
|
part_a = pool_fee // 2
|
|
part_a = pool_fee // 2
|
|
|
part_b = pool_fee // 2
|
|
part_b = pool_fee // 2
|
|
|
|
|
|
|
|
if dev_id not in user_gross_map:
|
|
if dev_id not in user_gross_map:
|
|
|
- user_gross_map[dev_id] = {"pool": 0, "sales": 0, "tech": 0}
|
|
|
|
|
- user_gross_map[dev_id]["tech"] += tech_fee
|
|
|
|
|
|
|
+ user_gross_map[dev_id] = {}
|
|
|
|
|
+ user_gross_map[dev_id].setdefault(order_cur, {"pool": 0, "sales": 0, "tech": 0})
|
|
|
|
|
+ user_gross_map[dev_id][order_cur]["tech"] += tech_fee
|
|
|
|
|
|
|
|
# 销售提成归属逻辑
|
|
# 销售提成归属逻辑
|
|
|
if o.handler_id:
|
|
if o.handler_id:
|
|
|
# 社交自收直客单 / 中介单:归该对接人个人
|
|
# 社交自收直客单 / 中介单:归该对接人个人
|
|
|
h_id = o.handler_id
|
|
h_id = o.handler_id
|
|
|
if h_id not in user_gross_map:
|
|
if h_id not in user_gross_map:
|
|
|
- user_gross_map[h_id] = {"pool": 0, "sales": 0, "tech": 0}
|
|
|
|
|
- user_gross_map[h_id]["sales"] += sales_fee
|
|
|
|
|
|
|
+ user_gross_map[h_id] = {}
|
|
|
|
|
+ user_gross_map[h_id].setdefault(order_cur, {"pool": 0, "sales": 0, "tech": 0})
|
|
|
|
|
+ user_gross_map[h_id][order_cur]["sales"] += sales_fee_total
|
|
|
|
|
+ displayed_sales_fee = sales_fee_total
|
|
|
else:
|
|
else:
|
|
|
- # 官网公海单:甲乙平分 40% 销售提成
|
|
|
|
|
- part_a += sales_fee // 2
|
|
|
|
|
- part_b += sales_fee // 2
|
|
|
|
|
|
|
+ # 官网公海单:如果没有设定对接人,就是甲方乙方平分40%销售提成
|
|
|
|
|
+ part_a += sales_fee_total // 2
|
|
|
|
|
+ part_b += sales_fee_total // 2
|
|
|
|
|
+ displayed_sales_fee = 0 # 对接人提成为0,提成已直接平分计入甲方与乙方
|
|
|
|
|
|
|
|
- user_gross_map[partner_a]["pool"] += part_a
|
|
|
|
|
- user_gross_map[partner_b]["pool"] += part_b
|
|
|
|
|
|
|
+ user_gross_map[partner_a].setdefault(order_cur, {"pool": 0, "sales": 0, "tech": 0})
|
|
|
|
|
+ user_gross_map[partner_a][order_cur]["pool"] += part_a
|
|
|
|
|
+
|
|
|
|
|
+ user_gross_map[partner_b].setdefault(order_cur, {"pool": 0, "sales": 0, "tech": 0})
|
|
|
|
|
+ user_gross_map[partner_b][order_cur]["pool"] += part_b
|
|
|
|
|
|
|
|
order_details.append(SettlementOrderDetailOut(
|
|
order_details.append(SettlementOrderDetailOut(
|
|
|
order_id=o.id,
|
|
order_id=o.id,
|
|
@@ -231,58 +285,71 @@ class SettlementService:
|
|
|
handler_name=h_name,
|
|
handler_name=h_name,
|
|
|
developer_id=dev_id,
|
|
developer_id=dev_id,
|
|
|
developer_name=dev_name,
|
|
developer_name=dev_name,
|
|
|
- order_amount=o.final_amount,
|
|
|
|
|
- avg_cost=avg_cost,
|
|
|
|
|
|
|
+ order_amount=order_amt,
|
|
|
|
|
+ currency=order_cur,
|
|
|
|
|
+ original_amount=o.final_amount,
|
|
|
|
|
+ original_currency=o.base_currency or order_cur,
|
|
|
|
|
+ avg_cost=order_cost,
|
|
|
net_profit=order_profit,
|
|
net_profit=order_profit,
|
|
|
tech_fee=tech_fee,
|
|
tech_fee=tech_fee,
|
|
|
- sales_fee=sales_fee,
|
|
|
|
|
|
|
+ sales_fee=displayed_sales_fee,
|
|
|
pool_fee=pool_fee,
|
|
pool_fee=pool_fee,
|
|
|
partner_a_amount=part_a,
|
|
partner_a_amount=part_a,
|
|
|
partner_b_amount=part_b,
|
|
partner_b_amount=part_b,
|
|
|
))
|
|
))
|
|
|
|
|
|
|
|
- # 查询未核销的个人过错罚单,并从提成中扣除
|
|
|
|
|
|
|
+ # 查询未核销的个人过错罚单,并从提成中扣除(按币种生成对账条目)
|
|
|
payout_summary: List[SettlementPayoutItem] = []
|
|
payout_summary: List[SettlementPayoutItem] = []
|
|
|
- for uid, breakdown in user_gross_map.items():
|
|
|
|
|
- total_user_gross = breakdown["pool"] + breakdown["sales"] + breakdown["tech"]
|
|
|
|
|
- if total_user_gross == 0:
|
|
|
|
|
- continue
|
|
|
|
|
-
|
|
|
|
|
- # 查询该用户待扣罚单
|
|
|
|
|
|
|
+ user_fault_penalty: Dict[str, int] = {}
|
|
|
|
|
+ for uid in user_gross_map.keys():
|
|
|
fault_stmt = select(func.coalesce(func.sum(VasFaultCompensation.penalty_amount), 0)).where(
|
|
fault_stmt = select(func.coalesce(func.sum(VasFaultCompensation.penalty_amount), 0)).where(
|
|
|
VasFaultCompensation.liable_user_id == uid,
|
|
VasFaultCompensation.liable_user_id == uid,
|
|
|
VasFaultCompensation.deducted_status == 0
|
|
VasFaultCompensation.deducted_status == 0
|
|
|
)
|
|
)
|
|
|
- fault_penalty = int((await db.execute(fault_stmt)).scalar() or 0)
|
|
|
|
|
-
|
|
|
|
|
- roles = []
|
|
|
|
|
- if breakdown["pool"] > 0:
|
|
|
|
|
- roles.append(f"合伙分红:{breakdown['pool']/100:.2f}元")
|
|
|
|
|
- if breakdown["sales"] > 0:
|
|
|
|
|
- roles.append(f"销售提成:{breakdown['sales']/100:.2f}元")
|
|
|
|
|
- if breakdown["tech"] > 0:
|
|
|
|
|
- roles.append(f"技术版权:{breakdown['tech']/100:.2f}元")
|
|
|
|
|
|
|
+ user_fault_penalty[uid] = int((await db.execute(fault_stmt)).scalar() or 0)
|
|
|
|
|
|
|
|
|
|
+ for uid, currencies_map in user_gross_map.items():
|
|
|
user_obj = users_map.get(uid)
|
|
user_obj = users_map.get(uid)
|
|
|
user_display_name = user_obj.nickname if (user_obj and user_obj.nickname) else uid
|
|
user_display_name = user_obj.nickname if (user_obj and user_obj.nickname) else uid
|
|
|
|
|
|
|
|
- net_payout = max(0, total_user_gross - fault_penalty)
|
|
|
|
|
- payout_summary.append(SettlementPayoutItem(
|
|
|
|
|
- user_id=uid,
|
|
|
|
|
- user_name=user_display_name,
|
|
|
|
|
- role_description=" | ".join(roles),
|
|
|
|
|
- gross_amount=total_user_gross,
|
|
|
|
|
- fault_penalty=fault_penalty,
|
|
|
|
|
- net_payout=net_payout,
|
|
|
|
|
- ))
|
|
|
|
|
|
|
+ for cur, breakdown in currencies_map.items():
|
|
|
|
|
+ total_user_gross = breakdown["pool"] + breakdown["sales"] + breakdown["tech"]
|
|
|
|
|
+ if total_user_gross == 0:
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ fault_penalty = 0
|
|
|
|
|
+ if cur == "CNY":
|
|
|
|
|
+ fault_penalty = user_fault_penalty.get(uid, 0)
|
|
|
|
|
+
|
|
|
|
|
+ sym = "¥" if cur == "CNY" else "€" if cur == "EUR" else "$" if cur == "USD" else cur
|
|
|
|
|
+ roles = []
|
|
|
|
|
+ if breakdown["pool"] > 0:
|
|
|
|
|
+ roles.append(f"合伙分红:{sym}{breakdown['pool']/100:.2f}")
|
|
|
|
|
+ if breakdown["sales"] > 0:
|
|
|
|
|
+ roles.append(f"销售提成:{sym}{breakdown['sales']/100:.2f}")
|
|
|
|
|
+ if breakdown["tech"] > 0:
|
|
|
|
|
+ roles.append(f"技术版权:{sym}{breakdown['tech']/100:.2f}")
|
|
|
|
|
+
|
|
|
|
|
+ net_payout = max(0, total_user_gross - fault_penalty)
|
|
|
|
|
+ payout_summary.append(SettlementPayoutItem(
|
|
|
|
|
+ user_id=uid,
|
|
|
|
|
+ user_name=user_display_name,
|
|
|
|
|
+ role_description=f"[{cur}] " + " | ".join(roles),
|
|
|
|
|
+ gross_amount=total_user_gross,
|
|
|
|
|
+ fault_penalty=fault_penalty,
|
|
|
|
|
+ net_payout=net_payout,
|
|
|
|
|
+ currency=cur,
|
|
|
|
|
+ ))
|
|
|
|
|
|
|
|
return SettlementPreviewResponse(
|
|
return SettlementPreviewResponse(
|
|
|
period_range=f"{req.start_date.strftime('%Y-%m-%d')} ~ {req.end_date.strftime('%Y-%m-%d')}",
|
|
period_range=f"{req.start_date.strftime('%Y-%m-%d')} ~ {req.end_date.strftime('%Y-%m-%d')}",
|
|
|
total_orders=total_orders,
|
|
total_orders=total_orders,
|
|
|
- total_revenue=total_revenue,
|
|
|
|
|
|
|
+ total_revenue=total_revenue_cny,
|
|
|
total_cost=total_cost,
|
|
total_cost=total_cost,
|
|
|
- avg_cost=avg_cost,
|
|
|
|
|
- net_profit=net_profit,
|
|
|
|
|
|
|
+ avg_cost=avg_cost_cny,
|
|
|
|
|
+ net_profit=net_profit_cny,
|
|
|
|
|
+ revenue_by_currency=revenue_by_currency,
|
|
|
|
|
+ profit_by_currency=profit_by_currency,
|
|
|
payout_summary=payout_summary,
|
|
payout_summary=payout_summary,
|
|
|
cost_breakdown=costs_summary,
|
|
cost_breakdown=costs_summary,
|
|
|
details=order_details,
|
|
details=order_details,
|