Пример #1
0
def get_projects_status(request):
    response_projects = []
    manager = get_database_manager(request.user)
    client_projects = json.loads(request.POST['projects'])

    for client_project in client_projects:
        try:
            server_project = FormModel.get(manager, client_project['id'])
            if (server_project._doc.void):
                response_projects.appened({
                    'id': client_project['id'],
                    'status': 'server-deleted'
                })
            elif server_project.revision != client_project['rev']:
                response_projects.append({
                    'id': server_project.id,
                    'status': 'outdated'
                })
        except Exception:
            response_projects.append({
                'id': client_project['id'],
                'status': 'server-deleted'
            })

    return response_json_cors(response_projects)
Пример #2
0
    def post(self, request, *args, **kwargs):
        manager = get_database_manager(request.user)
        questionnaires = self._get_projects(manager, request)
        projects_name = Set()
        removed_rep_ids = Set()
        selected_rep_ids = data_sender_short_codes(request, manager)

        for questionnaire in questionnaires:
            dashboard_page = settings.HOME_PAGE + "?deleted=true"
            if questionnaire.is_void():
                return HttpResponseRedirect(dashboard_page)
            for rep_id in selected_rep_ids:
                if rep_id in questionnaire.data_senders:
                    questionnaire.delete_datasender(manager, rep_id)
                    projects_name.add(questionnaire.name.capitalize())
                    removed_rep_ids.add(rep_id)

        if len(removed_rep_ids):
            UserActivityLog().log(request,
                                  action=REMOVED_DATA_SENDER_TO_PROJECTS,
                                  detail=json.dumps({
                                      "Unique ID":
                                      "[%s]" % ", ".join(removed_rep_ids),
                                      "Projects":
                                      "[%s]" % ", ".join(projects_name)
                                  }))

        return HttpResponse(
            json.dumps({
                "success":
                True,
                "message":
                _("The Data Sender(s) are removed from Questionnaire(s) successfully"
                  )
            }))
Пример #3
0
def rename_group(request):
    dbm = get_database_manager(request.user)
    current_group_name = request.POST['group_name']
    new_group_name = request.POST['new_group_name']
    try:
        group = get_group_by_name(dbm, current_group_name)
        if check_uniqueness_of_group(dbm, new_group_name):
            contact_ids = _get_reporter_ids_for_group_name(
                dbm, current_group_name, None)
            _rename_group_for_contacts(contact_ids, dbm, current_group_name,
                                       new_group_name)
            group.update_name(new_group_name)
            group.save()
            return HttpResponse(status=200,
                                content=json.dumps({'success': True}))
        else:
            return HttpResponse(
                status=200,
                content=json.dumps({
                    'success':
                    False,
                    'message':
                    ugettext("Group with same name already exists.")
                }))
    except DataObjectNotFound:
        return HttpResponse(status=400)
Пример #4
0
def export_count(request):
    if request.method == 'GET':
        return HttpResponse(status=405)

    submission_type = request.GET.get(u'type')
    post_body = json.loads(request.POST['data'])
    search_filters = post_body['search_filters']
    questionnaire_code = post_body['questionnaire_code']
    manager = get_database_manager(request.user)
    questionnaire = get_project_by_code(manager, questionnaire_code)
    organization = get_organization(request)
    local_time_delta = get_country_time_delta(organization.country)

    # the number_of_results limit will not be used for result-set size since scan-scroll api does not support it.
    # it is specified since the code-flow requires its value to be present

    query_params = {
        "search_filters": search_filters,
        "start_result_number": 0,
        "number_of_results": 4000,
        "order": "",
        "sort_field": "date"
    }

    search_text = search_filters.get("search_text", '')
    query_params.update({"search_text": search_text})
    query_params.update({"filter": submission_type})

    submission_count = get_submission_count(manager, questionnaire,
                                            query_params, local_time_delta)
    return HttpResponse(mimetype='application/json',
                        content=json.dumps({"count": submission_count}))
