示例#1
0
def showmessagebox(request):
	user = request.user

	if request.method == 'POST':
		touser = User.objects.filter(username=request.POST['touser'])
		content = request.POST['content']
		if len(touser) != 0:
			mail = Message(sender=user,receiver=touser[0],content=content)
			mail.save()
			return getmessagesfrom(request, touser[0].username)
		else:
			assert False

	if request.method == 'GET':
		if 'username' in request.GET:
			return getmessagesfrom(request, request.GET['username'])

	#queries to get a list of unique users this user has messaged (sent or received)
	messages = (user.received.all() | user.sent.all()).order_by('-date_sent')
	all_interactions = [message.sender if message.sender!= user else message.receiver for message in messages]
	interactions = []

	for message in all_interactions:
		if message not in interactions:
			interactions.append(message)

	unreadcount = []
	unreadvalues = []
	for sender in interactions:
		unreadcount.append(messages.filter(receiver=user, sender=sender, read=False).count())
		unreadvalues.append((sender,messages.filter(receiver=user, sender=sender, read=False).count()))

	request.session['unread_values'] = unreadvalues
	return render_to_response("messagebox.html", {}, RequestContext(request))
示例#2
0
def user_message_list_view(request, username):
    """
    Renders thread of all private messages between this user
    and the current user.
    """

    user = get_user_or_404(request, username)
    messages = (Message.objects.for_community(
        request.community).common_select_related().order_by(
            "-created").distinct())

    if user == request.user:
        messages = messages.for_sender_or_recipient(request.user)
    else:
        messages = messages.between(request.user, user)

    sent_messages = messages.filter(sender=request.user).count()
    received_messages = messages.filter(recipient=request.user).count()

    return render_user_detail(
        request,
        user,
        "users/detail/messages.html",
        {
            "sent_messages": sent_messages,
            "received_messages": received_messages,
            **get_pagination_context(request, messages),
        },
    )
示例#3
0
def get_teacher_data(tid,st,et):
    teacher = get_object_or_404(Teacher,id=tid)
    user = teacher.user
    tiles = Tile.objects.filter(creator=user)
    activies = Activity.objects.filter(creator=user)
    smses = SmsSend.objects.filter(sender=user)
    messages = MessageRecipient.objects.filter(message__sender=user)
    if st:
        messages = messages.filter(message__sent_at__gte=st)
        tiles = tiles.filter(start_time__gte=st)
        activies = activies.filter(start_time__gte=st)
        smses = smses.filter(send_date__gte=st)
    if et:
        messages = messages.filter(message__sent_at__lt=et)
        tiles = tiles.filter(start_time__lt=et)
        activies = activies.filter(start_time__lt=et)
        smses = smses.filter(send_date__lt=et)
        
    tile_num = tiles.exclude(new_category__parent_id=1130).exclude(category_id=9).count()
    active_num = activies.count()
    record_num = tiles.filter(new_category__parent_id=1130).count()
    sms = SmsSend.objects.filter(sender=user).count()
    msg = messages.filter(message__sender=user).count()
    ctx = {'teacher':teacher,'tile_num':tile_num,'active_num':active_num,'record_num':record_num,\
           'sms':sms,'msg':msg}
    return ctx
示例#4
0
def msg_inbox(request, filterby='all',
              template_name='privatemsg/inbox.html',
              extra_context=None):
    """
    Display the inbox for the current user.
    :param request: The current request.
    :param filterby: The selected filtering option.
    :param template_name: The template name to be used.
    :param extra_context: Any extra context for the template.
    :return: TemplateResponse
    """

    # Get the messages list for the current user
    messages = PrivateMessage.objects.inbox_for(request.user).select_related('parent_msg', 'sender')

    # Filter the list
    if filterby == 'read':
        messages = messages.filter(read_at__isnull=False)
    elif filterby == 'unread':
        messages = messages.filter(read_at__isnull=True)

    # Messages list pagination
    paginator, page = paginate(messages, request, NB_PRIVATE_MSG_PER_PAGE)

    # Render the template
    context = {
        'title': _('Private messages inbox'),
        'filter_by': filterby
    }
    update_context_for_pagination(context, 'private_messages', request, paginator, page)
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
示例#5
0
def message(request, message_id):
    user = request.user
    messages = Message.objects.for_user_or_author(user).filter(id=message_id)
    if len(messages) != 1:
        return HttpResponseForbidden("Not allowed")
    hide_thread = request.GET.get('hide_thread')
    message_thread = Message.objects.thread(messages[0], user)
    message_thread_length = message_thread.count()
    if not hide_thread:
        messages = message_thread

    reply = request.GET.get('reply')

    if reply:
        try:
            reply_msg = Message.objects.get(pk=reply, user=user)
            reply_msg.read = True
            reply_msg.save()
            extra_context['reply_msg'] = reply_msg
        except (Message.DoesNotExist, ValueError):
            pass

    messages.filter(user=user).update(read=True)

    extra_context = {
        'send_message_form':
        SendMessageForm(request.user, auto_id='message_form_id_%s'),
        'messages_display':
        True,
        'user_info':
        user,
        'subject':
        messages[0].subject,
        'mid':
        message_id,
        'thread_length':
        message_thread_length
    }

    response = object_list(request,
                           queryset=messages,
                           paginate_by=MESSAGES_ON_PAGE,
                           template_name='messages/message.html',
                           template_object_name='message',
                           extra_context=extra_context)
    try:
        last_message = messages[0]
        max_age = 60 * 60 * 24 * 365
        expires = cookie_date(time.time() + max_age)
        response.set_cookie(Message.hide_cookie_name, last_message.pk, max_age,
                            expires)
    except Message.DoesNotExist:
        pass
    return response
