Example #1
0
def apply_an_activity(request, action_id):
    user = request.user
    activity = get_object_or_404(Activity, id=action_id, is_active=True)
    if not user.is_authenticated():
        # 如果用户没有登陆,将其到引导登陆页面
        next_url = '/login?next=/action/%s' % action_id
        # 注意追踪推广参数
        if 'promotion_code' in request.POST:
            next_url += '?code=%s' % request.POST['promotion_code']
        return HttpResponse(json.dumps({'success': True, 'data': {'url': next_url}}))

    # 确认用户已经登陆以后,开始开始申请活动
    if Questionnaire.objects.filter(activity=activity, is_active=True).exists():
        # Then load the answer data and create the answer sheet
        q = Questionnaire.objects.filter(activity=activity, is_active=True).first()
        json_data = simplejson.loads(request.POST.get("answer", "{}"))
        try:
            create_answer_set_with_json({"answer": json_data}, request, q, request.user)
        except ValidationError:
            logger.debug(u"创建答案失败,发生了Validation错误,提交的json格式为:{0:s}".format(json))
            raise ValidationError(u"创建答案失败")

    # 此时,尝试申请活动
    application, success, error_info = ApplicationThrough.objects.try_to_apply(activity=activity, user=user)
    if success:
        # 向活动的创建者发送通知
        send_notification.send(sender=get_user_model(),
                               notification_type="activity_notification",
                               notification_center=activity.host.notification_center,
                               activity=activity,
                               user=request.user,
                               activity_notification_type="activity_applied")
        # 在这里我们需要检查当前用户是否是由其他用户分享过来的
        code = request.POST.get('promotion_code', None)
        if code is not None and code != user.profile.promotion_code:
            try:
                sharer = get_user_model().objects.get(profile__promotion_code=code)
                ShareRecord.objects.create(sharer=sharer, user=user, activity=activity)
            except ObjectDoesNotExist:
                logger.debug(u"发现非法的promotion_code: %s" % code)
        # 在日志内记录本次申请行为
        logger.debug(u"报名活动成功,对应活动为|{0:s}|(id:{1:d}), 当前用户为|{2:s}|({3:s})"
                     .format(activity.name, activity.id, request.user.profile.name, request.user.username))
        return HttpResponse(json.dumps({'success': True, 'data': {'url': '/mine/apply'}}))
    else:
        logger.debug(u"报名活动失败,对应活动为|{0:s}|(id:{1:d}), 当前用户为|{2:s}|({3:s}),原因为:{4:s}"
                     .format(activity.name, activity.id, request.user.profile.name, request.user.username, error_info))
        return HttpResponse(json.dumps({'success': False, 'data': {'id': error_info}}))
Example #2
0
def send_del_notification_to_candidate(act):
    """ 向该活动的所有参与者发送该活动已经被删除的通知
    """
    from Activity.models import ApplicationThrough
    applicants = ApplicationThrough.objects.filter(is_active=True,
                                                   activity=act,
                                                   status__in=['applying', 'approved', 'ready'])
    for applicant in applicants:
        send_notification.send(sender=settings.AUTH_USER_MODEL,
                               notification_type='activity_notification',
                               notification_center=applicant.user.notification_center,
                               activity=act,
                               user=applicant.user,
                               activity_notification_type='activity_deleted')

    applicants.update(is_active=False)
Example #3
0
def send_del_notification_to_candidate(act):
    """ 向该活动的所有参与者发送该活动已经被删除的通知
    """
    from Activity.models import ApplicationThrough
    applicants = ApplicationThrough.objects.filter(
        is_active=True,
        activity=act,
        status__in=['applying', 'approved', 'ready'])
    for applicant in applicants:
        send_notification.send(
            sender=settings.AUTH_USER_MODEL,
            notification_type='activity_notification',
            notification_center=applicant.user.notification_center,
            activity=act,
            user=applicant.user,
            activity_notification_type='activity_deleted')

    applicants.update(is_active=False)
Example #4
0
def unapply_an_activity(request, action_id):
    activity = get_object_or_404(Activity, id=action_id)
    applicant = get_object_or_404(ApplicationThrough, activity=activity,
                                  user=request.user,
                                  is_active=True,
                                  status__in=["applying", "approved"])
    applicant.is_active = False
    applicant.status = "applying"
    applicant.save()
    send_notification.send(sender=get_user_model(),
                           notification_type="activity_notification",
                           notification_center=activity.host.notification_center,
                           activity=activity,
                           user=request.user,
                           activity_notification_type="cancel_apply")
    return JsonResponse({
        "success": True,
        "data": {
            "url": "/mine/apply"
        }
    }, content_type='text/html')