Пример #5
0
    def post(self, request, *args, **kwargs):
        user = request.user
        manager = get_database_manager(user)
        search_parameters = {}
        search_filters = json.loads(request.POST.get('search_filters', ''))
        search_text = request.POST.get('sSearch', '').strip()
        search_filters.update({"search_text": search_text})
        search_parameters.update(
            {"start_result_number": int(request.POST.get('iDisplayStart'))})
        search_parameters.update(
            {"number_of_results": int(request.POST.get('iDisplayLength'))})
        search_parameters.update(
            {"sort_field": self._get_order_field(request.POST, manager)})
        search_parameters.update({"search_filters": search_filters})
        search_parameters.update(
            {"order": "-" if request.POST.get('sSortDir_0') == "desc" else ""})

        query_fields, datasenders = get_data_sender_search_results(
            manager, search_parameters)
        total_count = get_data_sender_without_search_filters_count(
            manager, search_parameters)
        filtered_count = get_data_sender_count(manager, search_parameters)
        datasenders = DatasenderQueryResponseCreator().create_response(
            datasenders)

        return HttpResponse(jsonpickle.encode(
            {
                'data': datasenders,
                'iTotalDisplayRecords': filtered_count,
                'iDisplayStart': int(request.POST.get('iDisplayStart')),
                "iTotalRecords": total_count,
                'iDisplayLength': int(request.POST.get('iDisplayLength'))
            },
            unpicklable=False),
                            content_type='application/json')
Пример #6
0
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)

            if entity_type_already_defined(manager, entity_name):
                raise EntityTypeAlreadyDefined(u"Type: %s is already defined" %
                                               u'.'.join(entity_name))

            create_registration_form(manager, entity_name)
            define_type(manager, entity_name)
            message = _("Entity definition successful")
            success = True
            UserActivityLog().log(request,
                                  action=ADDED_IDENTIFICATION_NUMBER_TYPE,
                                  project=entity_name[0].capitalize())
        except EntityTypeAlreadyDefined:
            message = _("%s already exists.") % (entity_name[0].capitalize(), )
    else:
        message = form.errors['entity_type_regex']
    return HttpResponse(json.dumps({
        'success': success,
        'message': _(message)
    }))
Пример #7
0
def delete_users(request):
    if request.method == 'GET':
        raise Http404

    django_ids = request.POST.get("all_ids").split(";")
    all_ids = NGOUserProfile.objects.filter(user__in=django_ids).values_list(
        'reporter_id', flat=True)
    manager = get_database_manager(request.user)
    organization = get_organization(request)
    transport_info = TransportInfo("web", request.user.username, "")
    ngo_admin_user_profile = get_ngo_admin_user_profiles_for(organization)[0]

    if ngo_admin_user_profile.reporter_id in all_ids:
        admin_full_name = ngo_admin_user_profile.user.first_name + ' ' + ngo_admin_user_profile.user.last_name
        messages.error(
            request,
            _("Your organization's account Administrator %s cannot be deleted")
            % (admin_full_name), "error_message")
    else:
        detail = user_activity_log_details(
            User.objects.filter(id__in=django_ids))
        delete_entity_instance(manager, all_ids, REPORTER, transport_info)
        delete_datasenders_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, REPORTER)
        action = DELETED_USERS
        UserActivityLog().log(request, action=action, detail=detail)
        messages.success(request, _("User(s) successfully deleted."))

    return HttpResponse(json.dumps({'success': True}))
Пример #8
0
def sent_reminders(request, project_id):
    dbm = get_database_manager(request.user)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    questionnaire = Project.get(dbm, project_id)
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    organization = Organization.objects.get(
        org_id=request.user.get_profile().org_id)
    is_trial_account = organization.in_trial_mode
    html = 'project/sent_reminders_trial.html' if organization.in_trial_mode else 'project/sent_reminders.html'
    return render_to_response(html, {
        'project':
        questionnaire,
        "project_links":
        make_project_links(questionnaire),
        'is_quota_reached':
        is_quota_reached(request, organization=organization),
        'reminders':
        get_all_reminder_logs_for_project(project_id, dbm),
        'in_trial_mode':
        is_trial_account,
        'questionnaire_code':
        questionnaire.form_code
    },
                              context_instance=RequestContext(request))