示例#6
0
def get_student_data(sid,st=None,et=None):
    student = get_object_or_404(Student,id=sid)
    user = student.user
    tile_content_type = ContentType.objects.get_by_natural_key("kinger", "tile")
    acc_logs = Access_log.objects.filter(user=user,type=2)
    comments = Comment.objects.filter(user=user,content_type=tile_content_type)
    daily_vistors = DailyRecordVisitor.objects.filter(visitor=user)
    sms_replaies = SmsReplay.objects.filter(sender=user)
    messages = MessageRecipient.objects.filter(message__sender=user)
    tiles = Tile.objects.filter(creator=user)
    if st:
        acc_logs = acc_logs.filter(send_time__gte=st)
        comments = comments.filter(submit_date__gte=st)
        daily_vistors = daily_vistors.filter(visit_time__gte=st)
        sms_replaies = sms_replaies.filter(target__deal_date__gte=st)
        messages = messages.filter(message__sent_at__gte=st)
        tiles = tiles.filter(start_time__gte=st)
    if et:
        acc_logs = acc_logs.filter(send_time__lt=et)
        comments = comments.filter(submit_date__lt=et)
        daily_vistors = daily_vistors.filter(visit_time__lt=et)
        sms_replaies = sms_replaies.filter(target__deal_date__lt=et)
        messages = messages.filter(message__sent_at__lt=et)
        tiles = tiles.filter(start_time__lt=et)
        
    web_num = acc_logs.exclude(url__startswith='/api').count()
    api_num = acc_logs.filter(url__startswith='/api').count()
    img_num = DailyRecordVisitor.objects.tile_img_count(user,stime=st,etime=et,type='img')
    word_num = DailyRecordVisitor.objects.tile_img_count(user,stime=st,etime=et,type='word')
    record_num = DailyRecordVisitor.objects.tile_img_count(user,stime=st,etime=et,type='record')
    
    word_comments = 0
    img_comments = 0
    for c in comments:
        try:
            if c.content_object.new_type_id in [1,2]:
                img_comments += 1
            if c.content_object.new_type_id == 4:
                word_comments += 1
        except:
            pass

    content_type = ContentType.objects.get_for_model(Activity)
    active_num = daily_vistors.filter(target_content_type=content_type).count()
    sms = sms_replaies.count()
    msg = messages.count()
    imgs = tiles.filter(new_type_id=1).count()
    words = tiles.filter(new_type_id=4).count()
    ctx = {'student':student,'web_num':web_num,'active_num':active_num,'record_num':record_num,\
           'sms':sms,'msg':msg,'api_num':api_num,'img_num':img_num,'word_comments':word_comments,\
           'img_comments':img_comments,'word_num':word_num,'img_num':img_num,'imgs':imgs,'words':words}
    return ctx
示例#7
0
文件: views.py 项目: sfu-fas/coursys
def view(request, reminder_slug):
    reminder, _ = _get_reminder_or_404(request, reminder_slug)
    messages = ReminderMessage.objects.filter(reminder=reminder).select_related('person')
    future_messages = messages.filter(sent=False).order_by('date', 'person')
    sent_messages = messages.filter(sent=True).order_by('sent_at', 'person')

    context = {
        'reminder': reminder,
        'future_messages': future_messages,
        'sent_messages': sent_messages,
        'future_days': MESSAGE_EARLY_CREATION,
        'sent_days': HISTORY_RETENTION,
    }
    return render(request, 'reminders/view.html', context)
示例#8
0
def view(request, reminder_slug):
    reminder, _ = _get_reminder_or_404(request, reminder_slug)
    messages = ReminderMessage.objects.filter(
        reminder=reminder).select_related('person')
    future_messages = messages.filter(sent=False).order_by('date', 'person')
    sent_messages = messages.filter(sent=True).order_by('sent_at', 'person')

    context = {
        'reminder': reminder,
        'future_messages': future_messages,
        'sent_messages': sent_messages,
        'future_days': MESSAGE_EARLY_CREATION,
        'sent_days': HISTORY_RETENTION,
    }
    return render(request, 'reminders/view.html', context)
示例#9
0
def message(request, index):
    messages = Message.objects.all()
    message = Message.objects.get(id=index)
    message.read = True
    message.save()
    fileExt = os.path.splitext(message.attachment.name)[1][1:]
    template = loader.get_template("message.html")
    inboxCount = messages.filter(receiver=request.user).count()
    sentCount = messages.filter(sender=request.user).count()
    context = {
        'message': message,
        'user': request.user,
        'inboxCount': inboxCount,
        'sentCount': sentCount,
        'fileExt': fileExt
    }
    return HttpResponse(template.render(context, request))
示例#10
0
def message_record(request,template_name="oa/message_record.html"):
    """发信记录列表"""
    user = request.user
    messages = Message.objects.filter(sender=user,sender_deleted_at__isnull=True)
    ty = int(request.GET.get("ty",-1))
    if ty == 0 or ty == 1:
        messages = messages.filter(type=ty)
 
    ctx = {'message_list':messages,'user':request.user,'ty':ty}
    return render(request,template_name,ctx)
示例#11
0
def mailbox(request,site_id,template_name="oa/mailbox_list.html"):
    """站点管理园长信箱列表"""
    site = get_object_or_404(WebSite,id=site_id)
    helpers.set_website_visit(request.user,site)
#    school = get_schools(request.user)[0]
#    user=school.header
    messages = MailBox.objects.filter(site=site).order_by('-ctime')
    ty = int(request.GET.get("ty",-1))
    if ty != -1:
        messages = messages.filter(is_read=ty)
    ctx = {'message_list':messages,'ty':ty,'site':site}
    return render(request,template_name,ctx)
示例#12
0
def messages(request):
    messages = Message.objects.all()
    inboxCount = messages.filter(receiver=request.user).count()
    sentCount = messages.filter(sender=request.user).count()
    query = request.GET.get("q")
    if query:
        if query == "inbox":
            messages = messages.filter(
                receiver=request.user).order_by('-created_at')
        elif query == "sent":
            messages = messages.filter(
                sender=request.user).order_by('-created_at')
        else:
            messages = messages.filter(
                Q(sender__username__icontains=query)
                | Q(receiver__username__icontains=query)
                | Q(msg_content__icontains=query)).order_by('-created_at')
    else:
        messages = messages.filter(receiver=request.user)
    template = loader.get_template("messages.html")
    context = {
        'messages': messages,
        'user': request.user,
        'inboxCount': inboxCount,
        'sentCount': sentCount
    }
    return HttpResponse(template.render(context, request))
示例#13
0
def control_messages(request, filter, category):
    """ control panel - list messages """
    if not request.user.is_superuser:
        return HttpResponseForbidden("Admin login required")
    if filter == 'now':
        messages = Message.objects.filter(
            end_date__gte=timezone.now()).order_by('-pk')
        filter_label = 'Nykyiset'
    elif filter == 'new':
        messages = Message.objects.filter(start_date__gte=timezone.now() -
                                          timedelta(days=7)).order_by('-pk')
        filter_label = 'Uudet'
    elif filter == 'upcoming':
        messages = Message.objects.filter(
            start_date__gte=timezone.now()).order_by('-pk')
        filter_label = 'Tulevat'
    elif filter == 'old':
        messages = Message.objects.filter(
            end_date__lt=timezone.now()).order_by('-pk')
        filter_label = 'Menneet'
    else:
        messages = Message.objects.all().order_by('-pk')
        filter_label = 'Kaikki'

    categories = Category.objects.filter(
        messages__in=messages).distinct().order_by('order')

    for c in categories:
        if str(c.pk) == category:
            messages = messages.filter(category=c)

    paginator = Paginator(messages, 100)  # 100 messages per page
    page = request.GET.get('page')
    try:
        messages = paginator.page(page)
    except PageNotAnInteger:
        messages = paginator.page(1)
    except EmptyPage:
        messages = paginator.page(paginator.num_pages)
    queries_without_page = request.GET.copy()
    if 'page' in queries_without_page.keys():
        del queries_without_page['page']

    return render(
        request, 'control/messages.html', {
            'messages': messages,
            'categories': categories,
            'filter': filter,
            'filter_label': filter_label,
        })
