def timezone(self): if not self.domain: return pytz.utc else: try: return util.get_timezone(self.request.couch_user.user_id, self.domain) except AttributeError: return util.get_timezone(None, self.domain)
def timezone(self): if not self.domain: return pytz.utc else: try: return util.get_timezone(self.request.couch_user, self.domain) except AttributeError: return util.get_timezone(None, self.domain)
def timezone(self): if self._timezone is None: if not self.domain: self._timezone = pytz.utc else: try: self._timezone = util.get_timezone(self.request.couch_user.user_id, self.domain) except AttributeError: self._timezone = util.get_timezone(None, self.domain) return self._timezone
def form_data(request, domain, instance_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: instance = XFormInstance.get(instance_id) except Exception: raise Http404() try: assert(domain == instance.domain) except AssertionError: raise Http404() cases = CommCareCase.view("case/by_xform_id", key=instance_id, reduce=False, include_docs=True).all() try: form_name = instance.get_form["@name"] except KeyError: form_name = "Untitled Form" is_archived = instance.doc_type == "XFormArchived" if is_archived: messages.info(request, _("This form is archived. To restore it, click 'Restore this form' at the bottom of the page.")) return render(request, "reports/reportdata/form_data.html", dict(domain=domain, instance=instance, cases=cases, timezone=timezone, slug=inspect.SubmitHistory.slug, is_archived=is_archived, form_data=dict(name=form_name, modified=instance.received_on)))
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: case = CommCareCase.get(case_id) report_name = 'Details for Case "%s"' % case.name except ResourceNotFound: messages.info(request, "Sorry, we couldn't find that case. If you think this is a mistake plase report an issue.") return HttpResponseRedirect(inspect.SubmitHistory.get_url(domain)) form_lookups = dict((form.get_id, "%s: %s" % (form.received_on.date(), xmlns_to_name(domain, form.xmlns, get_app_id(form)))) \ for form in case.get_forms()) return render_to_response(request, "reports/reportdata/case_details.html", { "domain": domain, "case_id": case_id, "form_lookups": form_lookups, "slug":inspect.CaseListReport.slug, "report": dict( name=report_name, slug=inspect.CaseListReport.slug, is_async=False, ), "layout_flush_content": True, "timezone": timezone })
def message_test(request, domain, phone_number): if request.method == "POST": message = request.POST.get("message", "") domain_scope = None if request.couch_user.is_superuser else domain try: incoming(phone_number, message, "TEST", domain_scope=domain_scope) except DomainScopeValidationError: messages.error( request, _("Invalid phone number being simulated. You may only " \ "simulate SMS from verified numbers belonging to contacts " \ "in this domain.") ) except Exception: notify_exception(request) messages.error( request, _("An error has occurred. Please try again in a few minutes " \ "and if the issue persists, please contact CommCareHQ " \ "Support.") ) context = get_sms_autocomplete_context(request, domain) context['domain'] = domain context['messagelog'] = SMSLog.by_domain_dsc(domain) context['now'] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context['timezone'] = tz context['timezone_now'] = datetime.now(tz=tz) context['layout_flush_content'] = True context['phone_number'] = phone_number return render(request, "sms/message_tester.html", context)
def chat(request, domain, contact_id): domain_obj = Domain.get_by_name(domain, strict=True) timezone = report_utils.get_timezone(None, domain) # floored_utc_timestamp is the datetime in UTC representing # midnight today in local time. This is used to calculate # all message history choices' timestamps, so that choosing # "Yesterday", for example, gives you data from yesterday at # midnight local time. local_date = datetime.now(timezone).date() floored_utc_timestamp = tz_utils.adjust_datetime_to_timezone( datetime.combine(local_date, time(0,0)), timezone.zone, pytz.utc.zone ).replace(tzinfo=None) def _fmt(d): return json_format_datetime(floored_utc_timestamp - timedelta(days=d)) history_choices = [(_(x), _fmt(y)) for (x, y) in SMS_CHAT_HISTORY_CHOICES] history_choices.append( (_("All Time"), json_format_datetime(datetime(1970, 1, 1))) ) context = { "domain" : domain, "contact_id" : contact_id, "contact" : get_contact(contact_id), "message_count_threshold" : domain_obj.chat_message_count_threshold or DEFAULT_MESSAGE_COUNT_THRESHOLD, "custom_case_username" : domain_obj.custom_case_username, "history_choices" : history_choices, } template = settings.CUSTOM_CHAT_TEMPLATES.get(domain_obj.custom_chat_template) or "sms/chat.html" return render(request, template, context)
def compose_message(request, domain, template="sms/compose.html"): context = get_sms_autocomplete_context(request, domain) context['domain'] = domain context['now'] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context['timezone'] = tz context['timezone_now'] = datetime.now(tz=tz) return render(request, template, context)
def reminders_in_error(request, domain): handler_map = {} if request.method == "POST": form = RemindersInErrorForm(request.POST) if form.is_valid(): kwargs = {} if is_bigcouch(): # Force a write to all nodes before returning kwargs["w"] = bigcouch_quorum_count() current_timestamp = datetime.utcnow() for reminder_id in form.cleaned_data.get("selected_reminders"): reminder = CaseReminder.get(reminder_id) if reminder.domain != domain: continue if reminder.handler_id in handler_map: handler = handler_map[reminder.handler_id] else: handler = reminder.handler handler_map[reminder.handler_id] = handler reminder.error = False reminder.error_msg = None handler.set_next_fire(reminder, current_timestamp) reminder.save(**kwargs) timezone = report_utils.get_timezone(request.couch_user.user_id, domain) reminders = [] for reminder in CaseReminder.view("reminders/reminders_in_error", startkey=[domain], endkey=[domain, {}], include_docs=True).all(): if reminder.handler_id in handler_map: handler = handler_map[reminder.handler_id] else: handler = reminder.handler handler_map[reminder.handler_id] = handler recipient = reminder.recipient case = reminder.case reminders.append({ "reminder_id": reminder._id, "handler_id": reminder.handler_id, "handler_name": handler.nickname, "case_id": case.get_id if case is not None else None, "case_name": case.name if case is not None else None, "next_fire": tz_utils.adjust_datetime_to_timezone( reminder.next_fire, pytz.utc.zone, timezone.zone).strftime("%Y-%m-%d %H:%M:%S"), "error_msg": reminder.error_msg, "recipient_name": get_recipient_name(recipient), })
def messaging(request, domain, template="sms/default.html"): context = get_sms_autocomplete_context(request, domain) context['domain'] = domain context['messagelog'] = SMSLog.by_domain_dsc(domain) context['now'] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context['timezone'] = tz context['timezone_now'] = datetime.now(tz=tz) context['layout_flush_content'] = True return render(request, template, context)
def _get_form_context(request, domain, instance_id): timezone = util.get_timezone(request.couch_user, domain) instance = _get_form_or_404(instance_id) try: assert domain == instance.domain except AssertionError: raise Http404() display = request.project.get_form_display(instance) context = {"domain": domain, "display": display, "timezone": timezone, "instance": instance} context["form_render_options"] = context return context
def reminders_in_error(request, domain): handler_map = {} if request.method == "POST": form = RemindersInErrorForm(request.POST) if form.is_valid(): kwargs = {} if is_bigcouch(): # Force a write to all nodes before returning kwargs["w"] = bigcouch_quorum_count() current_timestamp = datetime.utcnow() for reminder_id in form.cleaned_data.get("selected_reminders"): reminder = CaseReminder.get(reminder_id) if reminder.domain != domain: continue if reminder.handler_id in handler_map: handler = handler_map[reminder.handler_id] else: handler = reminder.handler handler_map[reminder.handler_id] = handler reminder.error = False reminder.error_msg = None handler.set_next_fire(reminder, current_timestamp) reminder.save(**kwargs) timezone = report_utils.get_timezone(request.couch_user.user_id, domain) reminders = [] for reminder in CaseReminder.view("reminders/reminders_in_error", startkey=[domain], endkey=[domain, {}], include_docs=True).all(): if reminder.handler_id in handler_map: handler = handler_map[reminder.handler_id] else: handler = reminder.handler handler_map[reminder.handler_id] = handler recipient = reminder.recipient case = reminder.case reminders.append({ "reminder_id" : reminder._id, "handler_id" : reminder.handler_id, "handler_name" : handler.nickname, "case_id" : case.get_id if case is not None else None, "case_name" : case.name if case is not None else None, "next_fire" : tz_utils.adjust_datetime_to_timezone(reminder.next_fire, pytz.utc.zone, timezone.zone).strftime("%Y-%m-%d %H:%M:%S"), "error_msg" : reminder.error_msg, "recipient_name" : get_recipient_name(recipient), }) context = { "domain" : domain, "reminders" : reminders, "timezone" : timezone, "timezone_now" : datetime.now(tz=timezone), } return render(request, "reminders/partial/reminders_in_error.html", context)
def message_test(request, domain, phone_number): if request.method == "POST": message = request.POST.get("message", "") incoming(phone_number, message, "TEST") context = get_sms_autocomplete_context(request, domain) context['domain'] = domain context['messagelog'] = SMSLog.by_domain_dsc(domain) context['now'] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context['timezone'] = tz context['timezone_now'] = datetime.now(tz=tz) context['layout_flush_content'] = True context['phone_number'] = phone_number return render_to_response(request, "sms/message_tester.html", context)
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: case = CommCareCase.get(case_id) except ResourceNotFound: case = None if case == None or case.doc_type != "CommCareCase" or case.domain != domain: messages.info(request, "Sorry, we couldn't find that case. If you think this is a mistake plase report an issue.") return HttpResponseRedirect(inspect.CaseListReport.get_url(domain=domain)) report_name = 'Details for Case "%s"' % case.name form_lookups = dict((form.get_id, "%s: %s" % (form.received_on.date(), xmlns_to_name(domain, form.xmlns, get_app_id(form)))) \ for form in case.get_forms()) try: owner_name = CommCareUser.get_by_user_id(case.owner_id, domain).raw_username except Exception: try: owning_group = Group.get(case.owner_id) owner_name = owning_group.display_name if owning_group.domain == domain else '' except Exception: owner_name = None try: username = CommCareUser.get_by_user_id(case.user_id, domain).raw_username except Exception: username = None return render(request, "reports/reportdata/case_details.html", { "domain": domain, "case_id": case_id, "username": username, "owner_name": owner_name, "form_lookups": form_lookups, "slug":inspect.CaseListReport.slug, "report": dict( name=report_name, slug=inspect.CaseListReport.slug, is_async=False, ), "layout_flush_content": True, "timezone": timezone })
def get_interactive_participants(domain): cases = CommCareCase.view("hqcase/types_by_domain", key=[domain, "participant"], include_docs=True, reduce=False).all() result = [] timezone = report_utils.get_timezone(None, domain) # Use project timezone only current_date = datetime.now(tz=timezone).date() for case in cases: study_arm = case.get_case_property("study_arm") if isinstance(study_arm, basestring) and study_arm.upper() == "A" and not case.closed: start_date = case.get_case_property("start_date") if not isinstance(start_date, date): start_date = parse(start_date).date() end_date = start_date + timedelta(days=55) if current_date >= start_date and current_date <= end_date: result.append(case) return result
def message_test(request, domain, phone_number): if request.method == "POST": message = request.POST.get("message", "") domain_scope = None if request.couch_user.is_superuser else domain incoming(phone_number, message, "TEST", domain_scope=domain_scope) context = get_sms_autocomplete_context(request, domain) context["domain"] = domain context["messagelog"] = SMSLog.by_domain_dsc(domain) context["now"] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context["timezone"] = tz context["timezone_now"] = datetime.now(tz=tz) context["layout_flush_content"] = True context["phone_number"] = phone_number return render(request, "sms/message_tester.html", context)
def message_test(request, domain, phone_number): if request.method == "POST": message = request.POST.get("message", "") domain_scope = None if request.couch_user.is_superuser else domain incoming(phone_number, message, "TEST", domain_scope=domain_scope) context = get_sms_autocomplete_context(request, domain) context['domain'] = domain context['messagelog'] = SMSLog.by_domain_dsc(domain) context['now'] = datetime.utcnow() tz = report_utils.get_timezone(request.couch_user.user_id, domain) context['timezone'] = tz context['timezone_now'] = datetime.now(tz=tz) context['layout_flush_content'] = True context['phone_number'] = phone_number return render(request, "sms/message_tester.html", context)
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: case = CommCareCase.get(case_id) except ResourceNotFound: case = None if case is None or case.doc_type != "CommCareCase" or case.domain != domain: messages.info(request, "Sorry, we couldn't find that case. If you think this is a mistake please report an issue.") return HttpResponseRedirect(inspect.CaseListReport.get_url(domain=domain)) try: owner_name = CommCareUser.get_by_user_id(case.owner_id, domain).raw_username except Exception: try: owning_group = Group.get(case.owner_id) owner_name = owning_group.display_name if owning_group.domain == domain else '' except Exception: owner_name = None try: username = CommCareUser.get_by_user_id(case.user_id, domain).raw_username except Exception: username = None return render(request, "reports/reportdata/case_details.html", { "domain": domain, "case_id": case_id, "case": case, "username": username, "owner_name": owner_name, "slug": inspect.CaseListReport.slug, "report": dict( name=case_inline_display(case), slug=inspect.CaseListReport.slug, is_async=False, ), "layout_flush_content": True, "timezone": timezone, "case_display_options": { "display": request.project.get_case_display(case), "timezone": timezone, "get_case_url": lambda case_id: reverse( case_details, args=[domain, case_id]) }, })
def _get_form_context(request, domain, instance_id): timezone = util.get_timezone(request.couch_user.user_id, domain) instance = _get_form_or_404(instance_id) try: assert domain == instance.domain except AssertionError: raise Http404() display = request.project.get_form_display(instance) context = { "domain": domain, "display": display, "timezone": timezone, "instance": instance } context['form_render_options'] = context return context
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user, domain) try: case = _get_case_or_404(domain, case_id) except Http404: messages.info( request, "Sorry, we couldn't find that case. If you think this is a mistake please report an issue." ) return HttpResponseRedirect(CaseListReport.get_url(domain=domain)) try: owner_name = CommCareUser.get_by_user_id(case.owner_id, domain).raw_username except Exception: try: owning_group = Group.get(case.owner_id) owner_name = owning_group.display_name if owning_group.domain == domain else "" except Exception: owner_name = None try: username = CommCareUser.get_by_user_id(case.user_id, domain).raw_username except Exception: username = None return render( request, "reports/reportdata/case_details.html", { "domain": domain, "case_id": case_id, "case": case, "username": username, "owner_name": owner_name, "slug": CaseListReport.slug, "report": dict(name=case_inline_display(case), slug=CaseListReport.slug, is_async=False), "layout_flush_content": True, "timezone": timezone, "case_display_options": { "display": request.project.get_case_display(case), "timezone": timezone, "get_case_url": lambda case_id: reverse(case_details, args=[domain, case_id]), }, "show_case_rebuild": toggles.CASE_REBUILD.enabled(request.user.username), }, )
def get_interactive_participants(domain): cases = CommCareCase.view("hqcase/types_by_domain", key=[domain, "participant"], include_docs=True, reduce=False).all() result = [] timezone = report_utils.get_timezone(None, domain) # Use project timezone only current_date = datetime.now(tz=timezone).date() for case in cases: study_arm = case.get_case_property("study_arm") if isinstance( study_arm, basestring) and study_arm.upper() == "A" and not case.closed: start_date = get_date(case, "start_date") if start_date is None: continue end_date = start_date + timedelta(days=55) if current_date >= start_date and current_date <= end_date: result.append(case) return result
def form_data(request, domain, instance_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: instance = XFormInstance.get(instance_id) except Exception: raise Http404() try: assert(domain == instance.domain) except AssertionError: raise Http404() cases = CommCareCase.view("case/by_xform_id", key=instance_id, reduce=False, include_docs=True).all() try: form_name = instance.get_form["@name"] except KeyError: form_name = "Untitled Form" return render_to_response(request, "reports/reportdata/form_data.html", dict(domain=domain, instance=instance, cases=cases, timezone=timezone, slug=inspect.SubmitHistory.slug, form_data=dict(name=form_name, modified=instance.received_on)))
def api_history(request, domain): result = [] contact_id = request.GET.get("contact_id", None) start_date = request.GET.get("start_date", None) timezone = report_utils.get_timezone(None, domain) domain_obj = Domain.get_by_name(domain, strict=True) try: assert contact_id is not None doc = get_contact(contact_id) assert doc is not None assert doc.domain == domain except Exception: return HttpResponse("[]") query_start_date_str = None if start_date is not None: try: query_start_date = parse(start_date) query_start_date += timedelta(seconds=1) query_start_date_str = json_format_datetime(query_start_date) except Exception: pass if query_start_date_str is not None: data = SMSLog.view("sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog", INCOMING, query_start_date_str], endkey=[doc.doc_type, contact_id, "SMSLog", INCOMING, {}], include_docs=True, reduce=False).all() data += SMSLog.view("sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog", OUTGOING, query_start_date_str], endkey=[doc.doc_type, contact_id, "SMSLog", OUTGOING, {}], include_docs=True, reduce=False).all() else: data = SMSLog.view("sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog"], endkey=[doc.doc_type, contact_id, "SMSLog", {}], include_docs=True, reduce=False).all() data.sort(key=lambda x : x.date) username_map = {} last_sms = None for sms in data: # Don't show outgoing SMS that haven't been processed yet if sms.direction == OUTGOING and not sms.processed: continue # Filter SMS that are tied to surveys if necessary if ((domain_obj.filter_surveys_from_chat and sms.xforms_session_couch_id) and not (domain_obj.show_invalid_survey_responses_in_chat and sms.direction == INCOMING and sms.invalid_survey_response)): continue if sms.direction == INCOMING: if doc.doc_type == "CommCareCase" and domain_obj.custom_case_username: sender = doc.get_case_property(domain_obj.custom_case_username) elif doc.doc_type == "CommCareCase": sender = doc.name else: sender = doc.first_name or doc.raw_username elif sms.chat_user_id is not None: if sms.chat_user_id in username_map: sender = username_map[sms.chat_user_id] else: try: user = CouchUser.get_by_user_id(sms.chat_user_id) sender = user.first_name or user.raw_username except Exception: sender = _("Unknown") username_map[sms.chat_user_id] = sender else: sender = _("System") last_sms = sms result.append({ "sender" : sender, "text" : sms.text, "timestamp" : tz_utils.adjust_datetime_to_timezone(sms.date, pytz.utc.zone, timezone.zone).strftime("%I:%M%p %m/%d/%y").lower(), "utc_timestamp" : json_format_datetime(sms.date), }) if last_sms: try: entry, lock = LastReadMessage.get_locked_obj( sms.domain, request.couch_user._id, sms.couch_recipient, create=True ) if (not entry.message_timestamp or entry.message_timestamp < last_sms.date): entry.message_id = last_sms._id entry.message_timestamp = last_sms.date entry.save() lock.release() except: logging.exception("Could not create/save LastReadMessage for message %s" % last_sms._id) # Don't let this block returning of the data pass return HttpResponse(json.dumps(result))
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user, domain) try: case = get_document_or_404(CommCareCase, domain, case_id)
def api_history(request, domain): result = [] contact_id = request.GET.get("contact_id", None) start_date = request.GET.get("start_date", None) timezone = report_utils.get_timezone(None, domain) domain_obj = Domain.get_by_name(domain, strict=True) try: assert contact_id is not None doc = get_contact(contact_id) assert doc is not None assert doc.domain == domain except Exception: return HttpResponse("[]") query_start_date_str = None if start_date is not None: try: query_start_date = parse(start_date) query_start_date += timedelta(seconds=1) query_start_date_str = json_format_datetime(query_start_date) except Exception: pass if query_start_date_str is not None: data = SMSLog.view( "sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog", INCOMING, query_start_date_str], endkey=[doc.doc_type, contact_id, "SMSLog", INCOMING, {}], include_docs=True, reduce=False, ).all() data += SMSLog.view( "sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog", OUTGOING, query_start_date_str], endkey=[doc.doc_type, contact_id, "SMSLog", OUTGOING, {}], include_docs=True, reduce=False, ).all() else: data = SMSLog.view( "sms/by_recipient", startkey=[doc.doc_type, contact_id, "SMSLog"], endkey=[doc.doc_type, contact_id, "SMSLog", {}], include_docs=True, reduce=False, ).all() data.sort(key=lambda x: x.date) username_map = {} for sms in data: if sms.direction == INCOMING: if doc.doc_type == "CommCareCase" and domain_obj.custom_case_username: sender = doc.get_case_property(domain_obj.custom_case_username) elif doc.doc_type == "CommCareCase": sender = doc.name else: sender = doc.first_name or doc.raw_username elif sms.chat_user_id is not None: if sms.chat_user_id in username_map: sender = username_map[sms.chat_user_id] else: try: user = CouchUser.get_by_user_id(sms.chat_user_id) sender = user.first_name or user.raw_username except Exception: sender = _("Unknown") username_map[sms.chat_user_id] = sender else: sender = _("System") result.append( { "sender": sender, "text": sms.text, "timestamp": tz_utils.adjust_datetime_to_timezone(sms.date, pytz.utc.zone, timezone.zone) .strftime("%I:%M%p %m/%d/%y") .lower(), "utc_timestamp": json_format_datetime(sms.date), } ) return HttpResponse(json.dumps(result))
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user, domain) try: case = _get_case_or_404(domain, case_id)
def case_details(request, domain, case_id): timezone = util.get_timezone(request.couch_user.user_id, domain) try: case = CommCareCase.get(case_id)