Пример #9
0
def registered_subjects(request, project_id, entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    current_entity_type = entity_type
    if not current_entity_type:
        current_entity_type = questionnaire.entity_type[0]

    subject = get_entity_type_info(current_entity_type, manager=manager)
    project_links = get_project_link(questionnaire, current_entity_type)
    subject_form_model = get_form_model_by_entity_type(manager,
                                                       [current_entity_type])
    in_trial_mode = _in_trial_mode(request)
    return render_to_response(
        'project/subjects/registered_subjects_list.html', {
            'project': questionnaire,
            'project_links': project_links,
            'is_quota_reached': is_quota_reached(request),
            "subject": subject,
            'in_trial_mode': in_trial_mode,
            'project_id': project_id,
            'entity_type': current_entity_type,
            'subject_headers': header_fields(subject_form_model),
            'questionnaire_code': questionnaire.form_code,
            'form_code': subject_form_model.form_code
        },
        context_instance=RequestContext(request))
Пример #10
0
def get_submission_breakup(request, project_id):
    dbm = get_database_manager(request.user)
    questionnaire = Project.get(dbm, project_id)
    submission_success, submission_errors = submission_stats(
        dbm, questionnaire.id)
    response = json.dumps([submission_success, submission_errors])
    return HttpResponse(response)
Пример #11
0
def rename_project(request, project_id):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    new_project_name = request.POST.get('data', '').strip()
    if len(new_project_name) == 0:
        return HttpResponse(json.dumps({
            "status":
            "error",
            "message":
            ugettext("This field is required.")
        }),
                            content_type='application/json')

    if (questionnaire.name != new_project_name):
        questionnaire.name = new_project_name
        try:
            questionnaire.save(process_post_update=True)
            UserActivityLog().log(request,
                                  action=RENAMED_PROJECT,
                                  project=questionnaire.name)
            return HttpResponse(json.dumps({"status": "success"}),
                                content_type='application/json')
        except DataObjectAlreadyExists as e:
            return HttpResponse(json.dumps({
                "status":
                "error",
                "message":
                ugettext("Questionnaire with same name already exists.")
            }),
                                content_type='application/json')
    return HttpResponse(json.dumps({"status": "success"}),
                        content_type='application/json')
Пример #12
0
def geo_json_for_project(request, project_id, entity_type=None):
    dbm = get_database_manager(request.user)
    location_list = []

    try:
        if entity_type:
            first_geocode_field = _get_first_geocode_field_for_entity_type(
                dbm, entity_type)
            if first_geocode_field:
                unique_ids = get_all_entities(dbm, [entity_type], limit=1000)
                location_list.extend(
                    get_location_list_for_entities(first_geocode_field,
                                                   unique_ids))
        else:
            questionnaire = Project.get(dbm, project_id)
            unique_ids = by_short_codes(dbm,
                                        questionnaire.data_senders,
                                        ["reporter"],
                                        limit=1000)
            location_list.extend(get_location_list_for_datasenders(unique_ids))

    except DataObjectNotFound:
        pass

    location_geojson = {"type": "FeatureCollection", "features": location_list}
    return HttpResponse(json.dumps(location_geojson))
Пример #13
0
 def get(self, request, reporter_id, *args, **kwargs):
     create_data_sender = False
     manager = get_database_manager(request.user)
     reporter_entity = ReporterEntity(
         get_by_short_code(manager, reporter_id, [REPORTER]))
     entity_links = {
         'registered_datasenders_link': reverse("all_datasenders")
     }
     datasender = {'short_code': reporter_id}
     get_datasender_user_detail(datasender, request.user)
     email = datasender.get(
         'email') if datasender.get('email') != '--' else False
     name = reporter_entity.name
     phone_number = reporter_entity.mobile_number
     location = reporter_entity.location
     geo_code = reporter_entity.geo_code
     form = ReporterRegistrationForm(
         initial={
             'name': name,
             'telephone_number': phone_number,
             'location': location,
             'geo_code': geo_code
         })
     return self.render_to_response({
         'reporter_id': reporter_id,
         'form': form,
         'project_links': entity_links,
         'email': email,
         'create_data_sender': create_data_sender
     })
Пример #14
0
def get_questions_paginated_or_by_ids(request):
    manager = get_database_manager(request.user)
    start = int(request.GET.get('start', '0'))
    length = int(request.GET.get('length', '10'))
    ids = request.GET.getlist('ids')

    if ids:
        projects = [
            _project_details(manager, project_id) for project_id in ids
        ]
        projects = list(filter(lambda x: x != None, projects))
        return response_json_cors(projects)

    project_list = []
    rows = manager.load_all_rows_in_view('all_projects', descending=True)
    for row in rows:
        questionnaire = FormModel.get(manager, row['id'])
        if questionnaire.xform:
            project_temp = dict(name=questionnaire.name,
                                project_uuid=questionnaire.id,
                                version=questionnaire._doc.rev)
            project_list.append(project_temp)

    return response_json_cors({
        "projects": project_list[start:start + length],
        "total": len(project_list),
        "start": start,
        "length": length
    })
Пример #15
0
def import_subjects_from_project_wizard(request, form_code):
    manager = get_database_manager(request.user)
    error_message, failure_imports, success_message, short_code_subject_details_dict = import_module.import_data(
        request, manager, default_parser=XlsOrderedParser, form_code=form_code)
    subject_details = {}

    if len(short_code_subject_details_dict) != 0:
        detail_dict = dict()
        form_model = get_form_model_by_code(manager, form_code)
        entity_type = form_model.entity_type[0]
        short_codes = []
        for short_code in short_code_subject_details_dict.keys():
            short_codes.append(short_code)

        subject_details = _format_imported_subjects_datetime_field_to_str(
            form_model, short_code_subject_details_dict)
        detail_dict.update({entity_type: "[%s]" % ", ".join(short_codes)})
        UserActivityLog().log(request,
                              action=IMPORTED_IDENTIFICATION_NUMBER,
                              detail=json.dumps(detail_dict))

    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,
            'successful_imports':
            subject_details,
        }))
