""" 打手注册共用逻辑:邀请码解析、创建打手、管事邀请统计。 """ import logging from django.conf import settings from django.db import transaction from yonghu.models import UserDashou, UserGuanshi logger = logging.getLogger('yonghu.dashouzhuce') def get_default_dashou_invite_code(): return getattr(settings, 'DASHOU_DEFAULT_INVITE_CODE', '').strip() def resolve_guanshi_for_dashou_register(invite_code): """ 根据邀请码查找管事;无邀请码时使用默认码;默认码查不到时按平台管事 yonghuid 回退。 返回 (guanshi_profile, error_message) """ code = (invite_code or '').strip() default_code = get_default_dashou_invite_code() if not code: code = default_code if not code: return None, '邀请码不能为空' if len(code) > 100: return None, '邀请码长度超过限制' guanshi = UserGuanshi.objects.select_related('user').filter(yaoqingma=code).first() if guanshi: return guanshi, None if default_code and code == default_code: fallback_uid = getattr(settings, 'DASHOU_DEFAULT_GUANSHI_YONGHUID', '').strip() if fallback_uid: guanshi = UserGuanshi.objects.select_related('user').filter( user__yonghuid=fallback_uid, ).first() if guanshi: if guanshi.yaoqingma != code: UserGuanshi.objects.filter(pk=guanshi.pk).update(yaoqingma=code) guanshi.refresh_from_db() logger.info('默认邀请码回退到平台管事 yonghuid=%s', fallback_uid) return guanshi, None return None, '邀请码无效或不存在' def create_dashou_for_user(user_main, guanshi_profile): """为已登录用户创建打手身份,并更新管事邀请统计。返回 dashou_profile。""" try: return user_main.dashou_profile except UserDashou.DoesNotExist: pass guanshi_yonghuid = guanshi_profile.user.yonghuid with transaction.atomic(): dashou_profile = UserDashou.objects.create( user=user_main, nicheng='大手子', chenghao='普通大手', yaoqingren=guanshi_yonghuid, jifen=5, ) locked_guanshi = UserGuanshi.objects.select_for_update().get(pk=guanshi_profile.pk) locked_guanshi.yaogingshuliang += 1 locked_guanshi.save(update_fields=['yaogingshuliang']) try: from decimal import Decimal from houtai.utils import update_guanshi_daily_by_action update_guanshi_daily_by_action( yonghuid=guanshi_yonghuid, action=1, amount=Decimal('0.00'), ) except Exception as stat_err: logger.warning('管事每日统计更新失败(邀请打手):%s', stat_err) return dashou_profile def ensure_guanshi_profile_for_user(user_main): """扫码注册流程:若用户尚无管事身份则创建(已存在则跳过)。""" if UserGuanshi.objects.filter(user=user_main).exists(): return UserGuanshi.objects.get(user=user_main) from utils.yaoqingma_utils import chuangjianYaoqingma return UserGuanshi.objects.create( user=user_main, yaoqingma=chuangjianYaoqingma(str(user_main.yonghuid)), )