def create_type(request): success = False form = EntityTypeForm(request.POST) if form.is_valid(): entity_name = form.cleaned_data["entity_type_regex"] entity_name = [entity_name.strip().lower()] try: manager = get_database_manager(request.user) define_type(manager, entity_name) create_registration_form(manager, entity_name) message = _("Entity definition successful") success = True UserActivityLog().log(request, action=ADDED_SUBJECT_TYPE, detail=entity_name[0].capitalize()) except EntityTypeAlreadyDefined: if request.POST["referer"] == 'project': message = _( "%s already registered as a subject type. Please select %s from the drop down menu." ) % (entity_name[0], entity_name[0]) else: message = _("%s already registered as a subject type.") % ( entity_name[0], ) else: message = form.fields['entity_type_regex'].error_messages['invalid'] return HttpResponse(json.dumps({ 'success': success, 'message': _(message) }))
def save_questionnaire(request): manager = get_database_manager(request) if request.method == 'POST': questionnaire_code = request.POST['questionnaire-code'] json_string = request.POST['question-set'] question_set = json.loads(json_string) pid = request.POST['pid'] project = models.get_project(pid, dbm=manager) form_model = manager.get(project.qid, FormModel) try: form_model = helper.update_questionnaire_with_questions(form_model, question_set, manager) except QuestionCodeAlreadyExistsException as e: return HttpResponseServerError(e) except EntityQuestionAlreadyExistsException as e: return HttpResponseServerError(e.message) else: try: form_model.form_code = questionnaire_code.lower() except DataObjectAlreadyExists as e: if e.message.find("Form") >= 0: return HttpResponseServerError("Questionnaire with this code already exists") return HttpResponseServerError(e.message) form_model.name = project.name form_model.entity_id = project.entity_type form_model.save() return HttpResponse(json.dumps({"response": "ok"}))
def export_template(request, entity_type=None): manager = get_database_manager(request.user) if entity_type is None: return HttpResponseRedirect(reverse(all_subjects)) fields, labels, field_codes = import_module.get_entity_type_fields( manager, entity_type) response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="%s.xls"' % ( entity_type, ) form_model = get_form_model_by_entity_type(manager, [entity_type.lower()]) wb = get_excel_sheet([labels], entity_type) form_code = form_model.form_code add_codes_sheet(wb, form_code, field_codes) try: index_geocode = fields.index(GEO_CODE_FIELD_NAME) except ValueError: index_geocode = 0 ws = wb.get_sheet(0) style = xlwt.XFStyle() style.num_format_str = '@' gps_col = ws.col(index_geocode) gps_col.set_style(style) wb.save(response) return response
def datasenders(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) _format_field_description_for_data_senders(reg_form.fields) cleaned_up_fields = _get_questions_for_datasenders_registration_for_print_preview(reg_form.fields) return render_to_response('project/datasenders.html', {'fields': cleaned_up_fields, 'project':project, 'project_links':project_links}, context_instance=RequestContext(request))
def hierarchy_report(request): manager = get_database_manager(request) column_headers, values = [], [] choices = [(t, '.'.join(t)) for t in get_all_entity_types(manager)] if request.method == 'POST': form = ReportHierarchy(data=request.POST, choices=choices) if form.is_valid(): entity_type = form.cleaned_data['entity_type'].split(".") aggregates_field = form.cleaned_data['aggregates_field'] reduce_function = form.cleaned_data['reduce'] aggregates = {aggregates_field: reduce_function} aggregate_on_path = form.cleaned_data['aggregate_on_path'] level = form.cleaned_data['level'] report_data = data.aggregate(manager, entity_type=entity_type, aggregates=aggregates, aggregate_on=TypeAggregration(type=aggregate_on_path,level=level), ) column_headers, values = tabulate_output(report_data, "Path") else: form = ReportHierarchy(choices=choices) return render_to_response('reports/reportperhierarchypath.html', {'form': form, 'column_headers': column_headers, 'column_values': values}, context_instance=RequestContext(request))
def create_profile(request): manager = get_database_manager(request) entity_list = get_all_entity_types(manager) entity_list = helper.remove_reporter(entity_list) project_summary = dict(name='New Project') if request.method == 'GET': form = ProjectProfile(entity_list=entity_list,initial={'activity_report':'yes'}) return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False}, context_instance=RequestContext(request)) form = ProjectProfile(data=request.POST, entity_list=entity_list) if form.is_valid(): entity_type=form.cleaned_data['entity_type'] project = Project(name=form.cleaned_data["name"], goals=form.cleaned_data["goals"], project_type=form.cleaned_data['project_type'], entity_type=entity_type, devices=form.cleaned_data['devices'], activity_report=form.cleaned_data['activity_report'], sender_group=form.cleaned_data['sender_group']) form_model = helper.create_questionnaire(post=form.cleaned_data, dbm=manager) try: pid = project.save(manager) qid = form_model.save() project.qid = qid pid = project.save(manager) except DataObjectAlreadyExists as e: messages.error(request, e.message) return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False}, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse(subjects_wizard, args=[pid])) else: return render_to_response('project/profile.html', {'form': form, 'project': project_summary, 'edit':False}, context_instance=RequestContext(request))
def report(request): manager = get_database_manager(request) types = get_all_entity_types(manager) choices = [('.'.join(t), '.'.join(t)) for t in types] column_headers = [] values = [] error_message = None if request.method == 'POST': form = Report(data=request.POST, choices=choices) if form.is_valid(): entity_type = form.cleaned_data['entity_type'].split(".") filter_criteria = form.cleaned_data['filter'] aggregates_field = form.cleaned_data['aggregates_field'] location = filter_criteria.split(",") if filter_criteria else None report_data = data.aggregate(manager, entity_type=entity_type, aggregates={aggregates_field: data.reduce_functions.LATEST}, filter=LocationFilter(location=location) ) column_headers, values = tabulate_output(report_data, "ID") if not len(values): error_message = 'Sorry, No records found for this query' else: form = Report(choices=choices) return render_to_response('reports/reportperlocation.html', {'form': form, 'column_headers': column_headers, 'column_values': values, 'error_message': error_message}, context_instance=RequestContext(request))
def edit_profile(request, project_id=None): manager = get_database_manager(request) entity_list = get_all_entity_types(manager) entity_list = helper.remove_reporter(entity_list) project = models.get_project(project_id, dbm=manager) if request.method == 'GET': form = ProjectProfile(data=project, entity_list=entity_list) return render_to_response('project/profile.html', {'form': form, 'project': project, 'edit':True}, context_instance=RequestContext(request)) form = ProjectProfile(data=request.POST, entity_list=entity_list) if form.is_valid(): older_entity_type = project.entity_type if older_entity_type != form.cleaned_data["entity_type"]: new_questionnaire = helper.create_questionnaire(form.cleaned_data, manager) new_qid = new_questionnaire.save() project.qid = new_qid project.update(form.cleaned_data) project.update_questionnaire(manager) try: pid = project.save(manager) except DataObjectAlreadyExists as e: messages.error(request, e.message) return render_to_response('project/profile.html', {'form': form, 'project': project, 'edit':True}, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse(subjects_wizard, args=[pid])) else: return render_to_response('project/profile.html', {'form': form, 'project': project, 'edit':True}, context_instance=RequestContext(request))
def index(request): manager = get_database_manager(request) rows = models.get_all_projects(dbm=manager) project_list = [] for row in rows: analysis = log = "#" disabled = "disable_link" project_id = row['value']['_id'] project = models.get_project(project_id, dbm=manager) questionnaire = manager.get(project['qid'], FormModel) questionnaire_code = questionnaire.form_code link = reverse(project_overview, args=[project_id]) if project.state != ProjectState.INACTIVE: disabled = "" analysis = reverse(project_data, args=[project_id, questionnaire_code]) log = reverse(project_results, args=[project_id, questionnaire_code]) project = dict(name=row['value']['name'], created=row['value']['created'], type=row['value']['project_type'], link=link, log=log, analysis=analysis, disabled=disabled) project_list.append(project) return render_to_response('alldata/index.html', {'projects': project_list}, context_instance=RequestContext(request))
def hierarchy_report(request): manager = get_database_manager(request) column_headers, values = [], [] choices = [(t, '.'.join(t)) for t in get_all_entity_types(manager)] if request.method == 'POST': form = ReportHierarchy(data=request.POST, choices=choices) if form.is_valid(): entity_type = form.cleaned_data['entity_type'].split(".") aggregates_field = form.cleaned_data['aggregates_field'] reduce_function = form.cleaned_data['reduce'] aggregates = {aggregates_field: reduce_function} aggregate_on_path = form.cleaned_data['aggregate_on_path'] level = form.cleaned_data['level'] report_data = data.aggregate( manager, entity_type=entity_type, aggregates=aggregates, aggregate_on=TypeAggregration(type=aggregate_on_path, level=level), ) column_headers, values = tabulate_output(report_data, "Path") else: form = ReportHierarchy(choices=choices) return render_to_response('reports/reportperhierarchypath.html', { 'form': form, 'column_headers': column_headers, 'column_values': values }, context_instance=RequestContext(request))
def report(request): manager = get_database_manager(request) types = get_all_entity_types(manager) choices = [('.'.join(t), '.'.join(t)) for t in types] column_headers = [] values = [] error_message = None if request.method == 'POST': form = Report(data=request.POST, choices=choices) if form.is_valid(): entity_type = form.cleaned_data['entity_type'].split(".") filter_criteria = form.cleaned_data['filter'] aggregates_field = form.cleaned_data['aggregates_field'] location = filter_criteria.split(",") if filter_criteria else None report_data = data.aggregate( manager, entity_type=entity_type, aggregates={aggregates_field: data.reduce_functions.LATEST}, filter=LocationFilter(location=location)) column_headers, values = tabulate_output(report_data, "ID") if not len(values): error_message = 'Sorry, No records found for this query' else: form = Report(choices=choices) return render_to_response('reports/reportperlocation.html', { 'form': form, 'column_headers': column_headers, 'column_values': values, 'error_message': error_message }, context_instance=RequestContext(request))
def delete_entity(request): manager = get_database_manager(request.user) organization = get_organization(request) transport_info = TransportInfo("web", request.user.username, "") entity_type = request.POST['entity_type'] project = request.POST.get("project", "") all_ids = request.POST['all_ids'].split(';') ngo_admin_user_profile = get_ngo_admin_user_profiles_for(organization)[0] if ngo_admin_user_profile.reporter_id in all_ids: messages.error( request, _("Your organization's account Administrator %s cannot be deleted") % (_get_full_name(ngo_admin_user_profile.user)), "error_message") else: delete_entity_instance(manager, all_ids, entity_type, transport_info) if entity_type == REPORTER: delete_datasender_from_project(manager, all_ids) delete_datasender_users_if_any(all_ids, organization) if organization.in_trial_mode: delete_datasender_for_trial_mode(manager, all_ids, entity_type) action = DELETED_DATA_SENDERS else: action = DELETED_SUBJECTS UserActivityLog().log(request, action=action, detail="%s: [%s]" % (entity_type.capitalize(), ", ".join(all_ids)), project=project.capitalize()) messages.success(request, get_success_message(entity_type)) return HttpResponse(json.dumps({'success': True}))
def web_preview(request): project_info = json.loads(request.POST['profile_form']) manager = get_database_manager(request.user) return render_to_response("project/web_instruction_preview.html", get_web_preview_context(manager, request.POST, project_info), context_instance=RequestContext(request))
def edit_project(request, project_id=None): manager = get_database_manager(request.user) entity_list = get_all_entity_types(manager) entity_list = helper.remove_reporter(entity_list) project = Project.load(manager.database, project_id) questionnaire = FormModel.get(manager, project.qid) if request.method == 'GET': form = CreateProject(data=project, entity_list=entity_list) activity_report_questions = json.dumps(helper.get_activity_report_questions(manager), default=field_to_json) subject_report_questions = json.dumps(helper.get_subject_report_questions(manager), default=field_to_json) fields = questionnaire.fields if questionnaire.entity_defaults_to_reporter(): fields = helper.hide_entity_question(questionnaire.fields) existing_questions = json.dumps(fields, default=field_to_json) return render_to_response('project/create_project.html', {'form': form, "activity_report_questions": repr(activity_report_questions), 'subject_report_questions': repr(subject_report_questions), 'preview_links': get_preview_and_instruction_links(), 'existing_questions': repr(existing_questions), 'questionnaire_code': questionnaire.form_code, 'project': project, 'is_edit': 'true', 'post_url': reverse(edit_project, args=[project_id])}, context_instance=RequestContext(request)) if request.method == 'POST': project_info = json.loads(request.POST['profile_form']) form = CreateProject(entity_list, data=project_info) if form.is_valid(): detail = dict() for key, changed in enumerate(form.changed_data): if getattr(project, changed) != form.cleaned_data.get(changed): detail.update({changed.capitalize(): form.cleaned_data.get(changed)}) project.update(form.cleaned_data) try: old_fields = questionnaire.fields questionnaire = update_questionnaire(questionnaire, request.POST, form.cleaned_data['entity_type'], form.cleaned_data['name'], manager, form.cleaned_data['language']) changed_questions = get_changed_questions(old_fields, questionnaire.fields, subject=False) detail.update(changed_questions) project.state = request.POST['project_state'] project.qid = questionnaire.save() UserActivityLog().log(request, project=project.name, action=EDITED_PROJECT, detail=json.dumps(detail)) except (QuestionCodeAlreadyExistsException, QuestionAlreadyExistsException, EntityQuestionAlreadyExistsException) as ex: return HttpResponse( json.dumps({'success': False, 'error_in_project_section': False, 'error_message': _(ex.message)})) except DataObjectAlreadyExists: return HttpResponse(json.dumps({'success': False, 'error_in_project_section': False, 'error_message': 'Questionnaire with this code already exists'})) try: project.save(manager) except DataObjectAlreadyExists as ex: message = _("%s with %s = %s already exists.") % (_(ex.data[2]), _(ex.data[0]), "'%s'" % project.name) return HttpResponse( json.dumps({'success': False, 'error_message': message, 'error_in_project_section': True})) return HttpResponse(json.dumps({'success': True, 'project_id': project.id}))
def questionnaire_web_preview(request): manager = get_database_manager(request.user) project_info = Project.load(manager.database, request.POST["project_id"]) context = get_web_preview_context(manager, request.POST, project_info) if project_info else {} return render_to_response("project/web_instruction_preview.html", context, context_instance=RequestContext(request))
def create_subject(request): db_manager = get_database_manager(request) entity_types = get_all_entity_types(db_manager) project_helper.remove_reporter(entity_types) return render_to_response("entity/create_subject.html", { "post_url": reverse(submit), "entity_types": entity_types }, context_instance=RequestContext(request))
def sms_preview(request): manager = get_database_manager(request.user) context = {'org_number': get_organization_telephone_number(request)} project_info = json.loads(request.POST['profile_form']) context.update(get_sms_preview_context(manager, request.POST, project_info)) return render_to_response("project/sms_instruction_preview.html", context, context_instance=RequestContext(request))
def export_data(request): questionnaire_code = request.POST.get("questionnaire_code") manager = get_database_manager(request) form_model = get_form_model_by_code(manager, questionnaire_code) data_dictionary = _load_data(form_model, manager, questionnaire_code, request) response_string, header_list, type_list = _format_data_for_presentation(data_dictionary, form_model) raw_data_list = json.loads(response_string) raw_data_list.insert(0, header_list) file_name = request.POST.get(u"project_name")+'_analysis' return _create_excel_response(raw_data_list, file_name)
def registered_datasenders(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) all_data = load_all_subjects_of_type(request) return render_to_response('project/registered_datasenders.html', { 'project': project, 'project_links': project_links, 'all_data': all_data }, context_instance=RequestContext(request))
def subjects(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) return render_to_response('project/subjects.html', { 'fields': reg_form.fields, 'project': project, 'project_links': project_links }, context_instance=RequestContext(request))
def wrapper(*args, **kw): request = args[0] user = request.user dbm = get_database_manager(user) project_id = kw["project_id"] project = Project.load(dbm.database, project_id) if "web" not in project.devices: referer = django_settings.HOME_PAGE return HttpResponseRedirect(referer) return f(*args, **kw)
def import_subjects_from_project_wizard(request): manager = get_database_manager(request) error_message, failure_imports, success, success_message = import_module.import_data( request, manager) return HttpResponse( json.dumps({ 'success': success, 'message': success_message, 'error_message': error_message, 'failure_imports': failure_imports }))
def create_data_sender(request): create_data_sender = True entity_links = {'back_link': reverse(all_datasenders)} if request.method == 'GET': form = ReporterRegistrationForm() return render_to_response('entity/create_or_edit_data_sender.html', { 'form': form, 'create_data_sender': create_data_sender, 'entity_links': entity_links }, context_instance=RequestContext(request)) if request.method == 'POST': dbm = get_database_manager(request.user) org_id = request.user.get_profile().org_id form = ReporterRegistrationForm(org_id=org_id, data=request.POST) success = False try: reporter_id, message = process_create_data_sender_form( dbm, form, org_id) success = True except DataObjectAlreadyExists as e: message = _( "Data Sender with Unique Identification Number (ID) = %s already exists." ) % e.data[1] if len(form.errors) == 0 and form.requires_web_access() and success: email_id = request.POST['email'] create_single_web_user(org_id=org_id, email_address=email_id, reporter_id=reporter_id, language_code=request.LANGUAGE_CODE) if message is not None and success: if form.cleaned_data['project_id'] != "": project = Project.load(dbm.database, form.cleaned_data['project_id']) project = project.name else: project = "" if not len(form.errors): UserActivityLog().log(request, action=REGISTERED_DATA_SENDER, detail=json.dumps( dict({"Unique ID": reporter_id})), project=project) form = ReporterRegistrationForm( initial={'project_id': form.cleaned_data['project_id']}) return render_to_response('datasender_form.html', { 'form': form, 'message': message, 'success': success, 'entity_links': entity_links }, context_instance=RequestContext(request))
def questionnaire_sms_preview(request): manager = get_database_manager(request.user) context = {'org_number': get_organization_telephone_number(request)} project_info = Project.load(manager.database, request.POST['project_id']) if project_info: context.update( get_sms_preview_context(manager, request.POST, project_info)) return render_to_response("project/sms_instruction_preview.html", context, context_instance=RequestContext(request))
def load_all_subjects_of_type(request, entity_type="reporter"): manager = get_database_manager(request) rows = get_all_entities(dbm=manager, include_docs=True) data = [] for row in rows: type = _get_entity_type_from_row(row) entity, short_code = _get_entity_for_row(manager, row, type) type = '.'.join(type) if type.lower() == entity_type: data.append(_tabulate_data(entity, row, short_code, type)) return data
def project_overview(request, project_id=None): manager = get_database_manager(request) project = models.get_project(project_id, dbm=manager) link = reverse(edit_profile, args=[project_id]) questionnaire = helper.load_questionnaire(manager, project['qid']) number_of_questions = len(questionnaire.fields) project_links = _make_project_links(project, questionnaire.form_code) return render_to_response('project/overview.html', {'project': project, 'entity_type': project['entity_type'], 'project_links': project_links , 'project_profile_link': link, 'number_of_questions': number_of_questions}, context_instance=RequestContext(request))
def submissions(request): """ Called via ajax, returns the partial HTML for the submissions made for the project, paginated. """ manager = get_database_manager(request) if request.method == 'GET': questionnaire_code = request.GET.get('questionnaire_code') count,results,error_message = _get_submissions(manager, questionnaire_code, request) return render_to_response('project/log_table.html', {'questionnaire_code': questionnaire_code, 'results': results, 'pages': count,'error_message': error_message, 'success_message': ""}, context_instance=RequestContext(request))
def all_datasenders(request): manager = get_database_manager(request) if request.method == 'POST': error_message, failure_imports, success, success_message = import_module.import_data(request, manager) all_data_senders = import_module.load_all_subjects_of_type(request) return HttpResponse(json.dumps({'success': success, 'message': success_message, 'error_message': error_message, 'failure_imports': failure_imports, 'all_data': all_data_senders})) all_data_senders = import_module.load_all_subjects_of_type(request) return render_to_response('entity/all_datasenders.html', {'all_data': all_data_senders}, context_instance=RequestContext(request))
def map_entities(request): dbm = get_database_manager(request.user) project = Project.load(dbm.database, request.GET['project_id']) if project.is_activity_report(): entity_list = [ get_by_short_code(dbm, short_code, ["reporter"]) for short_code in project.data_senders ] else: entity_list = get_entities_by_type(dbm, request.GET['id']) location_geojson = helper.create_location_geojson(entity_list) return HttpResponse(location_geojson)
def export_data(request): questionnaire_code = request.POST.get("questionnaire_code") manager = get_database_manager(request) form_model = get_form_model_by_code(manager, questionnaire_code) data_dictionary = _load_data(form_model, manager, questionnaire_code, request) response_string, header_list, type_list = _format_data_for_presentation( data_dictionary, form_model) raw_data_list = json.loads(response_string) raw_data_list.insert(0, header_list) file_name = request.POST.get(u"project_name") + '_analysis' return _create_excel_response(raw_data_list, file_name)
def datasenders(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) _format_field_description_for_data_senders(reg_form.fields) cleaned_up_fields = _get_questions_for_datasenders_registration_for_print_preview( reg_form.fields) return render_to_response('project/datasenders.html', { 'fields': cleaned_up_fields, 'project': project, 'project_links': project_links }, context_instance=RequestContext(request))
def questionnaire_wizard(request, project_id=None): manager = get_database_manager(request) if request.method == 'GET': previous_link = reverse(subjects_wizard, args=[project_id]) project = models.get_project(project_id, manager) form_model = helper.load_questionnaire(manager, project.qid) fields = form_model.fields if form_model.entity_defaults_to_reporter(): fields = helper.hide_entity_question(form_model.fields) existing_questions = json.dumps(fields, default=field_to_json) return render_to_response('project/questionnaire_wizard.html', {"existing_questions": repr(existing_questions), 'questionnaire_code': form_model.form_code, "previous": previous_link, 'project': project}, context_instance=RequestContext(request))
def sender_registration_form_preview(request,project_id=None): manager = get_database_manager(request) project = models.get_project(project_id, manager) if request.method == "GET": fields, previous_link, project_links, questions, registration_questionnaire = _get_registration_form(manager, project, project_id, type_of_subject='Data sender') example_sms = "%s +%s <answer> .... +%s <answer>" % (registration_questionnaire.form_code, fields[0].code, fields[len(fields)-1].code) datasender_questions = _get_questions_for_datasenders_registration_for_print_preview(questions) return render_to_response('project/questionnaire_preview.html', {"questions":datasender_questions, 'questionnaire_code': registration_questionnaire.form_code, "previous": previous_link, 'project': project, 'project_links': project_links, 'example_sms':example_sms}, context_instance=RequestContext(request))
def index(request): project_list = [] rows = models.get_all_projects(dbm=get_database_manager(request)) for row in rows: project_id = row['value']['_id'] link = reverse(project_overview, args=[project_id]) activate_link = reverse(activate_project, args=[project_id]) project = dict(name=row['value']['name'], created=row['value']['created'], type=row['value']['project_type'], link=link, activate_link=activate_link, state=row['value']['state']) project["created"] = project["created"].strftime("%d %B, %Y") project_list.append(project) return render_to_response('project/index.html', {'projects': project_list}, context_instance=RequestContext(request))
def create_datasender(request): if request.method == 'GET': form = ReporterRegistrationForm() return render_to_response('entity/create_datasender.html', {'form': form}, context_instance=RequestContext(request)) if request.method == 'POST': dbm = get_database_manager(request) form, form_errors, message, success = _validate_post_data(dbm, request) if success: form = ReporterRegistrationForm() response = render_to_response('datasender_form.html', {'form': form, 'message': message, 'form_errors': form_errors, 'success': success}, context_instance=RequestContext(request)) return response
def activate_project(request, project_id=None): manager = get_database_manager(request) project = models.get_project(project_id, manager) project.activate(manager) form_model = helper.load_questionnaire(manager, project.qid) oneDay = datetime.timedelta(days=1) tomorrow = datetime.datetime.now() + oneDay submissions, ids = get_submissions_made_for_form(manager, form_model.form_code, start_time=0, end_time=int(mktime(tomorrow.timetuple())) * 1000, page_size=None) for each in ids: if each is not None: data_record = manager._load_document(each, DataRecordDocument) manager.invalidate(each) SubmissionLogger(manager).void_data_record(data_record.submission.get("submission_id")) return HttpResponseRedirect(reverse(project_overview, args=[project_id]))
def project_overview(request, project_id=None): manager = get_database_manager(request) project = models.get_project(project_id, dbm=manager) link = reverse(edit_profile, args=[project_id]) questionnaire = helper.load_questionnaire(manager, project['qid']) number_of_questions = len(questionnaire.fields) project_links = _make_project_links(project, questionnaire.form_code) return render_to_response('project/overview.html', { 'project': project, 'entity_type': project['entity_type'], 'project_links': project_links, 'project_profile_link': link, 'number_of_questions': number_of_questions }, context_instance=RequestContext(request))
def export_log(request): questionnaire_code = request.GET.get("questionnaire_code") manager = get_database_manager(request) count,results,error_message = _get_submissions(manager,questionnaire_code,request,paginate=False) header_list = ["To", "From", "Date Received", "Submission status", "Deleted Record","Errors"] header_list.extend([each[1] for each in results['questions']]) raw_data_list = [header_list] if count: submissions, ids = zip(*results['submissions']) raw_data_list.extend([list(each) for each in submissions]) file_name = request.GET.get(u"project_name")+'_log' return _create_excel_response(raw_data_list,file_name)
def create_profile(request): manager = get_database_manager(request) entity_list = get_all_entity_types(manager) entity_list = helper.remove_reporter(entity_list) project_summary = dict(name='New Project') if request.method == 'GET': form = ProjectProfile(entity_list=entity_list, initial={'activity_report': 'yes'}) return render_to_response('project/profile.html', { 'form': form, 'project': project_summary, 'edit': False }, context_instance=RequestContext(request)) form = ProjectProfile(data=request.POST, entity_list=entity_list) if form.is_valid(): entity_type = form.cleaned_data['entity_type'] project = Project(name=form.cleaned_data["name"], goals=form.cleaned_data["goals"], project_type=form.cleaned_data['project_type'], entity_type=entity_type, devices=form.cleaned_data['devices'], activity_report=form.cleaned_data['activity_report'], sender_group=form.cleaned_data['sender_group']) form_model = helper.create_questionnaire(post=form.cleaned_data, dbm=manager) try: pid = project.save(manager) qid = form_model.save() project.qid = qid pid = project.save(manager) except DataObjectAlreadyExists as e: messages.error(request, e.message) return render_to_response('project/profile.html', { 'form': form, 'project': project_summary, 'edit': False }, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse(subjects_wizard, args=[pid])) else: return render_to_response('project/profile.html', { 'form': form, 'project': project_summary, 'edit': False }, context_instance=RequestContext(request))
def get_submission_breakup(request, project_id): dbm = get_database_manager(request.user) project = Project.load(dbm.database, project_id) form_model = FormModel.get(dbm, project.qid) rows = dbm.load_all_rows_in_view('undeleted_submission_log', startkey=[form_model.form_code], endkey=[form_model.form_code, {}], group=True, group_level=1, reduce=True) submission_success, submission_errors = 0, 0 for row in rows: submission_success = row["value"]["success"] submission_errors = row["value"]["count"] - row["value"]["success"] response = json.dumps([submission_success, submission_errors]) return HttpResponse(response)
def create_type(request): success = False form = EntityTypeForm(request.POST) if form.is_valid(): entity_name = form.cleaned_data["entity_type_regex"] entity_name = [entity_name.lower()] try: manager = get_database_manager(request) define_type(manager, entity_name) message = "Entity definition successful" success = True except EntityTypeAlreadyDefined: message = "This subject has already been added." else: message = form.fields['entity_type_regex'].error_messages['invalid'] return HttpResponse(json.dumps({'success': success, 'message': message}))
def datasenders_wizard(request, project_id=None): if request.method == 'GET': manager = get_database_manager(request) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) previous_link = reverse(questionnaire_wizard, args=[project_id]) project = models.get_project(project_id, manager) import_reporter_form = ReporterRegistrationForm() _format_field_description_for_data_senders(reg_form.fields) cleaned_up_fields = _get_questions_for_datasenders_registration_for_wizard(reg_form.fields) return render_to_response('project/datasenders_wizard.html', {'fields': cleaned_up_fields, "previous": previous_link, 'form': import_reporter_form, 'post_url': reverse(import_subjects_from_project_wizard), 'project': project, 'step': 'datasenders'}, context_instance=RequestContext(request)) if request.method == 'POST': return HttpResponseRedirect(reverse(finish, args=[project_id]))
def subjects_wizard(request, project_id=None): if request.method == 'GET': manager = get_database_manager(request) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) previous_link = reverse(edit_profile, args=[project_id]) entity_types = get_all_entity_types(manager) project = models.get_project(project_id, manager) helper.remove_reporter(entity_types) import_subject_form = SubjectUploadForm() return render_to_response('project/subjects_wizard.html', {'fields': reg_form.fields, "previous": previous_link, "entity_types": entity_types, 'import_subject_form': import_subject_form, 'post_url': reverse(import_subjects_from_project_wizard), 'project': project, 'step': 'subjects'}, context_instance=RequestContext(request)) if request.method == 'POST': return HttpResponseRedirect(reverse(questionnaire_wizard, args=[project_id]))
def submissions(request): """ Called via ajax, returns the partial HTML for the submissions made for the project, paginated. """ manager = get_database_manager(request) if request.method == 'GET': questionnaire_code = request.GET.get('questionnaire_code') count, results, error_message = _get_submissions( manager, questionnaire_code, request) return render_to_response('project/log_table.html', { 'questionnaire_code': questionnaire_code, 'results': results, 'pages': count, 'error_message': error_message, 'success_message': "" }, context_instance=RequestContext(request))
def dashboard(request): manager = get_database_manager(request) project_list = [] rows = manager.load_all_rows_in_view('all_projects', descending=True, limit=4) for row in rows: link = reverse("project-overview",args=(row['value']['_id'],)) form_model = manager.get(row['value']['qid'], FormModel) questionnaire_code = form_model.form_code submissions, success, errors = get_submissions(manager, questionnaire_code) project = dict(name=row['value']['name'], link=link, submissions=submissions, success=success, errors=errors, inactive=is_project_inactive(row)) project_list.append(project) return render_to_response('dashboard/home.html', {"projects": project_list}, context_instance=RequestContext(request))
def questionnaire_wizard(request, project_id=None): manager = get_database_manager(request) if request.method == 'GET': previous_link = reverse(subjects_wizard, args=[project_id]) project = models.get_project(project_id, manager) form_model = helper.load_questionnaire(manager, project.qid) fields = form_model.fields if form_model.entity_defaults_to_reporter(): fields = helper.hide_entity_question(form_model.fields) existing_questions = json.dumps(fields, default=field_to_json) return render_to_response( 'project/questionnaire_wizard.html', { "existing_questions": repr(existing_questions), 'questionnaire_code': form_model.form_code, "previous": previous_link, 'project': project }, context_instance=RequestContext(request))
def all_subjects(request, form_code=None): manager = get_database_manager(request.user) if request.method == 'POST': error_message, failure_imports, success_message, imported_entities = import_module.import_data( request, manager, default_parser=XlsOrderedParser, form_code=form_code) if len(imported_entities) != 0: detail_dict = dict() for short_code, entity_type in imported_entities.items(): entity_type = entity_type.capitalize() if detail_dict.get(entity_type) is not None: detail_dict.get(entity_type).append(short_code) else: detail_dict.update({entity_type: [short_code]}) for key, detail in detail_dict.items(): detail_dict.update({key: "[%s]" % ", ".join(detail)}) UserActivityLog().log(request, action=IMPORTED_SUBJECTS, detail=json.dumps(detail_dict)) subjects_data = import_module.load_all_subjects(manager) return HttpResponse( json.dumps({ 'success': error_message is None and is_empty(failure_imports), 'message': success_message, 'error_message': error_message, 'failure_imports': failure_imports, 'all_data': subjects_data, 'imported': imported_entities.keys() })) subjects_data = import_module.load_all_subjects(manager) return render_to_response('entity/all_subjects.html', { 'all_data': subjects_data, 'current_language': translation.get_language(), 'edit_url': '/entity/subject/edit/' }, context_instance=RequestContext(request))
def edit_profile(request, project_id=None): manager = get_database_manager(request) entity_list = get_all_entity_types(manager) entity_list = helper.remove_reporter(entity_list) project = models.get_project(project_id, dbm=manager) if request.method == 'GET': form = ProjectProfile(data=project, entity_list=entity_list) return render_to_response('project/profile.html', { 'form': form, 'project': project, 'edit': True }, context_instance=RequestContext(request)) form = ProjectProfile(data=request.POST, entity_list=entity_list) if form.is_valid(): older_entity_type = project.entity_type if older_entity_type != form.cleaned_data["entity_type"]: new_questionnaire = helper.create_questionnaire( form.cleaned_data, manager) new_qid = new_questionnaire.save() project.qid = new_qid project.update(form.cleaned_data) project.update_questionnaire(manager) try: pid = project.save(manager) except DataObjectAlreadyExists as e: messages.error(request, e.message) return render_to_response('project/profile.html', { 'form': form, 'project': project, 'edit': True }, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse(subjects_wizard, args=[pid])) else: return render_to_response('project/profile.html', { 'form': form, 'project': project, 'edit': True }, context_instance=RequestContext(request))
def questionnaire_preview(request, project_id=None): manager = get_database_manager(request) if request.method == 'GET': previous_link = reverse(subjects_wizard, args=[project_id]) project = models.get_project(project_id, manager) form_model = helper.load_questionnaire(manager, project.qid) fields = form_model.fields if form_model.entity_defaults_to_reporter(): fields = helper.hide_entity_question(form_model.fields) project_links = _make_project_links(project, form_model.form_code) questions = [] for field in fields: question = helper.get_preview_for_field(field) questions.append(question) example_sms = "%s +%s <answer> .... +%s <answer>" % (form_model.form_code, fields[0].code, fields[len(fields)-1].code) return render_to_response('project/questionnaire_preview.html', {"questions": questions, 'questionnaire_code': form_model.form_code, "previous": previous_link, 'project': project, 'project_links': project_links, 'example_sms':example_sms}, context_instance=RequestContext(request))
def project_data(request, project_id=None, questionnaire_code=None): manager = get_database_manager(request) project = models.get_project(project_id, dbm=manager) form_model = get_form_model_by_code(manager, questionnaire_code) project_links = _make_project_links(project, questionnaire_code) if request.method == "GET": data_dictionary = data.aggregate_for_form(manager, form_code=questionnaire_code, aggregates={"*": data.reduce_functions.LATEST}, aggregate_on=EntityAggregration()) response_string, header_list, type_list = _format_data_for_presentation(data_dictionary, form_model) return render_to_response('project/data_analysis.html', {"entity_type": form_model.entity_type[0], "data_list": repr(response_string), "header_list": header_list, "type_list": type_list, 'project_links': project_links, 'project': project} , context_instance=RequestContext(request)) if request.method == "POST": data_dictionary = _load_data(form_model, manager, questionnaire_code, request) response_string, header_list, type_list = _format_data_for_presentation(data_dictionary, form_model) return HttpResponse(response_string)
def index(request): manager = get_database_manager(request) rows = models.get_all_projects(dbm=manager) project_list = [] for row in rows: analysis = log = "#" disabled = "disable_link" project_id = row['value']['_id'] project = models.get_project(project_id, dbm=manager) questionnaire = manager.get(project['qid'], FormModel) questionnaire_code=questionnaire.form_code link = reverse(project_overview, args=[project_id]) if project.state != ProjectState.INACTIVE: disabled="" analysis = reverse(project_data, args=[project_id, questionnaire_code]) log=reverse(project_results, args=[project_id, questionnaire_code]) project = dict(name=row['value']['name'], created=row['value']['created'], type=row['value']['project_type'], link=link, log=log, analysis=analysis, disabled=disabled) project_list.append(project) return render_to_response('alldata/index.html', {'projects': project_list}, context_instance=RequestContext(request))
def project_results(request, project_id=None, questionnaire_code=None): manager = get_database_manager(request) project = models.get_project(project_id, dbm=manager) project_links = _make_project_links(project, questionnaire_code) if request.method == 'GET': count, results, error_message = _get_submissions(manager, questionnaire_code, request) return render_to_response('project/results.html', {'questionnaire_code': questionnaire_code, 'results': results, 'pages': count, 'error_message': error_message, 'project_links': project_links, 'project': project}, context_instance=RequestContext(request) ) if request.method == "POST": data_record_ids = json.loads(request.POST.get('id_list')) for each in data_record_ids: data_record = manager._load_document(each, DataRecordDocument) manager.invalidate(each) SubmissionLogger(manager).void_data_record(data_record.submission.get("submission_id")) current_page = request.POST.get('current_page') count, results = _load_submissions(int(current_page), manager, questionnaire_code) return render_to_response('project/log_table.html', {'questionnaire_code': questionnaire_code, 'results': results, 'pages': count, 'success_message': "The selected records have been deleted"}, context_instance=RequestContext(request))
def finish(request, project_id=None): manager = get_database_manager(request) project = models.get_project(project_id, manager) form_model = helper.load_questionnaire(manager, project.qid) if request.method == 'GET': project.to_test_mode(manager) number_of_registered_subjects = get_entity_count_for_type(manager, project.entity_type) number_of_registered_datasenders = get_entity_count_for_type(manager, 'reporter') profile = request.user.get_profile() organization = Organization.objects.get(org_id=profile.org_id) from_number = TEST_REPORTER_MOBILE_NUMBER organization_settings = OrganizationSetting.objects.get(organization=organization) to_number = organization_settings.sms_tel_number previous_link = reverse(datasenders_wizard, args=[project_id]) fields = form_model.fields[1:] if form_model.entity_defaults_to_reporter() else form_model.fields return render_to_response('project/finish_and_test.html', {'from_number':from_number, 'to_number':to_number, 'project':project, 'fields': fields, 'project_links': _make_links_for_finish_page(project_id, form_model), 'number_of_datasenders': number_of_registered_datasenders, 'number_of_subjects': number_of_registered_subjects, "previous": previous_link}, context_instance=RequestContext(request)) if request.method == 'POST': return HttpResponseRedirect(reverse(project_overview, args=[project_id]))
def submit(request): dbm = get_database_manager(request) post = _get_submission(request.POST) success = True try: web_player = WebPlayer(dbm, SubmissionHandler(dbm)) message = {k: v for (k, v) in post.get('message').items() if not is_empty(v)} if message.get(LOCATION_TYPE_FIELD_CODE) is not None: message[LOCATION_TYPE_FIELD_CODE]+= COUNTRY request = Request(message=message, transportInfo=TransportInfo(transport=post.get('transport'), source=post.get('source'), destination=post.get('destination'))) response = web_player.accept(request) if response.success: message = get_success_msg_for_registration_using(response, "web") else: message = get_submission_error_message_for(response.errors) entity_id = response.datarecord_id except MangroveException as exception: message = get_exception_message_for(exception=exception, channel="web") success = False entity_id = None return HttpResponse(json.dumps({'success': success, 'message': message, 'entity_id': entity_id}))
def wrapper(*args, **kw): if not len(get_all_projects(get_database_manager(args[0]))): return HttpResponseRedirect("/start?page=" + args[0].path) return f(*args, **kw)
def subjects(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) reg_form = get_form_model_by_code(manager, REGISTRATION_FORM_CODE) return render_to_response('project/subjects.html', {'fields': reg_form.fields, 'project':project, 'project_links':project_links}, context_instance=RequestContext(request))
def registered_datasenders(request, project_id=None): manager = get_database_manager(request) project, project_links = _get_project_and_project_link(manager, project_id) all_data = load_all_subjects_of_type(request) return render_to_response('project/registered_datasenders.html', {'project':project, 'project_links':project_links, 'all_data':all_data}, context_instance=RequestContext(request))