Пример #16
0
def questionnaire(request, project_id):
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        questionnaire = Project.get(manager, project_id)
        if questionnaire.is_void():
            return HttpResponseRedirect(settings.HOME_PAGE + "?deleted=true")
        fields = questionnaire.fields
        existing_questions = json.dumps(fields, default=field_to_json)
        project_links = make_project_links(questionnaire)
        success, error = submission_stats(manager, questionnaire.form_code)
        project_has_submissions = (success + error > 0)
        in_trial_mode = _in_trial_mode(request)
        is_success = False
        active_language = request.LANGUAGE_CODE
        if "success" in [m.message for m in messages.get_messages(request)]:
            is_success = True
        return render_to_response(
            'project/questionnaire.html', {
                "existing_questions": repr(existing_questions),
                'questionnaire_code': questionnaire.form_code,
                'project': questionnaire,
                'project_has_submissions': project_has_submissions,
                'project_links': project_links,
                'is_quota_reached': is_quota_reached(request),
                'in_trial_mode': in_trial_mode,
                'is_success': is_success,
                'active_language': active_language,
                'post_url': reverse(edit_project, args=[project_id]),
                'unique_id_types': get_unique_id_types(manager),
                'preview_links': get_preview_and_instruction_links()
            },
            context_instance=RequestContext(request))
Пример #17
0
def map_admin(request, entity_type=None):
    form_model = get_form_model_by_entity_type(
        get_database_manager(request.user), [entity_type.lower()])
    entity_preference = get_entity_preference(get_db_manager("public"),
                                              _get_organization_id(request),
                                              entity_type)

    filters_in_entity_preference = []
    details_in_entity_preference = []
    specials_in_entity_preference = []

    if entity_preference is not None:
        filters_in_entity_preference = entity_preference.filters
        details_in_entity_preference = entity_preference.details
        specials_in_entity_preference = entity_preference.specials

    filters = _build_filterable_fields(form_model.form_fields,
                                       filters_in_entity_preference)
    details = _build_details(form_model.form_fields,
                             details_in_entity_preference)
    specials = _build_specials(form_model.form_fields,
                               specials_in_entity_preference)

    return render_to_response('entity/map_edit.html', {
        "entity_type": entity_type,
        "form_code": form_model.form_code,
        "filters": json.dumps(filters),
        "details": json.dumps(details),
        "specials": json.dumps(specials)
    },
                              context_instance=RequestContext(request))
