修复财务接口:统一date字段查询,板子全平台合计

This commit is contained in:
XingQue
2026-06-24 22:08:40 +08:00
parent 79f2d4f020
commit 8e5db24bad
5 changed files with 329 additions and 335 deletions

View File

@@ -38,7 +38,7 @@ from backend.utils import (
update_dashou_daily_by_action,
update_shangjia_daily
)
from jituan.services.club_context import filter_queryset_by_club, filter_user_related_by_club, filter_user_qs_by_club, orders_for_request
from jituan.services.club_context import filter_club_char_field, filter_queryset_by_club, filter_user_related_by_club, filter_user_qs_by_club, orders_for_request
from jituan.services.club_penalty import (
filter_penalty_qs, resolve_penalty_club_id, filter_gsfenhong_qs,
forbid_penalty_out_of_scope, resolve_penalty_record_club_id,
@@ -6939,7 +6939,7 @@ class CaiwuView(APIView):
today_start = datetime.combine(today, datetime.min.time())
today_end = today_start + timedelta(days=1)
# 今日收入 / 支出(全平台各俱乐部合计,只读 daily_income_stat / daily_payout_stat
# 四个板子 + 累计:全平台 daily_income_stat / daily_payout_stat 按 date 汇总(不按俱乐部缩范围
today_inc = DailyIncomeStat.query.filter(date=today).aggregate(
total_amount=Sum('total_amount'),
total_count=Sum('total_count'),
@@ -7016,12 +7016,12 @@ class CaiwuView(APIView):
all_zuzhang_yue = float(UserZuzhang.query.aggregate(total=Sum('ketixian_jine'))['total'] or 0.00)
all_shangjia_yue = float(UserShangjia.query.aggregate(total=Sum('yue'))['total'] or 0.00)
# 平台总收支及利润(只读日统计表)
# 累计收支 / 利润:日统计表全平台各行相加
total_income = float(DailyIncomeStat.query.aggregate(total=Sum('total_amount'))['total'] or 0.00)
total_payout = float(DailyPayoutStat.query.aggregate(total=Sum('total_amount'))['total'] or 0.00)
platform_profit = round(total_income - total_payout, 2)
# 近30天每日收支明细按日期合并各俱乐部
# 近30天每日收支明细全平台
daily_stats = []
since = today - timedelta(days=30)
income_by_date = {
@@ -7340,19 +7340,14 @@ class SzxxView(APIView):
"""
每日收支详细统计数据
POST /houtai/szxx
Body: {
"phone": "管理员手机号",
"granularity": "day" | "month" | "year",
"year": 2026, // day/month 时必填
"month": 5, // day 时必填
"summary_date": "2026-05-16" // 可选,格式随颗粒度
}
只读 daily_income_stat / daily_payout_stat按 date 字段汇总。
"""
permission_classes = [IsAuthenticated]
def post(self, request):
try:
# 避免模块名冲突,局部导入
from jituan.services.szxx_stats import build_szxx_payload
username_from_frontend = request.data.get('phone', None)
kefu_obj, permissions = verify_kefu_permission(request, username_from_frontend)
if kefu_obj is None:
@@ -7366,127 +7361,11 @@ class SzxxView(APIView):
month = request.data.get('month')
summary_date = request.data.get('summary_date')
now = date.today()
data, err = build_szxx_payload(request, granularity, year, month, summary_date)
if err:
return Response({'code': 1, 'msg': err}, status=400)
# ---------- 时间范围与分组字段 ----------
if granularity == 'day':
if not year or not month:
return Response({'code': 1, 'msg': '按日统计需要年份和月份'}, status=400)
# 分组字段
group_field = 'day'
# 过滤条件
income_filter = {'year': year, 'month': month}
payout_filter = {'year': year, 'month': month}
# 默认汇总日期
if not summary_date:
summary_date = now.strftime('%Y-%m-%d')
summary_parts = summary_date.split('-')
summary_filter = {'year': int(summary_parts[0]), 'month': int(summary_parts[1]), 'day': int(summary_parts[2])}
# 用于构造返回的日期字符串
date_format = '%Y-%m-%d'
elif granularity == 'month':
if not year:
return Response({'code': 1, 'msg': '按月统计需要年份'}, status=400)
group_field = 'month'
income_filter = {'year': year}
payout_filter = {'year': year}
if not summary_date:
summary_date = now.strftime('%Y-%m')
summary_parts = summary_date.split('-')
summary_filter = {'year': int(summary_parts[0]), 'month': int(summary_parts[1])}
date_format = '%Y-%m'
elif granularity == 'year':
group_field = 'year'
income_filter = {}
payout_filter = {}
if not summary_date:
summary_date = str(now.year)
summary_filter = {'year': int(summary_date)}
date_format = '%Y'
else:
return Response({'code': 1, 'msg': '无效的颗粒度'}, status=400)
# ---------- 收入分组查询daily_income_stat----------
income_qs = filter_queryset_by_club(
DailyIncomeStat.query.filter(**income_filter), request,
).values(group_field) \
.annotate(total_income=Sum('total_amount'), total_count=Sum('total_count')) \
.order_by(group_field)
# ---------- 支出分组查询daily_payout_stat----------
payout_qs = filter_queryset_by_club(
DailyPayoutStat.query.filter(**payout_filter), request,
).values(group_field) \
.annotate(total_payout=Sum('total_amount'), total_count=Sum('total_count')) \
.order_by(group_field)
# ---------- 合并数据 ----------
data_map = {}
for item in income_qs:
key = item[group_field]
data_map[key] = {
'income': float(item['total_income'] or 0),
'income_count': item['total_count'] or 0,
'payout': 0.0,
'payout_count': 0
}
for item in payout_qs:
key = item[group_field]
if key not in data_map:
data_map[key] = {'income': 0.0, 'income_count': 0, 'payout': 0.0, 'payout_count': 0}
data_map[key]['payout'] = float(item['total_payout'] or 0)
data_map[key]['payout_count'] = item['total_count'] or 0
time_series = []
for key, vals in data_map.items():
# 构造日期字符串
if granularity == 'day':
date_str = f"{year}-{month:02d}-{key:02d}"
elif granularity == 'month':
date_str = f"{year}-{key:02d}"
else:
date_str = str(key)
profit = round(vals['income'] - vals['payout'], 2)
time_series.append({
'date': date_str,
'income': vals['income'],
'payout': vals['payout'],
'profit': profit
})
time_series.sort(key=lambda x: x['date'])
# ---------- 汇总数据 ----------
income_summary = filter_queryset_by_club(
DailyIncomeStat.query.filter(**summary_filter), request,
).aggregate(
total_income=Sum('total_amount'), total_count=Sum('total_count')
)
payout_summary = filter_queryset_by_club(
DailyPayoutStat.query.filter(**summary_filter), request,
).aggregate(
total_payout=Sum('total_amount'), total_count=Sum('total_count')
)
total_income = float(income_summary['total_income'] or 0)
total_payout = float(payout_summary['total_payout'] or 0)
total_profit = round(total_income - total_payout, 2)
return Response({
'code': 0,
'msg': 'ok',
'data': {
'time_series': time_series,
'summary': {
'total_income': total_income,
'total_income_count': income_summary['total_count'] or 0,
'total_payout': total_payout,
'total_payout_count': payout_summary['total_count'] or 0,
'total_profit': total_profit
}
}
})
return Response({'code': 0, 'msg': 'ok', 'data': data})
except Exception as e:
logger.exception("SzxxView 接口错误")

View File

@@ -1,64 +1,68 @@
"""
一键恢复财务「每日收入」统计repair_wechat_income 搞乱后执行)
恢复 daily_income_stat每日收入统计表全表数据
只重建
- daily_income_stat(每日收入统计表,财务看板读这个)
- platform_income_log支付幂等日志
repair_wechat_income 对该表的破坏
- 把扫描到的每笔订单/充值重复写入 daily_income_stat
- 金额记到「执行命令那天」,不是真实支付日
- 含退款单(Status=5)也被当成收入加进去
绝不碰:
- daily_payout_stat每日支出repair 没动过)
- szjilu收支记录表已废弃
- 订单 / 充值业务表
本命令按 platform_income_log + 无日志的已支付单,重建整张 daily_income_stat。
不碰 daily_payout_stat,不碰 szjilu不删订单。
用法:
预览python manage.py restore_finance_stats
执行python manage.py restore_finance_stats --yes
"""
from datetime import date
from django.core.management.base import BaseCommand
from django.db.models import Sum
from jituan.services.szjilu_accounting import restore_finance_daily_stats
from config.models import DailyIncomeStat, DailyPayoutStat
from jituan.services.szjilu_accounting import rebuild_daily_income_stat_table
class Command(BaseCommand):
help = '从订单/充值重建 daily_income_stat(恢复 repair 搞乱的每日收入'
help = '恢复 daily_income_stat 全表(财务四个板子读这张表'
def add_arguments(self, parser):
parser.add_argument('--since-year', type=int, default=2020, help='从哪年开始重算')
parser.add_argument('--until-year', type=int, default=0, help='到哪年,默认今年')
parser.add_argument('--yes', action='store_true', help='确认写入数据库')
def handle(self, *args, **options):
until_year = options['until_year'] or date.today().year
since_year = options['since_year'] or 2020
dry_run = not options['yes']
if dry_run:
self.stdout.write(self.style.WARNING(
'【预览】未改数据库。下面「恢复后」应是正确每日收入合计。\n'
))
self.stdout.write(self.style.WARNING('【预览】未改数据库\n'))
else:
self.stdout.write(self.style.WARNING(
'【执行】正在从订单/充值重建 daily_income_stat...\n'
))
self.stdout.write(self.style.WARNING('【执行】重建 daily_income_stat...\n'))
r = restore_finance_daily_stats(since_year, until_year, dry_run=dry_run)
r = rebuild_daily_income_stat_table(dry_run=dry_run)
self.stdout.write(f'范围: {r["since_year"]} ~ {r["until_year"]}')
self.stdout.write(f' 支付笔数: {r["after_count"]}')
self.stdout.write(f' 支付笔数(去重): {r["payment_rows"]}')
self.stdout.write(f' 其中日志: {r["from_log"]}')
self.stdout.write(f' 补漏订单: {r["gap_orders"]}')
self.stdout.write(f' 补漏充值: {r["gap_cz"]}')
self.stdout.write(f' 日统计行数: {r["daily_rows"]}')
self.stdout.write(f' 恢复前 daily 合计: {r["before_daily_total"]:.2f}')
self.stdout.write(self.style.SUCCESS(
f' 恢复后 daily 合计: {r.get("after_daily_total", r["after_total"]):.2f}'
f' 恢复后 daily 合计: {r["after_daily_total"]:.2f}'
))
self.stdout.write(f' 其中今日收入: {r["today_amount"]:.2f} 元 / {r["today_count"]}')
payout_today = DailyPayoutStat.objects.filter(date=date.today()).aggregate(
t=Sum('total_amount'),
)['t'] or 0
self.stdout.write(
f' (未动)今日支出表: {float(payout_today):.2f}'
)
if dry_run:
self.stdout.write(self.style.WARNING(
'\n数字对的话执行:\n'
' python manage.py restore_finance_stats --yes'
'\n预览数字合理后执行:\n'
' python manage.py restore_finance_stats --yes\n'
'然后 push 代码并刷新财务页。'
))
else:
check = DailyIncomeStat.objects.aggregate(t=Sum('total_amount'))['t'] or 0
self.stdout.write(self.style.SUCCESS(
'\n完成。daily_payout_stat 未动。请 push 代码后刷新财务页。'
f'\n完成。数据库 daily_income_stat 合计: {float(check):.2f}'
))

View File

@@ -61,26 +61,24 @@ def build_caiwu_payload(request):
order_qs = _order_qs(request)
cz_qs = _czjilu_qs(request)
hy_qs = _huiyuangoumai_qs(request)
income_qs = _daily_income_qs(request)
payout_qs = _daily_payout_qs(request)
scope = resolve_club_scope(request)
today_income_qs = income_qs.filter(date=today)
today_payout_qs = payout_qs.filter(date=today)
inc_agg = today_income_qs.aggregate(
# 四个板子:全平台合计(与 /houtai/caiwu 一致,读 date 字段)
today_inc = DailyIncomeStat.query.filter(date=today).aggregate(
total_amount=Sum('total_amount'),
total_count=Sum('total_count'),
)
today_income_amount = float(inc_agg['total_amount'] or 0.00)
today_income_count = int(inc_agg['total_count'] or 0)
today_income_amount = float(today_inc['total_amount'] or 0.00)
today_income_count = int(today_inc['total_count'] or 0)
pay_agg = today_payout_qs.aggregate(
today_pay = DailyPayoutStat.query.filter(date=today).aggregate(
total_amount=Sum('total_amount'),
total_count=Sum('total_count'),
)
today_payout_amount = float(pay_agg['total_amount'] or 0.00)
today_payout_count = int(pay_agg['total_count'] or 0)
today_payout_amount = float(today_pay['total_amount'] or 0.00)
today_payout_count = int(today_pay['total_count'] or 0)
today_orders = order_qs.filter(
CreateTime__gte=today_start,
@@ -135,59 +133,44 @@ def build_caiwu_payload(request):
total_payout = float(
DailyPayoutStat.query.aggregate(total=Sum('total_amount'))['total'] or 0.00
)
scoped_total_income = float(income_qs.aggregate(total=Sum('total_amount'))['total'] or 0.00)
scoped_total_payout = float(payout_qs.aggregate(total=Sum('total_amount'))['total'] or 0.00)
scoped_income_qs = _daily_income_qs(request)
scoped_payout_qs = _daily_payout_qs(request)
scoped_total_income = float(scoped_income_qs.aggregate(total=Sum('total_amount'))['total'] or 0.00)
scoped_total_payout = float(scoped_payout_qs.aggregate(total=Sum('total_amount'))['total'] or 0.00)
platform_profit = round(scoped_total_income - scoped_total_payout, 2)
daily_stats = []
since = today - timedelta(days=30)
if scope == DATA_SCOPE_ALL:
income_by_date = {
str(row['date']): {
'income': float(row['total_amount'] or 0),
'income_count': int(row['total_count'] or 0),
}
for row in income_qs.filter(date__gte=since).values('date').annotate(
total_amount=Sum('total_amount'),
total_count=Sum('total_count'),
)
income_by_date = {
str(row['date']): {
'income': float(row['total_amount'] or 0),
'income_count': int(row['total_count'] or 0),
}
payout_by_date = {
str(row['date']): float(row['total_amount'] or 0)
for row in payout_qs.filter(date__gte=since).values('date').annotate(
total_amount=Sum('total_amount'),
)
}
all_dates = sorted(
set(income_by_date.keys()) | set(payout_by_date.keys()),
reverse=True,
)[:30]
for d in all_dates:
inc = income_by_date.get(d, {'income': 0.0, 'income_count': 0})
payout_amt = payout_by_date.get(d, 0.00)
daily_stats.append({
'date': d,
'income': inc['income'],
'income_count': inc['income_count'],
'payout': payout_amt,
'profit': round(inc['income'] - payout_amt, 2),
})
else:
income_list = income_qs.filter(date__gte=since).order_by('-date')[:30]
payout_dict = {
str(p.date): float(p.total_amount)
for p in payout_qs.filter(date__gte=since)
}
for inc in income_list:
d = str(inc.date)
payout_amt = payout_dict.get(d, 0.00)
daily_stats.append({
'date': d,
'income': float(inc.total_amount),
'income_count': inc.total_count,
'payout': payout_amt,
'profit': round(float(inc.total_amount) - payout_amt, 2),
})
for row in DailyIncomeStat.query.filter(date__gte=since).values('date').annotate(
total_amount=Sum('total_amount'),
total_count=Sum('total_count'),
)
}
payout_by_date = {
str(row['date']): float(row['total_amount'] or 0)
for row in DailyPayoutStat.query.filter(date__gte=since).values('date').annotate(
total_amount=Sum('total_amount'),
)
}
all_dates = sorted(
set(income_by_date.keys()) | set(payout_by_date.keys()),
reverse=True,
)[:30]
for d in all_dates:
inc = income_by_date.get(d, {'income': 0.0, 'income_count': 0})
payout_amt = payout_by_date.get(d, 0.00)
daily_stats.append({
'date': d,
'income': inc['income'],
'income_count': inc['income_count'],
'payout': payout_amt,
'profit': round(inc['income'] - payout_amt, 2),
})
return {
'club_id': club_id,

View File

@@ -48,14 +48,8 @@ def _get_szjilu_for_update(club_id):
def apply_szjilu_income(amount, club_id=None):
"""平台收入:总收益、总流水、今日流水增加"""
jine = Decimal(str(amount))
with transaction.atomic():
szjilu = _get_szjilu_for_update(club_id)
szjilu.TotalIncome += jine
szjilu.TotalFlow += jine
szjilu.DailyFlow += jine
szjilu.save()
"""【已废弃】szjilu 禁止写入,财务只维护 daily_income_stat"""
logger.debug('apply_szjilu_income 已禁用 amount=%s club=%s', amount, club_id)
def subtract_szjilu_income(amount, club_id=None, subtract_daily_flow=True):
@@ -309,36 +303,8 @@ def sync_daily_income_stat_for_date(stat_date, reset_day=False):
def sync_szjilu_income_from_logs():
"""按 platform_income_log 全量重算各俱乐部 szjilu 累计收入/流水(纠正重复累加)"""
try:
rows = PlatformIncomeLog.objects.values('club_id').annotate(
total=Sum('amount'),
cnt=Count('id'),
)
except _PLATFORM_LOG_ERRORS as exc:
logger.error('platform_income_log 不可用: %s', exc)
return 0
today = date.today()
updated = 0
with transaction.atomic():
for row in rows:
cid = normalize_szjilu_club_id(row['club_id'])
total = row['total'] or _ZERO
today_agg = PlatformIncomeLog.objects.filter(
CreateTime__date=today, club_id=cid,
).aggregate(t=Sum('amount'))
today_flow = today_agg['t'] or _ZERO
szjilu, _ = Szjilu.objects.select_for_update().get_or_create(
club_id=cid,
defaults=dict(_SZJILU_DEFAULTS),
)
szjilu.TotalIncome = total
szjilu.TotalFlow = total
szjilu.DailyFlow = today_flow
szjilu.save(update_fields=['TotalIncome', 'TotalFlow', 'DailyFlow', 'UpdateTime'])
updated += 1
return updated
"""【已废弃】szjilu 禁止维护"""
return 0
# 订单已付款且非退款repair 错误地把 Status=5 退款单也计入了收入)
@@ -696,14 +662,8 @@ def recover_income_stats_for_date(stat_date, dry_run=True):
def apply_szjilu_expense(amount, club_id=None):
"""平台出款/支出:总收益减少,总支出、今日支出增加"""
jine = Decimal(str(amount))
with transaction.atomic():
szjilu = _get_szjilu_for_update(club_id)
szjilu.TotalIncome -= jine
szjilu.TotalExpense += jine
szjilu.DailyExpense += jine
szjilu.save()
"""【已废弃】szjilu 禁止写入,支出只维护 daily_payout_stat"""
logger.debug('apply_szjilu_expense 已禁用 amount=%s club=%s', amount, club_id)
def get_szjilu_snapshot(club_id=None):
@@ -887,12 +847,127 @@ def rebuild_income_stats_from_scratch(since_year=None, until_year=None, dry_run=
return result
def rebuild_daily_income_stat_table(dry_run=True):
"""
恢复 daily_income_stat 全表(财务看板唯一收入数据源)。
每笔 biz_ref 全局只计一次:
1. platform_income_log → 按日志 CreateTime 日期
2. 无日志的已支付订单/充值 → 按 UpdateTime 日期补入
不删日志、不碰 daily_payout_stat、不碰 szjilu。
"""
from collections import defaultdict
from orders.models import Order
from products.models import Czjilu
by_ref = {}
log_count = 0
try:
for log in PlatformIncomeLog.objects.all().iterator():
ref = (log.biz_ref or '').strip()
if not ref:
continue
stat_d = log.CreateTime.date() if log.CreateTime else date.today()
by_ref[ref] = {
'club_id': normalize_szjilu_club_id(log.club_id),
'amount': Decimal(str(log.amount or 0)),
'stat_date': stat_d,
}
log_count += 1
except _PLATFORM_LOG_ERRORS as exc:
logger.warning('platform_income_log 不可用,仅从订单补全: %s', exc)
gap_orders = 0
for od in Order.query.filter(Status__in=_LEGIT_ORDER_STATUSES):
ref = f'order:{od.OrderID}'
if ref in by_ref:
continue
pay_dt = od.UpdateTime or od.CreateTime
if not pay_dt:
continue
amt = Decimal(str(od.Amount or 0))
if amt <= 0:
continue
by_ref[ref] = {
'club_id': normalize_szjilu_club_id(getattr(od, 'ClubID', None)),
'amount': amt,
'stat_date': pay_dt.date() if hasattr(pay_dt, 'date') else pay_dt,
}
gap_orders += 1
gap_cz = 0
for cz in Czjilu.query.filter(zhuangtai=3, leixing__in=_LEGIT_CZ_LEIXING):
ref = f'cz:{cz.dingdan_id}'
if ref in by_ref:
continue
pay_dt = cz.UpdateTime or cz.CreateTime
if not pay_dt:
continue
amt = Decimal(str(cz.jine or 0))
if amt <= 0:
continue
by_ref[ref] = {
'club_id': normalize_szjilu_club_id(getattr(cz, 'club_id', None)),
'amount': amt,
'stat_date': pay_dt.date() if hasattr(pay_dt, 'date') else pay_dt,
}
gap_cz += 1
by_day_club = defaultdict(lambda: {'amt': _ZERO, 'cnt': 0})
today = date.today()
today_amt = _ZERO
today_cnt = 0
for info in by_ref.values():
key = (info['stat_date'], info['club_id'])
by_day_club[key]['amt'] += info['amount']
by_day_club[key]['cnt'] += 1
if info['stat_date'] == today:
today_amt += info['amount']
today_cnt += 1
total_amt = sum((v['amt'] for v in by_day_club.values()), _ZERO)
before = float(DailyIncomeStat.objects.aggregate(t=Sum('total_amount'))['t'] or 0)
result = {
'before_daily_total': before,
'after_daily_total': float(total_amt),
'payment_rows': len(by_ref),
'from_log': log_count,
'gap_orders': gap_orders,
'gap_cz': gap_cz,
'daily_rows': len(by_day_club),
'today_amount': float(today_amt),
'today_count': today_cnt,
'dry_run': dry_run,
}
if dry_run:
return result
with transaction.atomic():
DailyIncomeStat.objects.all().delete()
for (stat_d, cid), agg in by_day_club.items():
DailyIncomeStat.objects.create(
date=stat_d,
club_id=cid,
year=stat_d.year,
month=stat_d.month,
day=stat_d.day,
total_amount=agg['amt'],
total_count=agg['cnt'],
)
result['after_daily_total'] = float(
DailyIncomeStat.objects.aggregate(t=Sum('total_amount'))['t'] or 0
)
return result
def restore_finance_daily_stats(since_year=None, until_year=None, dry_run=True):
"""
一键恢复财务每日收入:从订单/充值重建 daily_income_stat + platform_income_log。
不碰 daily_payout_stat不碰 szjilu收支记录表已废弃
"""
return rebuild_income_stats_from_scratch(since_year, until_year, dry_run=dry_run)
"""兼容入口:全量恢复 daily_income_stat忽略 since/until整表重算"""
return rebuild_daily_income_stat_table(dry_run=dry_run)
def collect_today_live_wechat_payments(stat_date=None):
@@ -1044,18 +1119,4 @@ def repopulate_today_income_stats(stat_date=None, dry_run=True):
total_count=agg['cnt'],
)
today_d = date.today()
for cid, agg in by_club.items():
szjilu, _ = Szjilu.objects.select_for_update().get_or_create(
club_id=cid, defaults=dict(_SZJILU_DEFAULTS),
)
if stat_date == today_d:
szjilu.DailyFlow = agg['amt']
total_all = PlatformIncomeLog.objects.filter(club_id=cid).aggregate(
t=Sum('amount'),
)['t'] or _ZERO
szjilu.TotalIncome = total_all
szjilu.TotalFlow = total_all
szjilu.save(update_fields=['TotalIncome', 'TotalFlow', 'DailyFlow', 'UpdateTime'])
return result

View File

@@ -1,70 +1,149 @@
"""每日收支详细统计(供 /jituan/houtai/szxx旧 /houtai/szxx 不变)。"""
from datetime import date, datetime
from datetime import date
from django.db.models import Sum
from django.db.models.functions import ExtractDay, ExtractMonth, ExtractYear
from config.models import DailyIncomeStat, DailyPayoutStat
from jituan.services.club_context import filter_queryset_by_club, resolve_club_id_from_request, resolve_club_scope
from jituan.services.club_context import (
filter_club_char_field,
resolve_club_id_from_request,
resolve_club_scope,
)
def _month_bounds(y, m):
start = date(int(y), int(m), 1)
if int(m) == 12:
end = date(int(y) + 1, 1, 1)
else:
end = date(int(y), int(m) + 1, 1)
return start, end
def _year_bounds(y):
y = int(y)
return date(y, 1, 1), date(y + 1, 1, 1)
def build_szxx_payload(request, granularity, year, month, summary_date):
"""
与 SzxxView 返回结构一致,按俱乐部过滤日收入/日出款统计
返回 (data_dict, error_msg)error_msg 非空时表示参数错误
与 SzxxView 返回结构一致。
统一用 date 字段查询(与 /houtai/caiwu 四个板子一致),不用 year/month/day 冗余列
"""
now = date.today()
income_base = filter_club_char_field(DailyIncomeStat.objects.all(), request, field='club_id')
payout_base = filter_club_char_field(DailyPayoutStat.objects.all(), request, field='club_id')
if granularity == 'day':
if not year or not month:
return None, '按日统计需要年份和月份'
group_field = 'day'
income_filter = {'year': year, 'month': month}
payout_filter = {'year': year, 'month': month}
year, month = int(year), int(month)
chart_start, chart_end = _month_bounds(year, month)
income_rows = (
income_base.filter(date__gte=chart_start, date__lt=chart_end)
.annotate(day_key=ExtractDay('date'))
.values('day_key')
.annotate(total_income=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('day_key')
)
payout_rows = (
payout_base.filter(date__gte=chart_start, date__lt=chart_end)
.annotate(day_key=ExtractDay('date'))
.values('day_key')
.annotate(total_payout=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('day_key')
)
if not summary_date:
summary_date = now.strftime('%Y-%m-%d')
summary_parts = summary_date.split('-')
summary_filter = {
'year': int(summary_parts[0]),
'month': int(summary_parts[1]),
'day': int(summary_parts[2]),
}
summary_d = date.fromisoformat(str(summary_date)[:10])
income_summary = income_base.filter(date=summary_d).aggregate(
total_income=Sum('total_amount'), total_count=Sum('total_count'),
)
payout_summary = payout_base.filter(date=summary_d).aggregate(
total_payout=Sum('total_amount'), total_count=Sum('total_count'),
)
def _fmt_day(key):
return f'{year}-{month:02d}-{int(key):02d}'
elif granularity == 'month':
if not year:
return None, '按月统计需要年份'
group_field = 'month'
income_filter = {'year': year}
payout_filter = {'year': year}
year = int(year)
chart_start, chart_end = _year_bounds(year)
income_rows = (
income_base.filter(date__gte=chart_start, date__lt=chart_end)
.annotate(month_key=ExtractMonth('date'))
.values('month_key')
.annotate(total_income=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('month_key')
)
payout_rows = (
payout_base.filter(date__gte=chart_start, date__lt=chart_end)
.annotate(month_key=ExtractMonth('date'))
.values('month_key')
.annotate(total_payout=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('month_key')
)
if not summary_date:
summary_date = now.strftime('%Y-%m')
summary_parts = summary_date.split('-')
summary_filter = {'year': int(summary_parts[0]), 'month': int(summary_parts[1])}
parts = str(summary_date).split('-')
s_start, s_end = _month_bounds(parts[0], parts[1])
income_summary = income_base.filter(date__gte=s_start, date__lt=s_end).aggregate(
total_income=Sum('total_amount'), total_count=Sum('total_count'),
)
payout_summary = payout_base.filter(date__gte=s_start, date__lt=s_end).aggregate(
total_payout=Sum('total_amount'), total_count=Sum('total_count'),
)
def _fmt_day(key):
return f'{year}-{int(key):02d}'
elif granularity == 'year':
group_field = 'year'
income_filter = {}
payout_filter = {}
income_rows = (
income_base.annotate(year_key=ExtractYear('date'))
.values('year_key')
.annotate(total_income=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('year_key')
)
payout_rows = (
payout_base.annotate(year_key=ExtractYear('date'))
.values('year_key')
.annotate(total_payout=Sum('total_amount'), total_count=Sum('total_count'))
.order_by('year_key')
)
if not summary_date:
summary_date = str(now.year)
summary_filter = {'year': int(summary_date)}
s_start, s_end = _year_bounds(int(summary_date))
income_summary = income_base.filter(date__gte=s_start, date__lt=s_end).aggregate(
total_income=Sum('total_amount'), total_count=Sum('total_count'),
)
payout_summary = payout_base.filter(date__gte=s_start, date__lt=s_end).aggregate(
total_payout=Sum('total_amount'), total_count=Sum('total_count'),
)
def _fmt_day(key):
return str(int(key))
else:
return None, '无效的颗粒度'
income_qs = filter_queryset_by_club(
DailyIncomeStat.query.filter(**income_filter), request,
).values(group_field).annotate(
total_income=Sum('total_amount'),
total_count=Sum('total_count'),
).order_by(group_field)
payout_qs = filter_queryset_by_club(
DailyPayoutStat.query.filter(**payout_filter), request,
).values(group_field).annotate(
total_payout=Sum('total_amount'),
total_count=Sum('total_count'),
).order_by(group_field)
data_map = {}
for item in income_qs:
key = item[group_field]
if granularity == 'day':
key_field = 'day_key'
elif granularity == 'month':
key_field = 'month_key'
else:
key_field = 'year_key'
for item in income_rows:
key = item[key_field]
data_map[key] = {
'income': float(item['total_income'] or 0),
'income_count': item['total_count'] or 0,
@@ -72,8 +151,8 @@ def build_szxx_payload(request, granularity, year, month, summary_date):
'payout_count': 0,
}
for item in payout_qs:
key = item[group_field]
for item in payout_rows:
key = item[key_field]
if key not in data_map:
data_map[key] = {'income': 0.0, 'income_count': 0, 'payout': 0.0, 'payout_count': 0}
data_map[key]['payout'] = float(item['total_payout'] or 0)
@@ -81,27 +160,15 @@ def build_szxx_payload(request, granularity, year, month, summary_date):
time_series = []
for key, vals in data_map.items():
if granularity == 'day':
date_str = f"{year}-{month:02d}-{key:02d}"
elif granularity == 'month':
date_str = f"{year}-{key:02d}"
else:
date_str = str(key)
profit = round(vals['income'] - vals['payout'], 2)
time_series.append({
'date': date_str,
'date': _fmt_day(key),
'income': vals['income'],
'payout': vals['payout'],
'profit': profit,
})
time_series.sort(key=lambda x: x['date'])
income_summary = filter_queryset_by_club(
DailyIncomeStat.query.filter(**summary_filter), request,
).aggregate(total_income=Sum('total_amount'), total_count=Sum('total_count'))
payout_summary = filter_queryset_by_club(
DailyPayoutStat.query.filter(**summary_filter), request,
).aggregate(total_payout=Sum('total_amount'), total_count=Sum('total_count'))
total_income = float(income_summary['total_income'] or 0)
total_payout = float(payout_summary['total_payout'] or 0)