Example #5
0
def manage_an_activity2(request):
    user = request.user
    # 解析操作参数
    if request.method == 'GET':
        optype = request.GET['optype']
        action_id = request.GET['action']
        target_id = request.GET['target']
    else:
        optype = request.POST["optype"]
        action_id = request.POST["action"]
        target_id = request.POST["target"]
    # 获取目标活动
    activity = get_object_or_404(Activity, id=action_id, is_active=True)
    # 检查当前用户的操作权限
    if activity.host_id != user.id:
        return HttpResponse(json.dumps({'success': False, 'data': {'error': '没有操作权限'}}))
    # 获取目标用户
    try:
        target_user = get_user_model().objects.select_related('profile').get(id=target_id)
    except ObjectDoesNotExist:
        target_user = None

    # 开始按照optype参数的种类注意检查操作
    if optype == 'approve':
        # 通过申请操作
        if target_user is None:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "参数缺失"}}))
        approved_num = ApplicationThrough.objects.filter(activity=activity, is_active=True, status='approved').count()
        if approved_num >= activity.max_attend:
            # 如果当前已经通过的人数超过了最大运行的人数,则申请失败
            return HttpResponse(json.dumps({"success": False, "data": {"error": "该活动已报满"}}))
        # 查找出申请记录
        try:
            applicant = ApplicationThrough.objects.get(activity=activity, user=target_user, is_active=True,
                                                       status__in=['applying', 'denied'])
            applicant.status = "approved"
            applicant.save()
            send_notification.send(
                sender=get_user_model(),
                notification_center=target_user.notification_center,
                notification_type="activity_notification",
                activity=activity,
                user=target_user,
                activity_notification_type="apply_approved")

            if activity.id in Activity.objects.identification_acts_id:
                target_user.profile.identified = True
                target_user.profile.identified_date = timezone.now()
                target_user.profile.save()
            return HttpResponse(json.dumps({"success": True, "data": {}}))
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "目标并未申请本活动"}}))

    elif optype == 'approve_cancel':
        # 取消通过目标用户的申请
        if target_user is None:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "参数缺失"}}))
        try:
            applicant = ApplicationThrough.objects.get(
                activity=activity, user=target_user, is_active=True, status='approved')
            applicant.status = 'applying'
            applicant.save()
            # 检查这是否牵涉到认证用户,若是,需要剥夺相关用户的认证
            if activity.id in Activity.objects.identification_acts_id:
                target_user.profile.identified = False
                target_user.profile.save()
            return HttpResponse(json.dumps({"success": True, "data": {}}))
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "目标并未申请本活动或者其申请未被通过"}}))

    elif optype == 'deny':
        # 拒绝某个人的申请
        if target_user is None:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "参数缺失"}}))
        # 首先检索出目标用户的申请记录, 修改记录的状态
        try:
            applicant = ApplicationThrough.objects.get(activity=activity, user=target_user, is_active=True,
                                                       status__in=['applying', 'approved'])
            applicant.status = 'denied'
            applicant.save()
            # 向目标用户发送通知
            send_notification.send(
                sender=get_user_model(),
                notification_center=target_user.notification_center,
                notification_type="activity_notification",
                activity=activity,
                user=target_user,
                activity_notification_type="apply_rejected")
            # 返回json响应
            return HttpResponse(json.dumps({'success': True, 'data': {}}))
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "目标并未申请本活动"}}))

    elif optype == 'deny_cancel':
        # 取消拒绝
        if target_user is None:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "参数缺失"}}))
        try:
            applicant = ApplicationThrough.objects.get(
                activity=activity, user=target_user, is_active=True, status='denied')
            applicant.status = 'applying'
            applicant.save()
            return HttpResponse(json.dumps({'success': True, 'data': {}}))
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "目标并未申请本活动或者其申请未被拒绝"}}))

    elif optype == 'finish':
        # 完成活动
        if target_user is None:
            return HttpResponse(json.dumps({"success": False, "data": {"error": "参数缺失"}}))
        if activity.status != 2:
            return HttpResponse(json.dumps({'success': False, "data": {'error': '活动尚未结束'}}))
        try:
            applicant = ApplicationThrough.objects.get(
                activity=activity, user=target_user, is_active=True, status='approved')
            applicant.status = 'finished'
            applicant.save()
            # 向目标用户发送消息
            send_notification.send(
                sender=get_user_model(),
                notification_center=target_user.notification_center,
                notification_type='activity_notification',
                activity=activity,
                user=target_user,
                activity_notification_type='activity_finished')
            # TODO: 这里要确定应该是向米团长还是活动分享人发送通知
            try:
                share_record = ShareRecord.objects.get(user=user, activity=activity)
            except ObjectDoesNotExist:
                share_record = None
            team_leader = target_user.profile.team_leader
            contribution = RiceTeamContribution.objects.create(
                leader=team_leader, user=target_user, activity=activity)
            if team_leader is not None and activity.host.profile.identified:
                team_leader.profile.coin += contribution.contributed_coin
                team_leader.save()
            return HttpResponse(json.dumps({'success': True, 'data': {}}))
        except ObjectDoesNotExist:
            return HttpResponse(json.dumps({'success': False, 'data': {'error': '目标并未申请或者申请未被通过'}}))

    elif optype == "excel":
        def generate_excel_data():
            applicants = ApplicationThrough.objects.filter(activity=activity,
                                                           is_active=True)
            column_names = [u"用户姓名", u"性别", u"出生日期", u"年龄", u"联系方式", u"报名时间", u"申请状态"]

            def row_generator(app):
                # accept the applicant data as input, output the row data for the excel file
                row_user_profile = app.user.profile
                row_data = [row_user_profile.name,
                            row_user_profile.get_gender_display(),
                            row_user_profile.birthDate.strftime("%Y-%m-%d"),
                            str(row_user_profile.age),
                            row_user_profile.phoneNum,
                            timezone.make_naive(timezone.localtime(app.apply_at)).strftime("%Y-%m-%d %H-%M-%S"),
                            app.get_status_display()]
                return row_data

            data = map(row_generator, applicants)
            return [column_names] + data
        excel_data = generate_excel_data()
        return excel_response.ExcelResponse(excel_data, output_name=(activity.name+u"报名列表").encode("utf-8"))

    else:
        return HttpResponse(json.dumps({'success': False, 'data':{'error': '操作未定义'}}))