Пример #18
0
def questionnaire_preview(request, project_id=None, sms_preview=False):
    manager = get_database_manager(request.user)
    if request.method == 'GET':
        dashboard_page = settings.HOME_PAGE + "?deleted=true"
        questionnaire = Project.get(manager, project_id)
        if questionnaire.is_void():
            return HttpResponseRedirect(dashboard_page)
            #if form_model.is_entity_type_reporter():
        #    fields = helper.hide_entity_question(form_model.fields)
        project_links = make_project_links(questionnaire)
        questions = []
        fields = questionnaire.fields
        for field in fields:
            question = helper.get_preview_for_field(field)
            questions.append(question)
        example_sms = "%s" % (questionnaire.form_code)
        example_sms += get_example_sms(fields)

    template = 'project/questionnaire_preview.html' if sms_preview else 'project/questionnaire_preview_list.html'
    return render_to_response(
        template, {
            "questions": questions,
            'questionnaire_code': questionnaire.form_code,
            'project': questionnaire,
            'project_links': project_links,
            'is_quota_reached': is_quota_reached(request),
            'example_sms': example_sms,
            'org_number': get_organization_telephone_number(request)
        },
        context_instance=RequestContext(request))
Пример #19
0
def edit_subject_questionnaire(request, entity_type=None):
    # edit subject type questionnaire view
    manager = get_database_manager(request.user)
    if entity_type is None:
        return HttpResponseRedirect(reverse(all_subject_types))

    form_model = get_form_model_by_entity_type(manager, [entity_type.lower()])
    if form_model is None:
        form_model = get_form_model_by_code(manager, REGISTRATION_FORM_CODE)
    fields = form_model.fields

    existing_questions = json.dumps(fields, default=field_to_json)

    return render_to_response('entity/questionnaire.html', {
        'existing_questions':
        repr(existing_questions),
        'questionnaire_code':
        form_model.form_code,
        'language':
        form_model.activeLanguages[0],
        'entity_type':
        entity_type,
        'is_pro_sms':
        get_organization(request).is_pro_sms,
        'post_url':
        reverse(save_questionnaire),
        'unique_id_types':
        json.dumps([{
            "name": unique_id_type.capitalize(),
            "value": unique_id_type
        } for unique_id_type in get_unique_id_types(manager)
                    if unique_id_type != entity_type]),
    },
                              context_instance=RequestContext(request))
Пример #20
0
def subject_registration_form_preview(request,
                                      project_id=None,
                                      entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    if not entity_type:
        entity_type = questionnaire.entity_type[0]
    if request.method == "GET":
        fields, project_links, questions, registration_questionnaire = _get_registration_form(
            manager, questionnaire, entity_type)
        example_sms = get_example_sms_message(
            fields, registration_questionnaire.form_code)
        return render_to_response(
            'project/questionnaire_preview_list.html', {
                "questions": questions,
                'questionnaire_code': registration_questionnaire.form_code,
                'project': questionnaire,
                'project_links': project_links,
                'is_quota_reached': is_quota_reached(request),
                'example_sms': example_sms,
                'org_number': get_organization_telephone_number(request)
            },
            context_instance=RequestContext(request))
Пример #21
0
def my_poll_recipients_count(request, project_id):
    dbm = get_database_manager(request.user)
    questionnaire = Project.get(dbm, project_id)
    contact_dict = _get_poll_recipients(dbm, questionnaire)
    return HttpResponse(content_type='application/json',
                        content=json.dumps(
                            {'my_poll_recipients': contact_dict}))
Пример #22
0
def edit_my_subject_questionnaire(request, project_id, entity_type=None):
    manager = get_database_manager(request.user)
    questionnaire = Project.get(manager, project_id)
    if not entity_type:
        entity_type = questionnaire.entity_type[0]
    project_links = get_project_link(questionnaire, entity_type)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    reg_form = _get_subject_form_model(manager, entity_type)
    if reg_form is None:
        reg_form = form_model.get_form_model_by_code(manager,
                                                     REGISTRATION_FORM_CODE)
    fields = reg_form.fields
    existing_questions = json.dumps(fields, default=field_to_json)
    subject = get_entity_type_info(entity_type, manager=manager)
    return render_to_response('project/subject_questionnaire.html', {
        'project': questionnaire,
        'entity_type': entity_type,
        'project_links': project_links,
        'is_quota_reached': is_quota_reached(request),
        'existing_questions': repr(existing_questions),
        'questionnaire_code': reg_form.form_code,
        'language': reg_form.activeLanguages[0],
        'project_id': questionnaire.id,
        'subject': subject,
        'post_url': reverse(subject_save_questionnaire)
    },
                              context_instance=RequestContext(request))
Пример #23
0
    def post(self, request, *args, **kwargs):
        parser_dict = {
            '.xls': XlsDatasenderParser,
            '.xlsx': XlsxDataSenderParser
        }
        manager = get_database_manager(request.user)
        file_extension = os.path.splitext(request.GET["qqfile"])[1]
        parser = parser_dict.get(file_extension, None)
        is_update = request.GET.get('is_update') == 'true'
        error_message, failure_imports, success_message, successful_imports = import_module.import_data(
            request, manager, default_parser=parser, is_update=is_update)

        imported_data_senders = parse_successful_imports(successful_imports)
        self._convert_anonymous_submissions_to_registered(
            imported_data_senders, manager)

        self.update_activity_log(request, successful_imports)
        transaction.commit(
        )  #Mandatory for manually managed transaction blocks. Here it won't save anything

        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,
                'successful_imports':
                imported_data_senders
            }))
