def sms_invite(request, party_id):
    party = get_object_or_404(Party, id=party_id)

    if request.method == "POST":
        form = SMSInviteForm(request.POST)
        if form.is_valid():
            with transaction.commit_on_success():
                party.invite_type = "phone"  # 将邀请方式修改为phone
                party.save()

                sms_message, created = SMSMessage.objects.get_or_create(
                    party=party,
                    defaults={
                        "content": form.cleaned_data["content"],
                        "is_apply_tips": form.cleaned_data["is_apply_tips"],
                    },
                )
                if not created:
                    sms_message.content = form.cleaned_data["content"]
                    sms_message.is_apply_tips = form.cleaned_data["is_apply_tips"]
                    sms_message.save()

                client_phone_list = form.cleaned_data["client_phone_list"].split(",")
                parties_clients = PartiesClients.objects.select_related("client").filter(party=party)
                clients = Client.objects.filter(creator=request.user)

                for phone in client_phone_list:
                    client_temp = None
                    for client in clients:
                        if client.phone == phone.strip():
                            client_temp = client
                            break

                    if not client_temp:
                        client_temp = Client.objects.create(
                            creator=request.user, name=phone, phone=phone, invite_type="phone"
                        )

                    party_client_temp = None
                    for party_client in parties_clients:
                        if party_client.client == client_temp:
                            party_client_temp = party_client
                            break

                    if not party_client_temp:
                        party_client = PartiesClients.objects.create(party=party, client=client_temp)

            send_status = u"短信发送失败"
            with transaction.commit_on_success():
                send_message = Outbox(address=form.cleaned_data["client_phone_list"], base_message=sms_message)
                send_message.save()
                send_status = u"短信发送成功"

            request.session["send_status"] = send_status

            return redirect("list_party")
        else:
            client_data = []
            for client in Client.objects.filter(creator=request.user):
                if client.phone:
                    client_data.append(client.phone)
            return TemplateResponse(
                request,
                "parties/sms_invite.html",
                {"form": form, "party": party, "client_data": simplejson.dumps(client_data)},
            )
    else:
        apply_status = request.GET.get("apply", "all")
        if apply_status == "all":
            clients = PartiesClients.objects.filter(party=party_id).exclude(client__invite_type="public")
        else:
            clients = (
                PartiesClients.objects.filter(party=party_id)
                .filter(apply_status=apply_status)
                .exclude(client__invite_type="public")
            )

        if clients:
            client_phone_list = []
            for client in clients:
                client_phone_list.append(client.client.phone)
            client_phone_list = ",".join(client_phone_list)

            sms_message = SMSMessage.objects.get(party=party)

            data = {
                "client_phone_list": client_phone_list,
                "content": sms_message.content,
                "is_apply_tips": sms_message.is_apply_tips,
            }
            form = SMSInviteForm(initial=data)
        else:
            # 生成默认内容
            content = party.creator.username + u"邀请你参加:"
            if party.start_time == None and party.address == "":
                content = content + party.description + u",时间、地点,另行通知。"
            elif party.start_time != None and party.address == u"":
                content = (
                    content
                    + datetime.datetime.strftime(party.start_time, "%Y-%m-%d %H:%M")
                    + party.description
                    + u",地点另行通知。"
                )
            elif party.start_time == None and party.address != "":
                content = content + u"在" + party.address + party.description + u",时间待定。"
            else:
                content = (
                    content
                    + datetime.time.strftime(party.start_time, "%Y-%m-%d %H:%M")
                    + u" ,在"
                    + party.address
                    + u"的活动"
                    + party.description
                )

            data = {"client_phone_list": "", "content": content, "is_apply_tips": True}
            form = SMSInviteForm(initial=data)
        client_data = []
        for client in Client.objects.filter(creator=request.user):
            if client.phone:
                client_data.append(client.phone)
        return TemplateResponse(
            request,
            "parties/sms_invite.html",
            {"form": form, "party": party, "client_data": simplejson.dumps(client_data)},
        )
