Files
Django/merchant_ops/services/stats.py

109 lines
3.5 KiB
Python

"""子客服日统计 + 商家日统计双写。"""
from datetime import date
from decimal import Decimal
from django.db import transaction
from django.db.models import F
from backend.utils import update_shangjia_daily
from merchant_ops.constants import STAT_ACTION_DISPATCH, STAT_ACTION_REFUND, STAT_ACTION_SETTLE
from merchant_ops.models import MerchantStaffDailyStats
def _action_fields(action, amount):
amount = Decimal(str(amount))
if action == STAT_ACTION_DISPATCH:
return {'dispatch_count': 1, 'dispatch_amount': amount}
if action == STAT_ACTION_SETTLE:
return {'settle_count': 1, 'settle_amount': amount}
if action == STAT_ACTION_REFUND:
return {'refund_count': 1, 'refund_amount': amount}
return {}
def update_staff_daily(merchant_id, staff_user_id, member_id, amount, action):
"""子客服日统计;老板操作不写此表。"""
amount = Decimal(str(amount)) if amount else Decimal('0.00')
fields = _action_fields(action, amount)
if not fields:
return
today = date.today()
with transaction.atomic():
stat, _ = MerchantStaffDailyStats.objects.select_for_update().get_or_create(
merchant_id=merchant_id,
staff_user_id=staff_user_id,
stat_date=today,
defaults={
'club_id': 'xq',
'member_id': member_id,
'year': today.year,
'month': today.month,
'day': today.day,
},
)
update_kwargs = {}
for k, v in fields.items():
if k.endswith('_count'):
update_kwargs[k] = F(k) + int(v)
else:
update_kwargs[k] = F(k) + v
MerchantStaffDailyStats.query.filter(id=stat.id).update(**update_kwargs)
def update_merchant_and_staff_stats(merchant_id, staff_member, amount, action):
"""商家日统计必写;子客服则双写。"""
update_shangjia_daily(merchant_id, amount, action)
if staff_member:
update_staff_daily(
merchant_id,
staff_member.staff_user_id,
staff_member.id,
amount,
action,
)
def bump_cancel_count(merchant_id, staff_member):
if not staff_member:
return
today = date.today()
with transaction.atomic():
stat, _ = MerchantStaffDailyStats.objects.select_for_update().get_or_create(
merchant_id=merchant_id,
staff_user_id=staff_member.staff_user_id,
stat_date=today,
defaults={
'club_id': 'xq',
'member_id': staff_member.id,
'year': today.year,
'month': today.month,
'day': today.day,
},
)
MerchantStaffDailyStats.query.filter(id=stat.id).update(
cancel_count=F('cancel_count') + 1,
)
def bump_penalty_count(merchant_id, staff_member):
if not staff_member:
return
today = date.today()
with transaction.atomic():
stat, _ = MerchantStaffDailyStats.objects.select_for_update().get_or_create(
merchant_id=merchant_id,
staff_user_id=staff_member.staff_user_id,
stat_date=today,
defaults={
'club_id': 'xq',
'member_id': staff_member.id,
'year': today.year,
'month': today.month,
'day': today.day,
},
)
MerchantStaffDailyStats.query.filter(id=stat.id).update(
penalty_count=F('penalty_count') + 1,
)