Пример #24
0
    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request", None)
        assert request is not None
        forms.Form.__init__(self, *args, **kwargs)
        org_id = request.user.get_profile().org_id

        users_rs = NGOUserProfile.objects.select_related().\
            extra(select={'lower_username': '******'}).\
            filter(org_id=org_id).order_by("lower_username")

        all_users = [("", _("All Users"))]

        all_users.extend([(user.user.id,
                           "%s %s" % (user.user.first_name.capitalize(),
                                      user.user.last_name.capitalize()))
                          for user in users_rs])

        self.fields["user"].choices = all_users
        project_choices = [("", _("All Projects"))]
        projects = get_all_projects(get_database_manager(request.user))
        project_choices.extend(
            sorted([(prj["value"]["name"], prj["value"]["name"].capitalize())
                    for prj in projects],
                   key=itemgetter(1, 0)))
        self.fields["project"].choices = project_choices
Пример #25
0
    def post(self, request, *args, **kwargs):
        manager = get_database_manager(request.user)
        questionnaires = self._get_projects(manager, request)
        projects_name = Set()
        for questionnaire in questionnaires:
            for id in data_sender_short_codes(request, manager):
                questionnaire.associate_data_sender_to_project(manager, id)
            projects_name.add(questionnaire.name.capitalize())
        ids = request.POST["ids"].split(';')
        if len(ids):
            UserActivityLog().log(request,
                                  action=ADDED_DATA_SENDERS_TO_PROJECTS,
                                  detail=json.dumps({
                                      "Unique ID":
                                      "[%s]" % ", ".join(ids),
                                      "Projects":
                                      "[%s]" % ", ".join(projects_name)
                                  }))

        return HttpResponse(
            json.dumps({
                "success":
                True,
                "message":
                _("The Data Sender(s) are added to Questionnaire(s) successfully"
                  )
            }))
Пример #26
0
def all_subject_types(request):
    manager = get_database_manager(request.user)
    subjects_data = load_subject_type_with_projects(manager)
    subjects_count = get_subjects_count(manager)
    if "deleted_subject" in request.GET.keys():
        deleted_subject_error_message = _(
            'Sorry. The Identification Number Type you are looking for has been deleted'
        )
        return render_to_response(
            'entity/all_subject_types.html', {
                'all_data': subjects_data,
                'current_language': translation.get_language(),
                'subjects_count': subjects_count,
                'is_pro_sms': get_organization(request).is_pro_sms,
                'deleted_subject_error_message':
                [deleted_subject_error_message],
            },
            context_instance=RequestContext(request))
    else:
        return render_to_response(
            'entity/all_subject_types.html', {
                'all_data': subjects_data,
                'is_pro_sms': get_organization(request).is_pro_sms,
                'current_language': translation.get_language(),
                'subjects_count': subjects_count,
            },
            context_instance=RequestContext(request))