Exemple #2
0
def sms_invite(request, party_id):
    party = get_object_or_404(Party, id = party_id, creator = request.user)
    #取得最近20个活动,用来从中获取好友
    recent_parties = Party.objects.filter(invite_type = 'phone').filter(creator = request.user).exclude(id = party.id).order_by('-created_time')
    
    if request.method == 'POST':
        form = SMSInviteForm(request.POST)
        if form.is_valid():
            number_of_message = 1     #每次邀请转换为短信的条数, 默认一条       
            with transaction.commit_on_success():
                party.invite_type = 'phone' #将邀请方式修改为phone
                party.save()
                
                sms_message, created = SMSMessage.objects.get_or_create(party = party,
                    defaults = {'content': form.cleaned_data['content'], 'is_apply_tips': form.cleaned_data['is_apply_tips']})
                if not created:
                    sms_message.content = form.cleaned_data['content']
                    sms_message.is_apply_tips = form.cleaned_data['is_apply_tips']
                    sms_message.save()
                    
                number_of_message = (len(sms_message.content) + (SHORT_LINK_LENGTH if sms_message.is_apply_tips else 0) + BASIC_MESSAGE_LENGTH - 1) / BASIC_MESSAGE_LENGTH    
                client_phone_list = form.cleaned_data['client_phone_list'].split(',')
                parties_clients = PartiesClients.objects.select_related('client').filter(party = party)
                clients = Client.objects.filter(creator = request.user)
                
                for phone in client_phone_list:
                    client_temp = None
                    for client in clients:
                        if client.phone == phone.strip():
                            client_temp = client
                            break
                    
                    if not client_temp:
                        client_temp = Client.objects.create(
                            creator = request.user,
                            #name = phone,
                            phone = phone,
                            invite_type = 'phone'
                        )
                    
                    party_client_temp = None
                    for party_client in parties_clients:
                        if party_client.client == client_temp:
                            party_client_temp = party_client
                            break
                    
                    if not party_client_temp:
                        party_client = PartiesClients.objects.create(
                            party = party,
                            client = client_temp
                        )

            send_status = 'sms_fail'
            sms_count = ''
            client_phone_list = form.cleaned_data['client_phone_list'].split(',')
            client_phone_list_len = len(client_phone_list)
            userprofile = request.user.get_profile() 
            sms_count = userprofile.available_sms_count
            will_send_message_num = client_phone_list_len * number_of_message #可能发送的从短信条数
            if will_send_message_num > sms_count:#短信人数*短信数目>可发送的短信数目,拒绝发送
                form.errors['client_phone_list'] = '将要发送的短信数量大于可用的短信数量。请调整后继续发送。'
                
                client_data = []
                for client in Client.objects.filter(creator = request.user):
                    if client.phone:
                        client_data.append(client.phone)
                noanswer_client = []
                apply_client = []
                reject_client = []
                parties_clients = PartiesClients.objects.select_related('client').filter(party = party)
                for  party_client in parties_clients :
                    if party_client.apply_status == 'noanswer':
                        noanswer_client.append(party_client.client.phone)
                    if party_client.apply_status == 'apply':
                        apply_client.append(party_client.client.phone)
                    if party_client.apply_status == 'reject':
                        reject_client.append(party_client.client.phone)
                
                noanswer_client = ','.join(noanswer_client)
                apply_client = ','.join(apply_client)
                reject_client = ','.join(reject_client)
                quickadd_client = {'noanswer_client':noanswer_client,
                                   'apply_client':apply_client,
                                   'reject_client':reject_client
                                   }                    
                return TemplateResponse(request, 'parties/sms_invite.html', {'form': form, 'party': party, 'client_data':simplejson.dumps(client_data), 'quickadd_client':quickadd_client, 'recent_parties':recent_parties})
            
            
            with transaction.commit_on_success():
                client_phone_list = form.cleaned_data['client_phone_list']
                send_message = Outbox(address = client_phone_list, base_message = sms_message)
                send_message.save()
                send_status = 'sms_success'
                
            request.session['sms_count'] = sms_count - will_send_message_num    
            request.session['send_status'] = send_status 
            return redirect('list_party')
        else:
            client_data = []
            for client in Client.objects.filter(creator = request.user):
                if client.phone:
                    client_data.append(client.phone)
            noanswer_client = []
            apply_client = []
            reject_client = []
            parties_clients = PartiesClients.objects.select_related('client').filter(party = party)
            for  party_client in parties_clients :
                if party_client.apply_status == 'noanswer':
                    noanswer_client.append(party_client.client.phone)
                if party_client.apply_status == 'apply':
                    apply_client.append(party_client.client.phone)
                if party_client.apply_status == 'reject':
                    reject_client.append(party_client.client.phone)
            
            noanswer_client = ','.join(noanswer_client)
            apply_client = ','.join(apply_client)
            reject_client = ','.join(reject_client)
            quickadd_client = {'noanswer_client':noanswer_client,
                               'apply_client':apply_client,
                               'reject_client':reject_client
                               }                    
            return TemplateResponse(request, 'parties/sms_invite.html', {'form': form, 'party': party, 'client_data':simplejson.dumps(client_data), 'quickadd_client':quickadd_client, 'recent_parties':recent_parties})
    else:
        apply_status = request.GET.get('apply', 'all')
        if apply_status == 'all':
            clients = PartiesClients.objects.filter(party = party_id)
        else:
            clients = PartiesClients.objects.filter(party = party_id).filter(apply_status = apply_status)

        #生成默认内容
        userprofile = request.user.get_profile()
        creator = userprofile.true_name if userprofile.true_name else request.user.username  
        content = _create_default_content(creator, party.start_date, party.start_time , party.address, party.description)
        
        if clients:
            client_phone_list = []
            for client in clients:
                client_phone_list.append(client.client.phone)
            client_phone_list = ','.join(client_phone_list)

            sms_message = SMSMessage.objects.get(party = party)

            data = {
                'client_phone_list': client_phone_list,
                'content': content,
                'is_apply_tips' : sms_message.is_apply_tips
            }
            form = SMSInviteForm(initial = data)
        else:
            data = {
               'client_phone_list': '',
               'content': content,
               'is_apply_tips' : True
            }
            form = SMSInviteForm(initial = data)    
        client_data = []
        for client in Client.objects.filter(creator = request.user):
            if client.phone:
                client_data.append(client.phone)
        noanswer_client = []
        apply_client = []
        reject_client = []
        parties_clients = PartiesClients.objects.select_related('client').filter(party = party)
        for  party_client in parties_clients :
            if party_client.apply_status == 'noanswer':
                noanswer_client.append(party_client.client.phone)
            if party_client.apply_status == 'apply':
                apply_client.append(party_client.client.phone)
            if party_client.apply_status == 'reject':
                reject_client.append(party_client.client.phone)
        
        noanswer_client = ','.join(noanswer_client)
        apply_client = ','.join(apply_client)
        reject_client = ','.join(reject_client)
        quickadd_client = {'noanswer_client':noanswer_client,
                           'apply_client':apply_client,
                           'reject_client':reject_client
                           }        
        return TemplateResponse(request, 'parties/sms_invite.html', {'form': form, 'party': party, 'client_data':simplejson.dumps(client_data), 'quickadd_client':quickadd_client, 'recent_parties':recent_parties})