示例#14
0
def latest_notification(request):
    try:
        time_threshold = datetime.now() - timedelta(seconds=30)
        messages = Notification.objects.filter(date_posted__gt=time_threshold)
        messages = messages.filter(user=request.user)
        messages = messages.order_by('date_posted')
        messages = serializers.serialize('json', messages)
        msg_count = Notification.objects.filter(user=request.user,
                                                read=False).count()
        # print(unread_msg_count)
        response = {'messages': messages, 'msg_count': msg_count}

    except:
        response = serializers.serialize('json', [])
    return HttpResponse(json.dumps(response))
示例#15
0
def patient_case(request, case_id):
    if Case.objects.filter(id=case_id):
        case = Case.objects.get(id=case_id)
        appointment = Appointment.objects.filter(case=case).filter(is_current=True)[0]
        patient = appointment.patient
        messages = Message.objects.filter(case=case)
        unread = messages.filter(is_read = False)
        for un in unread:
            un.is_read = True
              
        return render_to_response('referring/case-view.htm', {'case':case, 'appointment':appointment, 'patient':patient, 'messages':messages},
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('error.htm', {'error':"No such Case"},
                                  context_instance=RequestContext(request))
示例#16
0
def latest_chat_messages(request, pk):
    if request.user.is_authenticated:
        try:
            touser = User.objects.get(id=pk)
            time_threshold = datetime.now() - timedelta(minutes=1)
            messages = Messages.objects.filter(
                date_postdate__gt=time_threshold)
            messages = messages.filter(
                Q(msg_from=request.user, msg_to=touser)
                | Q(msg_from=touser, msg_to=request.user))
            messages = messages.order_by('date_postdate')
            response = serializers.serialize('json', messages)
        except:
            response = serializers.serialize('json', [])
        return HttpResponse(response, content_type='application/json')
    else:
        response = serializers.serialize('json', {})
        return HttpResponse(response, content_type='application/json')
示例#17
0
def user_messages(request):
    context = {}
    try:
        user = UserAccount.objects.get(user=request.user)
    except Exception as e:
        print "e", e
        user = None
    if request.method == 'POST':
        rp = request.POST
        print "rp: ", rp
        message_obj = MessageCenter.objects.create(subject=rp.get('subject'),
                                                   message=rp.get('message'),
                                                   user=request.user,
                                                   new=True)
        message_obj.save()
        comment_obj = MessageCenterComment.objects.create(
            message=rp.get('message'),
            message_obj=message_obj,
            user=request.user)
        messages.success(request, 'Message sent successfully')
        return redirect(request.META['HTTP_REFERER'])
    else:
        context = {}
        messages = MessageCenter.objects.filter(user=request.user)
        query = request.GET.get('q')
        if query:
            new_messages = messages.filter(
                (Q(subject__icontains=query) | Q(message__icontains=query)),
                new=True)
            replied_messages = messages.filter(
                (Q(subject__icontains=query) | Q(message__icontains=query)),
                replied=True)
            archived_messages = messages.filter(
                (Q(subject__icontains=query) | Q(message__icontains=query)),
                archive=True)
            #deleted_messages = messages.filter((Q(subject__icontains=query) | Q(message__icontains=query)), deleted=True)
        else:
            new_messages = messages.filter(new=True)
            replied_messages = messages.filter(replied=True)
            archived_messages = messages.filter(archive=True)
            #deleted_messages = messages.filter(deleted=True)
        comment_form = MessageCenterCommentForm()
        context['comment_form'] = comment_form
        context['new_messages'] = new_messages
        context['replied_messages'] = replied_messages
        context['archived_messages'] = archived_messages
        context['new_count'] = new_messages.count()
        context['replied_count'] = replied_messages.count()
        context['archived_count'] = archived_messages.count()
        context['user'] = user
        template_name = 'general/user_messages.html'
        return render(request, template_name, context)
示例#18
0
def get_patient_stats_detail_context(report_date, patient_id):
    """

    """
    context = {}
    days = get_day_of_month(report_date.year, report_date.month, -1).day
    num_days_in_report_month = days
    datetime_end_month = datetime.datetime(report_date.year, report_date.month,
                                           num_days_in_report_month, 23, 59)
    datetime_start_month = datetime.datetime(report_date.year,
                                             report_date.month, 01, 0, 0)

    patient = get_object_or_404(Patient, id=patient_id)
    context["daily_doses"] = patient.daily_doses

    context["patient"] = patient
    if not report_date:
        report_date = datetime.now()

    wp_usage_rows = []
    for day in range(1, days + 1):
        row_date = datetime.date(report_date.year, report_date.month, day)
        if is_patient_out_of_date_range(patient, row_date):
            continue

        row = []
        row.append(row_date)
        msg_count = patient.wisepill_messages.filter(
            timestamp__year=row_date.year,
            timestamp__month=row_date.month,
            timestamp__day=row_date.day).count()
        row.append(msg_count)
        wp_usage_rows.append(row)

    pill_count_data = {}
    pills_missed_data = {}
    pill_count_data["patient_id"] = patient.subject_number
    pills_missed = patient.pillsmissed_set.filter(
        date__range=(datetime_start_month,
                     datetime_end_month)).order_by('-date')[:4]
    weeks = []
    for pm in pills_missed:
        week_start = pm.date - datetime.timedelta(days=7)
        week_end = pm.date
        num_missed = pm.num_missed
        weeks.append({
            'pills_missed': num_missed,
            'week_start': week_start,
            'week_end': week_end,
            'received_on': pm.date
        })

    pills_missed_data[patient] = weeks

    pm_weekly_aggregate = []
    num_weeks_in_report_month = num_days_in_report_month / 7
    for week in range(0, num_weeks_in_report_month + 1):
        week_start = (datetime.date(report_date.year, report_date.month, 1) +
                      datetime.timedelta(days=week * 7))
        week_end = week_start + datetime.timedelta(days=7)
        pm_week_data = {}
        if is_patient_out_of_date_range(patient, week_start, week_end):
            continue

        pills_missed_set = patient.pillsmissed_set.filter(
            date__gt=week_start, date__lt=week_end,
            source=1)  # source = 1 means SMS
        if len(pills_missed_set) > 0:
            pills_missed_week = pills_missed_set.aggregate(
                Sum('num_missed'))["num_missed__sum"]
        else:
            pills_missed_week = "No Response/No Query"

        pm_week_data["sum"] = pills_missed_week
        pm_week_data["week_start"] = week_start
        pm_week_data["week_end"] = week_end
        pm_weekly_aggregate.append(pm_week_data)

    patient_connections = patient.contact.connection_set.all()
    messages = Message.objects.filter(connection__in=patient_connections)

    messages = messages.exclude(text__contains='start tree').exclude(
        text__contains='TimeOut')  #exclude internal messages
    messages = messages.filter(
        date__range=(datetime_start_month, datetime_end_month)).order_by(
            '-date')  #stick to the report month

    reminders = Reminder.objects.all()

    context["pat_messages"] = messages
    context["wp_usage_rows"] = wp_usage_rows
    context["pm_weeks"] = pills_missed_data
    context["pm_weekly"] = pm_weekly_aggregate
    return context
示例#19
0
def ureporter_profile(request, connection_pk):
    from script.models import ScriptSession, ScriptResponse, Script

    connection = get_object_or_404(Connection, pk=connection_pk)
    session = ScriptSession.objects.filter(connection__pk=connection_pk)
    messages = Message.objects.filter(connection=connection).order_by('-date')
    contact=connection.contact
    if contact:
        #get the proxy
        contact = Ureporter.objects.get(pk=connection.contact.pk)

    reporter_form = EditReporterForm(instance=contact)
    total_outgoing = messages.filter(direction='O',
                                     connection__pk=connection_pk).count()
    total_incoming = messages.filter(direction='I',
                                     connection__pk=connection_pk).count()
    try:
        response_rate = contact.responses.values_list('poll').distinct().count() * 100 / float(Poll.objects.filter(contacts=contact).distinct().count())
    except (ZeroDivisionError, ValueError):
        response_rate = None
#    gr_poll = Poll.objects.get(pk=121)
    gr_poll = Script.objects.get(slug="autoreg_en").steps.get(order=1).poll
    how_did_u_hear = None
    if session:
        try:
            how_did_u_hear = \
                session[0].responses.filter(response__poll=gr_poll)[0].response.message.text
        except (ScriptResponse.DoesNotExist, IndexError):
            how_did_u_hear = 'N/A'
    if request.GET.get('download', None):
        data = []
        data = messages.values_list('text', 'direction', 'date',
                                    'connection__contact__reporting_location__name').iterator()
        headers = ['Message', 'Direction', 'Date', 'District']

        return ExcelResponse(data=data, headers=headers)
    columns = [
               ('Message', True, 'text', SimpleSorter()),
               ('connection', True, 'connection', SimpleSorter()),
               ('Date', True, 'date', SimpleSorter()),
               ('Direction', True, 'direction', SimpleSorter())
               ]

    # hack hack send the reply message by hacking the sendmessage form
    if request.method == 'POST' :
        if not request.POST.get('text', None) == u'' and request.POST.get('action') == u'ureport.forms.ReplyTextForm' and not request.POST.get('page_action',None):
            rep_form=ReplyTextForm(request=request)
            Message.objects.create(
                connection=connection, direction='O'
                , status='Q',
                text=request.POST.get('text'))
            return generic(
                request,
                model=Message,
                queryset=messages,
                total_outgoing=total_outgoing,
                total_incoming=total_incoming,
                response_rate=response_rate,
                how_did_u_hear=how_did_u_hear,
                contact=contact,
                reporter_form=reporter_form,
                objects_per_page=20,
                status_message='Message sent',
                status_message_type='success',
                results_title='Message History',
                selectable=False,
                partial_row='ureport/partials/messages/message_history_row.html',
                base_template='ureport/message_history_base.html',
                action_forms=[ReplyTextForm],
                columns=columns,
                sort_column='date',
                sort_ascending=False,
            )

    return generic(
        request,
        model=Message,
        queryset=messages,
        contact=contact,
        total_outgoing=total_outgoing,
        total_incoming=total_incoming,
        response_rate=response_rate,
        objects_per_page=20,
        how_did_u_hear=how_did_u_hear,
        reporter_form=reporter_form,
        results_title='Message History',
        selectable=False,
        partial_row='ureport/partials/messages/message_history_row.html',
        base_template='ureport/message_history_base.html',
        action_forms=[ReplyTextForm],
        columns=columns,
        sort_column='date',
        sort_ascending=False,
    )
示例#20
0
def compose(request,
            message_id=None,
            template_name='usuario/mensajes/redactar.html',
            success_url=None,
            recipient_filter=None):
    """
    Displays and handles the ``form_class`` form to compose new messages.
    Required Arguments: None
    Optional Arguments:
        ``recipient``: username of a `django.contrib.auth` User, who should
                       receive the message, optionally multiple usernames
                       could be separated by a '+'
        ``form_class``: the form-class to use
        ``template_name``: the template to use
        ``success_url``: where to redirect after successfull submission
    """
    form_errors = ''

    (tipo_mensaje, expresion) = msj_expresion('alert')
    mensaje = u'El mensaje será guardado como borrador automáticamente cada 5 minutos'
    message = None
    if request.method == "POST":
        form = ComposeForm(request.POST)
        cuerpo = ''
        valido = form.is_valid()

        # Revisar si hay quien apruebe en el departamento del redactor
        jefe = Destinatarios.objects.filter(
            usuarios__user__userprofile__persona__cargo_principal__dependencia=
            request.user.profile.persona.cargo_principal.dependencia,
            usuarios__user__userprofile__persona__cargo_principal__cargo=request
            .user.profile.persona.cargo_principal.dependencia.cargo_max)
        if not jefe.exists():
            mensaje = u'Este memo no puede ser enviado ni aprobado porque no existe un jefe de departamento en %s' % (
                request.user.profile.persona.cargo_principal.dependencia)
            valido = False
        else:
            jefe = jefe[0]

        if valido:
            if request.POST.has_key('recipient'):
                destinatarios = form.cleaned_data['recipient']
                destinos = []
                for dest in destinatarios:
                    if dest.usuarios == None:
                        destinatarios2 = Destinatarios.objects.filter(
                            usuarios__persona__cargo_principal__cargo=dest.
                            grupos)
                        for dest2 in destinatarios2:
                            if not dest2 in form.cleaned_data['recipient']:
                                destinos.append(dest2)
                    else:
                        destinos.append(dest)
                destinatarios = destinos
            else:
                destinatarios = None

            if request.POST.has_key('con_copia'):
                con_copia = form.cleaned_data['con_copia']
            else:
                con_copia = None

            if request.POST.has_key('archivo'):
                archivo = request.POST['archivo']
            else:
                archivo = None

            sender = Destinatarios.objects.get(usuarios__user=request.user)

            # Revisar si se envió el formulario como borrador
            borrador = False
            enviar = False
            plantilla = False
            if request.POST.has_key('borrador'):
                borrador = True
            if request.POST.has_key('enviar'):
                enviar = True
            if request.POST.has_key('plantilla'):
                plantilla = True

            if enviar:
                mensaje = u'Mensaje enviado exitosamente'
            elif borrador:
                mensaje = u'Borrador guardado exitosamente'

            elif plantilla:
                print "Aún no programado"
                mensaje = u'Plantilla guardada exitosamente'

            # Por cada destinatario, enviar el memo, generar un log y enviar correo si está en la opción de envío
            if message_id:
                msjs_guardados = Message.objects.get(id=message_id)
                body = request.POST['body']
                subject = request.POST['subject']
                num_ident = msjs_guardados.num_ident
                codigo = msjs_guardados.codigo

                # Enlazar los destinatarios con los con_copia
                destinos = []

                if destinatarios:
                    for dest in destinatarios:
                        destinos.append(dest)
                if con_copia:
                    for dest_cc in con_copia:
                        destinos.append(dest_cc)
                '''
                if not destinatarios or not con_copia:
                    message = Message.objects.get(id=message_id)
                    message.body = body
                    message.subject = subject
                    message.archivo = archivo
                    message.borrador = borrador
                    message.save()
                '''

                msjs_guardados = Message.objects.filter(codigo=codigo)
                for dest in destinos:
                    # Si el destinatario no está en el campo 'recipient', entonces está en 'con_copia'
                    if not dest in destinatarios:
                        cc = True
                    else:
                        cc = False

                    # Si con ese codigo, están los mismos destinatarios, entonces se guarda la información
                    if msjs_guardados.filter(recipient=dest).exists():
                        message = Message.objects.get(recipient=dest,
                                                      codigo=codigo)
                        message.recipient = dest
                        message.body = body
                        message.subject = subject
                        message.archivo = archivo
                        message.borrador = borrador
                        message.con_copia = cc

                        message.save()

                    # Si no existe, se crea
                    else:
                        message = crear_mensaje(
                            destino=dest,
                            envio=sender,
                            asunto=subject,
                            cc=cc,
                            cuerpo=body,
                            num_ident=msjs_guardados[0].num_ident,
                            codigo=msjs_guardados[0].codigo,
                            borrador=borrador,
                            archivo=archivo,
                        )
                # Eliminar memos cuyos destinatarios hayan sido excluidos
                if destinos:
                    msjs_guardados = msjs_guardados.exclude(
                        recipient__in=destinos)
                    if msjs_guardados.exists():
                        msjs_guardados.delete()

            else:
                fecha_actual = datetime.datetime.today()
                mensajes = Message.objects.filter(
                    sender__usuarios__user__userprofile__persona__cargo_principal__dependencia
                    =sender.usuarios.user.profile.persona.cargo_principal.
                    dependencia,
                    sent_at__year=fecha_actual.year,
                    sent_at__month=fecha_actual.month)
                num_ident = mensajes.count() + 1

                # El identificador se genera a partir del id del memo, del jefe de departamento y del minuto, segundo y microsegundo actual
                identificador = '%s%s' % (Message.objects.all().count(),
                                          jefe.id)

                codigo = ''
                for ident in identificador:
                    codigo = codigo + str(ord(ident))
                codigo = codigo + str(datetime.datetime.today().microsecond)

                if destinatarios:
                    for destino in destinatarios:
                        message = crear_mensaje(
                            destino=destino,
                            envio=sender,
                            asunto=request.POST['subject'],
                            cuerpo=request.POST['body'],
                            cc=False,
                            num_ident=num_ident,
                            codigo=codigo,
                            borrador=borrador,
                            archivo=archivo,
                        )
                elif con_copia:
                    for destino_cc in con_copia:
                        message = crear_mensaje(
                            destino=destino_cc,
                            envio=sender,
                            asunto=request.POST['subject'],
                            cuerpo=request.POST['body'],
                            cc=True,
                            num_ident=num_ident,
                            codigo=codigo,
                            borrador=borrador,
                            archivo=archivo,
                        )
                else:
                    message = crear_mensaje(
                        destino=None,
                        envio=sender,
                        asunto=request.POST['subject'],
                        cuerpo=request.POST['body'],
                        cc=False,
                        num_ident=num_ident,
                        codigo=codigo,
                        borrador=borrador,
                        archivo=archivo,
                    )
            # ¿Necesita el jefe recibir directamente el memorándum?
            '''
            if enviar and not destinatarios.__contains__(jefe):
                destino = jefe,
                message = crear_mensaje(
                            destino=destino, 
                            envio=sender, 
                            asunto=request.POST['subject'], 
                            cuerpo=request.POST['body'], 
                            cc=False,
                            num_ident=num_ident,
                            codigo=codigo,
                            borrador=borrador,
                            archivo=archivo,
                            )
            '''

            (tipo_mensaje, expresion) = msj_expresion('success')

            if success_url is None:
                success_url = reverse('messages_inbox')
            if request.GET.has_key('next'):
                success_url = request.GET['next']

        form.body = request.POST['body']
        if form.errors or not valido:
            (tipo_mensaje, expresion) = msj_expresion('error')
            label = ""
            if form.errors.keys()[0] == 'subject':
                label = "Asunto"
            elif form.errors.keys()[0] == 'recipient':
                label = "Destinatarios"
            elif form.errors.keys()[0] == 'body':
                label = "Texto"

            if not label == "":
                mensaje = label + ': ' + form.errors.values()[0][0]

            if form.errors.has_key('__all__'):
                mensaje = form.errors['__all__'].as_text().split('* ')[1]

        if form.errors or not valido:
            return render_to_response(template_name, {
                'tipo': 'Redactar',
                'tipo_mensaje': tipo_mensaje,
                'mensaje': mensaje,
                'message': message,
                'expresion': expresion,
                'request': request,
                'form': form,
            },
                                      context_instance=RequestContext(request))

        elif request.POST.has_key('borrador'):
            return HttpResponseRedirect('/redactar/%s/' % (message.id))

        return bandeja(request,
                       tipo_bandeja='enviados',
                       expresion=expresion,
                       tipo_mensaje=tipo_mensaje,
                       mensaje=mensaje)
    else:
        form = ComposeForm()
        if message_id:
            message = Message.objects.get(id=message_id)
            if message.status.nombre == 'Aprobado':
                (tipo_mensaje, expresion) = msj_expresion('error')
                mensaje = u'Ese mensaje ya ha sido aprobado. No puede ser editado'
                return bandeja(request,
                               tipo_bandeja='enviados',
                               expresion=expresion,
                               tipo_mensaje=tipo_mensaje,
                               mensaje=mensaje)
            messages = Message.objects.filter(codigo=message.codigo)
            messages_cc = messages.filter(con_copia=True)
            messages = messages.filter(con_copia=False)
            dest_cc = []
            dest = []
            if messages_cc.exists():
                for msj in messages_cc:
                    dest_cc.append(msj.recipient)

            if messages.exists():
                for msj in messages:
                    dest.append(msj.recipient)

            form.fields['recipient'].initial = dest
            form.fields['body'].initial = message.body
            form.fields['con_copia'].initial = dest_cc
            form.fields['subject'].initial = message.subject
            form.fields['archivo'].initial = message.archivo

        else:
            persona = u"%s.</br /> %s de %s" % (
                request.user.profile.persona,
                request.user.profile.persona.cargo_principal.cargo,
                request.user.profile.persona.cargo_principal.dependencia)
            form.fields[
                'body'].initial = u"<br /><br />Sin otro particular al cual hacer referencia, se despide. </br /></br /><b>Atentamente,</br /> %s</b>" % (
                    persona.upper())
    return render_to_response(template_name, {
        'tipo': 'Redactar',
        'tipo_mensaje': tipo_mensaje,
        'mensaje': mensaje,
        'message': message,
        'expresion': expresion,
        'request': request,
        'form': form,
    },
                              context_instance=RequestContext(request))
示例#21
0
文件: views.py 项目: dimagi/aremind
def get_patient_stats_detail_context(report_date, patient_id):
    """

    """
    context = {}
    days = get_day_of_month(report_date.year,report_date.month,-1).day
    num_days_in_report_month = days
    datetime_end_month = datetime.datetime(report_date.year,report_date.month,num_days_in_report_month,23,59)
    datetime_start_month = datetime.datetime(report_date.year, report_date.month,01,0,0)

    patient = get_object_or_404(Patient, id=patient_id)
    context["daily_doses"] = patient.daily_doses

    context["patient"] = patient
    if not report_date:
        report_date = datetime.now()

    wp_usage_rows = []
    for day in range(1,days+1):
        row_date = datetime.date(report_date.year,report_date.month, day)
        if is_patient_out_of_date_range(patient, row_date):
            continue
        
        row = []
        row.append(row_date)
        msg_count = patient.wisepill_messages.filter(timestamp__year=row_date.year,timestamp__month=row_date.month,timestamp__day=row_date.day).count()
        row.append(msg_count)
        wp_usage_rows.append(row)

    pill_count_data = {}
    pills_missed_data = {}
    pill_count_data["patient_id"] = patient.subject_number
    pills_missed = patient.pillsmissed_set.filter(date__range=(datetime_start_month,datetime_end_month)).order_by('-date')[:4]
    weeks = []
    for pm in pills_missed:
        week_start = pm.date-datetime.timedelta(days=7)
        week_end = pm.date
        num_missed = pm.num_missed
        weeks.append({
            'pills_missed': num_missed,
            'week_start': week_start,
            'week_end': week_end,
            'received_on': pm.date
        })

    pills_missed_data[patient] = weeks

    pm_weekly_aggregate = []
    num_weeks_in_report_month = num_days_in_report_month / 7
    for week in range(0,num_weeks_in_report_month + 1):
        week_start = (datetime.date(report_date.year,report_date.month,1) + datetime.timedelta(days=week*7))
        week_end = week_start + datetime.timedelta(days=7)
        pm_week_data = {}
        if is_patient_out_of_date_range(patient,week_start,week_end):
            continue

        pills_missed_set = patient.pillsmissed_set.filter(date__gt=week_start, date__lt=week_end, source=1) # source = 1 means SMS
        if len(pills_missed_set) > 0:
            pills_missed_week = pills_missed_set.aggregate(Sum('num_missed'))["num_missed__sum"]
        else:
            pills_missed_week = "No Response/No Query"


        pm_week_data["sum"] = pills_missed_week
        pm_week_data["week_start"] = week_start
        pm_week_data["week_end"] = week_end
        pm_weekly_aggregate.append(pm_week_data)



    patient_connections = patient.contact.connection_set.all()
    messages = Message.objects.filter(connection__in=patient_connections)

    messages = messages.exclude(text__contains='start tree').exclude(text__contains='TimeOut') #exclude internal messages
    messages = messages.filter(date__range=(datetime_start_month, datetime_end_month)).order_by('-date') #stick to the report month

    reminders = Reminder.objects.all()

    context["pat_messages"] = messages
    context["wp_usage_rows"] = wp_usage_rows
    context["pm_weeks"] = pills_missed_data
    context["pm_weekly"] = pm_weekly_aggregate
    return context
示例#22
0
文件: views.py 项目: sunlightlabs/lfr
 def get_context_data(self, **kwargs):
     ctx = super().get_context_data(**kwargs)
     messages = ctx['object_list']
     messages = messages.filter(email=self.request.user.email)
     ctx['object_list'] = messages
     return ctx
示例#23
0
文件: views.py 项目: Axelio/Umail
def compose(request, message_id=None,
        template_name='usuario/mensajes/redactar.html', success_url=None, recipient_filter=None):
    """
    Displays and handles the ``form_class`` form to compose new messages.
    Required Arguments: None
    Optional Arguments:
        ``recipient``: username of a `django.contrib.auth` User, who should
                       receive the message, optionally multiple usernames
                       could be separated by a '+'
        ``form_class``: the form-class to use
        ``template_name``: the template to use
        ``success_url``: where to redirect after successfull submission
    """
    form_errors = ''

    (tipo_mensaje, expresion) = msj_expresion('alert')
    mensaje = u'El mensaje será guardado como borrador automáticamente cada 5 minutos'
    message = None
    if request.method == "POST":
        form = ComposeForm(request.POST)
        cuerpo = ''
        valido = form.is_valid()

        # Revisar si hay quien apruebe en el departamento del redactor
        jefe = Destinatarios.objects.filter(usuarios__user__userprofile__persona__cargo_principal__dependencia = request.user.profile.persona.cargo_principal.dependencia, usuarios__user__userprofile__persona__cargo_principal__cargo = request.user.profile.persona.cargo_principal.dependencia.cargo_max)
        if not jefe.exists():
            mensaje = u'Este memo no puede ser enviado ni aprobado porque no existe un jefe de departamento en %s' %(request.user.profile.persona.cargo_principal.dependencia)
            valido = False
        else:
            jefe = jefe[0]

        if valido:
            if request.POST.has_key('recipient'):
                destinatarios = form.cleaned_data['recipient']
                destinos = []
                for dest in destinatarios:
                    if dest.usuarios == None:
                        destinatarios2 = Destinatarios.objects.filter(usuarios__persona__cargo_principal__cargo=dest.grupos)
                        for dest2 in destinatarios2:
                            if not dest2 in form.cleaned_data['recipient']:
                                destinos.append(dest2)
                    else:
                        destinos.append(dest)
                destinatarios = destinos
            else:
                destinatarios = None

            if request.POST.has_key('con_copia'):
                con_copia = form.cleaned_data['con_copia']
            else:
                con_copia = None

            if request.POST.has_key('archivo'):
                archivo = request.POST['archivo']
            else:
                archivo = None

            sender = Destinatarios.objects.get(usuarios__user=request.user)

            # Revisar si se envió el formulario como borrador
            borrador = False
            enviar = False
            plantilla = False
            if request.POST.has_key('borrador'):
                borrador = True
            if request.POST.has_key('enviar'):
                enviar = True
            if request.POST.has_key('plantilla'):
                plantilla = True

            if enviar:
                mensaje = u'Mensaje enviado exitosamente'
            elif borrador:
                mensaje = u'Borrador guardado exitosamente'

            elif plantilla:
                print "Aún no programado"
                mensaje = u'Plantilla guardada exitosamente'

            # Por cada destinatario, enviar el memo, generar un log y enviar correo si está en la opción de envío
            if message_id:
                msjs_guardados = Message.objects.get(id=message_id)
                body = request.POST['body']
                subject = request.POST['subject']
                num_ident = msjs_guardados.num_ident
                codigo = msjs_guardados.codigo

                # Enlazar los destinatarios con los con_copia
                destinos = []

                if destinatarios:
                    for dest in destinatarios:
                        destinos.append(dest)
                if con_copia:
                    for dest_cc in con_copia:
                        destinos.append(dest_cc)
                '''
                if not destinatarios or not con_copia:
                    message = Message.objects.get(id=message_id)
                    message.body = body
                    message.subject = subject
                    message.archivo = archivo
                    message.borrador = borrador
                    message.save()
                '''


                msjs_guardados = Message.objects.filter(codigo=codigo)
                for dest in destinos:
                    # Si el destinatario no está en el campo 'recipient', entonces está en 'con_copia'
                    if not dest in destinatarios:
                        cc = True
                    else:
                        cc = False

                    # Si con ese codigo, están los mismos destinatarios, entonces se guarda la información
                    if msjs_guardados.filter(recipient=dest).exists():
                        message = Message.objects.get(recipient=dest, codigo=codigo)
                        message.recipient = dest
                        message.body = body
                        message.subject = subject
                        message.archivo = archivo
                        message.borrador = borrador
                        message.con_copia = cc

                        message.save()

                    # Si no existe, se crea
                    else:
                        message = crear_mensaje(
                                    destino=dest, 
                                    envio=sender, 
                                    asunto=subject, 
                                    cc=cc,
                                    cuerpo=body, 
                                    num_ident=msjs_guardados[0].num_ident,
                                    codigo=msjs_guardados[0].codigo,
                                    borrador=borrador,
                                    archivo = archivo,
                                    )
                # Eliminar memos cuyos destinatarios hayan sido excluidos
                if destinos:
                    msjs_guardados = msjs_guardados.exclude(recipient__in=destinos)
                    if msjs_guardados.exists():
                        msjs_guardados.delete()

            else:
                fecha_actual = datetime.datetime.today()
                mensajes = Message.objects.filter(sender__usuarios__user__userprofile__persona__cargo_principal__dependencia=sender.usuarios.user.profile.persona.cargo_principal.dependencia, sent_at__year=fecha_actual.year, sent_at__month=fecha_actual.month)
                num_ident = mensajes.count() + 1

                # El identificador se genera a partir del id del memo, del jefe de departamento y del minuto, segundo y microsegundo actual
                identificador = '%s%s' %(Message.objects.all().count(), jefe.id)

                codigo = ''
                for ident in identificador:
                    codigo = codigo + str(ord(ident))
                codigo = codigo + str(datetime.datetime.today().microsecond)

                if destinatarios:
                    for destino in destinatarios:
                        message = crear_mensaje(
                                    destino=destino, 
                                    envio=sender, 
                                    asunto=request.POST['subject'], 
                                    cuerpo=request.POST['body'], 
                                    cc=False,
                                    num_ident=num_ident,
                                    codigo=codigo,
                                    borrador=borrador,
                                    archivo=archivo,
                                    )
                elif con_copia:
                    for destino_cc in con_copia:
                        message = crear_mensaje(
                                    destino=destino_cc, 
                                    envio=sender, 
                                    asunto=request.POST['subject'], 
                                    cuerpo=request.POST['body'], 
                                    cc=True,
                                    num_ident=num_ident,
                                    codigo=codigo,
                                    borrador=borrador,
                                    archivo=archivo,
                                    )
                else:
                    message = crear_mensaje(
                                destino=None, 
                                envio=sender, 
                                asunto=request.POST['subject'], 
                                cuerpo=request.POST['body'], 
                                cc=False,
                                num_ident=num_ident,
                                codigo=codigo,
                                borrador=borrador,
                                archivo=archivo,
                                )
            # ¿Necesita el jefe recibir directamente el memorándum?
            '''
            if enviar and not destinatarios.__contains__(jefe):
                destino = jefe,
                message = crear_mensaje(
                            destino=destino, 
                            envio=sender, 
                            asunto=request.POST['subject'], 
                            cuerpo=request.POST['body'], 
                            cc=False,
                            num_ident=num_ident,
                            codigo=codigo,
                            borrador=borrador,
                            archivo=archivo,
                            )
            '''
        
            (tipo_mensaje, expresion) = msj_expresion('success')
            
            if success_url is None:
                success_url = reverse('messages_inbox')
            if request.GET.has_key('next'):
                success_url = request.GET['next']

        form.body = request.POST['body']
        if form.errors or not valido:
            (tipo_mensaje, expresion) = msj_expresion('error')
            label = ""
            if form.errors.keys()[0] == 'subject':
                label = "Asunto"
            elif form.errors.keys()[0] == 'recipient':
                label = "Destinatarios"
            elif form.errors.keys()[0] == 'body':
                label = "Texto"

            if not label == "":
                mensaje =  label + ': ' + form.errors.values()[0][0]

            if form.errors.has_key('__all__'):
                mensaje = form.errors['__all__'].as_text().split('* ')[1]

        if form.errors or not valido:
            return render_to_response(template_name, {
                'tipo': 'Redactar',
                'tipo_mensaje':tipo_mensaje,
                'mensaje':mensaje,
                'message':message,
                'expresion':expresion,
                'request': request,
                'form': form,
            }, context_instance=RequestContext(request))

        elif request.POST.has_key('borrador'):
            return HttpResponseRedirect('/redactar/%s/' %(message.id))

        return bandeja(request, tipo_bandeja='enviados', expresion=expresion, tipo_mensaje=tipo_mensaje, mensaje=mensaje)
    else:
        form = ComposeForm()
        if message_id:
            message = Message.objects.get(id=message_id)
            if message.status.nombre == 'Aprobado':
                (tipo_mensaje, expresion) = msj_expresion('error')
                mensaje = u'Ese mensaje ya ha sido aprobado. No puede ser editado'
                return bandeja(request, tipo_bandeja='enviados', expresion=expresion, tipo_mensaje=tipo_mensaje, mensaje=mensaje)
            messages = Message.objects.filter(codigo=message.codigo)
            messages_cc = messages.filter(con_copia=True)
            messages = messages.filter(con_copia=False)
            dest_cc = []
            dest = []
            if messages_cc.exists():
                for msj in messages_cc:
                    dest_cc.append(msj.recipient)

            if messages.exists():
                for msj in messages:
                    dest.append(msj.recipient)

            form.fields['recipient'].initial = dest
            form.fields['body'].initial = message.body
            form.fields['con_copia'].initial = dest_cc
            form.fields['subject'].initial = message.subject
            form.fields['archivo'].initial = message.archivo
                
        else:
            persona = u"%s.</br /> %s de %s" %(request.user.profile.persona, request.user.profile.persona.cargo_principal.cargo, request.user.profile.persona.cargo_principal.dependencia)
            form.fields['body'].initial = u"<br /><br />Sin otro particular al cual hacer referencia, se despide. </br /></br /><b>Atentamente,</br /> %s</b>" %(persona.upper())
    return render_to_response(template_name, {
        'tipo': 'Redactar',
        'tipo_mensaje':tipo_mensaje,
        'mensaje':mensaje,
        'message':message,
        'expresion':expresion,
        'request': request,
        'form': form,
    }, context_instance=RequestContext(request))
示例#24
0
def ureporter_profile(request, connection_pk):
    from script.models import ScriptSession, ScriptResponse, Script

    connection = get_object_or_404(Connection, pk=connection_pk)
    session = ScriptSession.objects.filter(connection__pk=connection_pk)
    messages = Message.objects.filter(connection=connection).order_by('-date')
    contact = connection.contact
    if contact:
        #get the proxy
        contact = Ureporter.objects.get(pk=connection.contact.pk)

    reporter_form = EditReporterForm(instance=contact)
    total_outgoing = messages.filter(direction='O',
                                     connection__pk=connection_pk).count()
    total_incoming = messages.filter(direction='I',
                                     connection__pk=connection_pk).count()
    try:
        response_rate = contact.responses.values_list(
            'poll').distinct().count() * 100 / float(
                Poll.objects.filter(contacts=contact).distinct().count())
    except (ZeroDivisionError, ValueError):
        response_rate = None


#    gr_poll = Poll.objects.get(pk=121)
    gr_poll = Script.objects.get(slug="autoreg_en").steps.get(order=1).poll
    how_did_u_hear = None
    if session:
        try:
            how_did_u_hear = \
                session[0].responses.filter(response__poll=gr_poll)[0].response.message.text
        except (ScriptResponse.DoesNotExist, IndexError):
            how_did_u_hear = 'N/A'
    if request.GET.get('download', None):
        data = []
        data = messages.values_list(
            'text', 'direction', 'date',
            'connection__contact__reporting_location__name').iterator()
        headers = ['Message', 'Direction', 'Date', 'District']

        return ExcelResponse(data=data, headers=headers)
    columns = [('Message', True, 'text', SimpleSorter()),
               ('connection', True, 'connection', SimpleSorter()),
               ('Date', True, 'date', SimpleSorter()),
               ('Direction', True, 'direction', SimpleSorter())]

    # hack hack send the reply message by hacking the sendmessage form
    if request.method == 'POST':
        if not request.POST.get('text', None) == u'' and request.POST.get(
                'action'
        ) == u'ureport.forms.ReplyTextForm' and not request.POST.get(
                'page_action', None):
            rep_form = ReplyTextForm(request=request)
            Message.objects.create(connection=connection,
                                   direction='O',
                                   status='Q',
                                   text=request.POST.get('text'))
            return generic(
                request,
                model=Message,
                queryset=messages,
                total_outgoing=total_outgoing,
                total_incoming=total_incoming,
                response_rate=response_rate,
                how_did_u_hear=how_did_u_hear,
                contact=contact,
                reporter_form=reporter_form,
                objects_per_page=20,
                status_message='Message sent',
                status_message_type='success',
                results_title='Message History',
                selectable=False,
                partial_row=
                'ureport/partials/messages/message_history_row.html',
                base_template='ureport/message_history_base.html',
                action_forms=[ReplyTextForm],
                columns=columns,
                sort_column='date',
                sort_ascending=False,
            )

    return generic(
        request,
        model=Message,
        queryset=messages,
        contact=contact,
        total_outgoing=total_outgoing,
        total_incoming=total_incoming,
        response_rate=response_rate,
        objects_per_page=20,
        how_did_u_hear=how_did_u_hear,
        reporter_form=reporter_form,
        results_title='Message History',
        selectable=False,
        partial_row='ureport/partials/messages/message_history_row.html',
        base_template='ureport/message_history_base.html',
        action_forms=[ReplyTextForm],
        columns=columns,
        sort_column='date',
        sort_ascending=False,
    )
示例#25
0
def control_messages(request, filter, category):
    """Admin view - control messages.

    Messages can be edited and deleted in this view.

    Args:
        request: HttpRequest object from Django.
        filter: a string based on which to filter.
        category: message category.

    Returns:
        A Django TemplateResponse object that renders an html template.
    """

    if filter == "now":
        messages = Message.objects.filter(
            end_date__gte=timezone.now()).order_by("-pk")
        filter_label = _("Now")
    elif filter == "new":
        messages = Message.objects.filter(start_date__gte=timezone.now() -
                                          timedelta(days=7)).order_by("-pk")
        filter_label = _("New")
    elif filter == "upcoming":
        messages = Message.objects.filter(
            start_date__gte=timezone.now()).order_by("-pk")
        filter_label = _("Upcoming")
    elif filter == "old":
        messages = Message.objects.filter(
            end_date__lt=timezone.now()).order_by("-pk")
        filter_label = _("Old")
    else:
        messages = Message.objects.all().order_by("-pk")
        filter_label = _("All")

    categories = (Category.objects.filter(
        messages__in=messages).distinct().order_by("order"))

    for c in categories:
        if str(c.pk) == category:
            messages = messages.filter(category=c)

    paginator = Paginator(messages, 100)
    page = request.GET.get("page")
    try:
        messages = paginator.page(page)
    except PageNotAnInteger:
        messages = paginator.page(1)
    except EmptyPage:
        messages = paginator.page(paginator.num_pages)
    queries_without_page = request.GET.copy()
    if "page" in queries_without_page.keys():
        del queries_without_page["page"]

    return render(
        request,
        "control/messages.html",
        {
            "messages": messages,
            "categories": categories,
            "filter": filter,
            "filter_label": filter_label,
        },
    )