Пример #27
0
def delete_data_senders(request):
    manager = get_database_manager(request.user)
    organization = get_organization(request)
    entity_type = request.POST['entity_type']
    all_ids = data_sender_short_codes(request, manager)
    superusers = rep_id_name_dict_of_users(manager)
    non_superuser_rep_ids = [
        id for id in all_ids if id not in superusers.keys()
    ]
    transport_info = TransportInfo("web", request.user.username, "")

    delete_datasenders_from_project(manager, non_superuser_rep_ids)
    delete_entity_instance(manager, non_superuser_rep_ids, entity_type,
                           transport_info)
    delete_datasender_users_if_any(non_superuser_rep_ids, organization)
    if organization.in_trial_mode:
        delete_datasender_for_trial_mode(manager, non_superuser_rep_ids,
                                         entity_type)
    log_activity(
        request,
        DELETED_DATA_SENDERS,
        "%s: [%s]" %
        (entity_type.capitalize(), ", ".join(non_superuser_rep_ids)),
    )
    messages = get_success_message(entity_type)
    return HttpResponse(json.dumps({'success': True, 'message': messages}))
Пример #28
0
def all_subjects(request, subject_type):
    manager = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(manager, [subject_type])
    if not form_model:
        all_subject_types_page = '/entity/subjects/' + "?deleted_subject=true"
        return HttpResponseRedirect(all_subject_types_page)
    else:
        header_dict = header_fields(form_model)
        form_model = get_form_model_by_entity_type(manager, [subject_type])
        return render_to_response(
            'entity/all_subjects.html', {
                'subject_headers': header_dict,
                'current_language': translation.get_language(),
                'entity_type': subject_type,
                'questions': form_model.fields,
                'form_code': form_model.form_code,
                'is_pro_sms': get_organization(request).is_pro_sms,
                'links': {
                    'create_subject':
                    reverse("create_subject", args=(subject_type, )) +
                    "?web_view=True",
                    'edit_subject_registration_form':
                    reverse("edit_subject_questionnaire",
                            args=(subject_type, ))
                }
            },
            context_instance=RequestContext(request))
Пример #29
0
def add_or_remove_contact_from_groups(request):
    dbm = get_database_manager(request.user)
    group_names = json.loads(request.POST['group-names'])
    current_group_name = request.POST['current_group_name']
    contact_ids = json.loads(request.POST['contact_ids'])
    all_selected = json.loads(request.POST['all_selected'])
    action = request.POST['action']
    success = True
    try:
        if not all_selected:
            _update_group_for_contacts(contact_ids, dbm, group_names, action)
        else:
            search_query = request.POST['search_query']
            contact_ids = _get_reporter_ids_for_group_name(
                dbm, current_group_name, search_query)
            _update_group_for_contacts(contact_ids, dbm, group_names, action)
        message = 'The Contact(s) are added to Group(s) successfully.' if action == 'add' else 'The Contact(s) are removed from Group(s) successfully.'
    except Exception as e:
        # log exception
        message = ugettext('Failed to add in to group.')
        success = False
    return HttpResponse(content=json.dumps({
        'success': success,
        'message': ugettext(message)
    }),
                        content_type='application/json')
Пример #30
0
def check_submissions_status(request, project_uuid):
    req_id_version_array = json.loads(request.POST['submissions'])
    outdated_ids = []
    insync_ids = []
    req_id_version_dict = {}

    manager = get_database_manager(request.user)
    for single_dict in req_id_version_array:
        req_id_version_dict[single_dict['id']] = single_dict['rev']

    req_ids = req_id_version_dict.keys()
    rows = manager.load_all_rows_in_view(
        "survey_response_by_survey_response_id", keys=req_ids)
    id_version_dict = {
        r.value['_id']: r.value['_rev']
        for r in rows if not r.value['void']
    }

    req_ids_set = Set(req_ids)
    ids = id_version_dict.keys()
    ids_not_found = list(req_ids_set.difference(ids))
    ids_found = req_ids_set.intersection(ids)

    for id_found in ids_found:
        if req_id_version_dict[id_found] == id_version_dict[id_found]:
            insync_ids.append(id_found)
        else:
            outdated_ids.append(id_found)

    return response_json_cors({
        'both': insync_ids,
        'server-deleted': ids_not_found,
        'outdated': outdated_ids
    })