Exemple #1
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))
Exemple #2
0
def edit_user(request):
    if request.method == 'GET':
        profile = request.user.get_profile()
        if profile.mobile_phone == 'Not Assigned':
            profile.mobile_phone = ''
        org = get_organization(request)
        form = EditUserProfileForm(organization=org,
                                   reporter_id=profile.reporter_id,
                                   data=dict(
                                       title=profile.title,
                                       full_name=profile.user.first_name,
                                       username=profile.user.username,
                                       mobile_phone=profile.mobile_phone))
        return render_to_response(
            "accountmanagement/profile/edit_profile.html", {'form': form},
            context_instance=RequestContext(request))
    if request.method == 'POST':
        profile = request.user.get_profile()
        org = get_organization(request)

        form = EditUserProfileForm(organization=org,
                                   reporter_id=profile.reporter_id,
                                   data=request.POST)
        message = ""
        if form.is_valid():
            _update_user_and_profile(request, form)

            message = _('Profile has been updated successfully')
        return render_to_response(
            "accountmanagement/profile/edit_profile.html", {
                'form': form,
                'message': message
            },
            context_instance=RequestContext(request))
Exemple #3
0
 def get(self, request, *args, **kwargs):
     dbm = get_database_manager(request.user)
     organization = utils.get_organization(request)
     current_language_code = organization.language
     languages_list = get_available_project_languages(dbm)
     return self.render_to_response(RequestContext(request, {
         "available_languages": json.dumps(languages_list),
         'is_pro_sms': get_organization(request).is_pro_sms,
         "current_language": current_language_code,
     }))
def delete(request, project_id):
    dbm = get_database_manager(request.user)
    questionnaire = Project.get(dbm, project_id)
    dashboard_page = settings.HOME_PAGE + "?deleted=true"
    if questionnaire.is_void():
        return HttpResponseRedirect(dashboard_page)
    organization = get_organization(request)
    local_time_delta = get_country_time_delta(organization.country)
    survey_response_ids = get_survey_response_ids_from_request(
        dbm, request, questionnaire, local_time_delta)
    received_times = []
    for survey_response_id in survey_response_ids:
        survey_response = SurveyResponse.get(dbm, survey_response_id)
        received_times.append(
            datetime.datetime.strftime(
                convert_utc_to_localized(local_time_delta,
                                         survey_response.submitted_on),
                "%d/%m/%Y %X"))
        feeds_dbm = get_feeds_database(request.user)
        additional_feed_dictionary = get_project_details_dict_for_feed(
            questionnaire)
        delete_response = WebPlayerV2(dbm, feeds_dbm).delete_survey_response(
            survey_response, additional_feed_dictionary, websubmission_logger)
        mail_feed_errors(delete_response, dbm.database_name)
        if survey_response.data_record:
            ReportRouter().delete(
                get_organization(request).org_id, questionnaire.form_code,
                survey_response.data_record.id)

    if len(received_times):
        UserActivityLog().log(request,
                              action=DELETED_DATA_SUBMISSION,
                              project=questionnaire.name,
                              detail=json.dumps({
                                  "Date Received":
                                  "[%s]" % ", ".join(received_times)
                              }))
        response = encode_json({
            'success_message':
            ugettext("The selected submissions have been deleted"),
            'success':
            True
        })
    else:
        response = encode_json({
            'error_message': ugettext("No records deleted"),
            'success': False
        })

    return HttpResponse(response)
Exemple #5
0
def send_sms(request):

    try:
        input_request = jsonpickle.decode(request.raw_post_data)
        if not (input_request.get(NUMBERS) and input_request.get(MESSAGE)):
            raise ValueError
    except ValueError:
        return HttpResponse(status=400)

    organization = get_organization(request)
    current_month = datetime.date(datetime.datetime.now().year,
                                  datetime.datetime.now().month, 1)
    message_tracker = organization._get_message_tracker(current_month)
    client = SMSClient()
    result = {}
    org_tel_number = organization.tel_number()
    for number in input_request[NUMBERS]:
        if client.send_sms(org_tel_number, number,
                           unicode(input_request[MESSAGE]), MSG_TYPE_API,
                           message_tracker):
            result.update({number: "success"})
        else:
            result.update({number: "failure"})
    return HttpResponse(jsonpickle.encode(result, unpicklable=False),
                        content_type="application/javascript")
Exemple #6
0
def project_info(request, manager, form_model, project_id,
                 questionnaire_code):  #revisit:export
    project = Project.load(manager.database, project_id)
    is_summary_report = form_model.is_entity_type_reporter()
    rp_field = form_model.event_time_question
    organization = get_organization(request)
    in_trial_mode = organization.in_trial_mode
    has_rp = rp_field is not None
    is_monthly_reporting = rp_field.date_format.find(
        'dd') < 0 if has_rp else False

    return {
        "date_format": rp_field.date_format if has_rp else "dd.mm.yyyy",
        "is_monthly_reporting": is_monthly_reporting,
        "entity_type": form_model.entity_type[0].capitalize(),
        'project_links': (make_project_links(project, questionnaire_code)),
        'is_quota_reached': is_quota_reached(request,
                                             organization=organization),
        'project': project,
        'encoded_project_name': (urlquote(project.name)),
        'import_template_file_name': slugify(project.name),
        'questionnaire_code': questionnaire_code,
        'in_trial_mode': in_trial_mode,
        'reporting_period_question_text': rp_field.label if has_rp else None,
        'has_reporting_period': has_rp,
        'is_summary_report': is_summary_report
    }
Exemple #7
0
def get_stats(request, form_code):
    dbm = get_database_manager(request.user)
    questionnaire = get_project_by_code(dbm, form_code)
    search_parameters = {}
    search_parameters.update({"start_result_number": 0})
    search_parameters.update({"number_of_results": 0})
    filter_type = "success"
    search_parameters.update({"filter": filter_type})

    search_parameters.update({"sort_field": "ds_id"})
    search_parameters.update(
        {"order": "-" if request.POST.get('sSortDir_0') == "desc" else ""})
    search_filters = json.loads(request.POST.get('search_filters'))
    search_parameters.update({"search_filters": search_filters})
    search_text = search_filters.get("search_text", '')
    search_parameters.update({"search_text": search_text})
    organization = get_organization(request)
    local_time_delta = get_country_time_delta(organization.country)
    # total success submission count irrespective of current fields being present or not
    facet_results, total_submissions = get_facets_for_choice_fields(
        dbm, questionnaire, search_parameters, local_time_delta)

    return HttpResponse(json.dumps({
        'result':
        create_statistics_response(facet_results, questionnaire),
        'total':
        total_submissions
    }),
                        content_type='application/json')
Exemple #8
0
def _create_export_artifact(form_model, manager, request, search_filters):
    # 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", '')
    submission_type = request.GET.get(u'type')
    query_params.update({"search_text": search_text})
    query_params.update({"filter": submission_type})
    is_media = False
    if request.POST.get('is_media') == u'true':
        is_media = True
    organization = get_organization(request)
    local_time_delta = get_country_time_delta(organization.country)
    project_name = request.POST.get(u"project_name")
    current_language = get_language()
    if form_model.xform:
        return _advanced_questionnaire_export(current_language, form_model,
                                              is_media, local_time_delta,
                                              manager, project_name,
                                              query_params, submission_type)

    return SubmissionExporter(form_model, project_name, manager, local_time_delta, current_language) \
        .create_excel_response(submission_type, query_params)
Exemple #9
0
def analysis_results(request, project_id=None, questionnaire_code=None):
    manager = get_database_manager(request.user)
    org_id = helper.get_org_id_by_user(request.user)

    if request.method == 'GET':
        questionnaire = Project.get(manager, project_id)
        dashboard_page = settings.HOME_PAGE + "?deleted=true"
        if questionnaire.is_void():
            return HttpResponseRedirect(dashboard_page)

        filterable_fields = get_filterable_fields(questionnaire.fields, [])
        first_filterable_fields = filterable_fields.pop(
            0) if filterable_fields else None

        result_dict = {
            "xform": questionnaire.xform,
            "user_email": request.user.email,
            "is_quota_reached": is_quota_reached(request, org_id=org_id),
            "first_filterable_field": first_filterable_fields,
            "filterable_fields": filterable_fields,
            'is_pro_sms': get_organization(request).is_pro_sms,
            "is_media_field_present":
            questionnaire.is_media_type_fields_present
            # first 3 columns are additional submission data fields (ds_is, ds_name and submission_status
        }
        result_dict.update(
            project_info(request, questionnaire, questionnaire_code))
        return render_to_response('project/analysis_results.html',
                                  result_dict,
                                  context_instance=RequestContext(request))
Exemple #10
0
def failed_submissions(request):
    disable_link_class, hide_link_class, page_heading = projects_index(request)
    header_dict = OrderedDict([('from_number', 'Data Sender'),
                               ('created_at', 'Submission Date'),
                               ('form_code', 'Questionnaire Code'),
                               ('message', 'SMS Text'),
                               ('error1', 'Error Message')])
    organization = get_organization(request)

    return render_to_response('alldata/failed_submissions.html', {
        'page_heading':
        page_heading,
        'failedsubmissions_headers':
        header_dict,
        'disable_link_class':
        disable_link_class,
        'hide_link_class':
        hide_link_class,
        'is_crs_admin':
        is_crs_admin(request),
        'project_links':
        get_alldata_project_links(),
        'is_quota_reached':
        is_quota_reached(request, organization=organization)
    },
                              context_instance=RequestContext(request))
Exemple #11
0
    def post(self, is_update=None):
        organization = get_organization(self.request)
        questionnaire_form = self.form(self.request.POST, organization.country_name())
        if not questionnaire_form.is_valid():
            return self.invalid_data_response(questionnaire_form, is_update)

        return self.success_resposne(is_update, organization, questionnaire_form)
Exemple #12
0
def upgrade(request):
    profile = request.user.get_profile()
    organization = get_organization(request)
    if request.method == 'GET':
        form = UpgradeForm()
        return render_to_response("registration/upgrade.html", {'organization': organization, 'profile': profile,
                                                                'form': form}, context_instance=RequestContext(request))
    if request.method == 'POST':
        form = UpgradeForm(request.POST)
        if form.is_valid():
            organization.in_trial_mode = False
            organization.save()

            invoice_period = form.cleaned_data['invoice_period']
            preferred_payment = form.cleaned_data['preferred_payment']
            payment_details = PaymentDetails.objects.model(organization=organization, invoice_period=invoice_period,
                preferred_payment=preferred_payment)
            payment_details.save()
            message_tracker = MessageTracker.objects.filter(organization=organization)
            if message_tracker.count() > 0:
                tracker = message_tracker[0]
                tracker.reset()
            DataSenderOnTrialAccount.objects.filter(organization=organization).delete()
            _send_upgrade_email(request.user, request.LANGUAGE_CODE)
            messages.success(request, _("upgrade success message"))
            return HttpResponseRedirect(django_settings.LOGIN_REDIRECT_URL)

        return render_to_response("registration/upgrade.html", {'organization': organization, 'profile': profile,
                                                                'form': form}, context_instance=RequestContext(request))
Exemple #13
0
def settings(request):
    if request.method == 'GET':
        organization = get_organization(request)
        organization_form = OrganizationForm(instance=organization)

        return render_to_response("accountmanagement/account/org_settings.html",
                {'organization_form': organization_form}, context_instance=RequestContext(request))

    if request.method == 'POST':
        organization = Organization.objects.get(org_id=request.POST["org_id"])
        organization_form = OrganizationForm(request.POST, instance=organization).update()
        if organization_form.errors:
            message = ""
        else:
            message = _('Settings have been updated successfully')
            changed_data = organization_form.changed_data
            if len(changed_data) != 0:
                detail_dict = dict()
                current_lang = get_language()
                activate("en")
                for changed in changed_data:
                    label = u"%s" % organization_form.fields[changed].label
                    detail_dict.update({label: organization_form.cleaned_data.get(changed)})
                activate(current_lang)
                detail_as_string = json.dumps(detail_dict)
                UserActivityLog().log(request, action=CHANGED_ACCOUNT_INFO, detail=detail_as_string)

        return render_to_response("accountmanagement/account/org_settings.html",
                {'organization_form': organization_form, 'message': message}, context_instance=RequestContext(request))
Exemple #14
0
def start(request):
    text_dict = {'project': _('Questionnaires'), 'datasenders': _('Data Senders'),
                 'subjects': _('Identification Numbers'), 'alldata': _('Questionnaires')}

    title_dict = {'project': _('Questionnaires'), 'datasenders': _('Data Senders'),
                  'subjects': _('Identification Numbers'), 'alldata': _('Questionnaires')}

    tabs_dict = {'project': 'questionnaires', 'datasenders': 'data_senders',
                 'subjects': 'subjects', 'alldata': 'questionnaires'}

    help_url_dict = {'projet': 'https://www.datawinners.com/%s/find-answers-app/category/proj/?template=help',
                     'datasenders': 'https://www.datawinners.com/%s/find-answers-app/category/allds/?template=help',
                     'subjects': 'https://www.datawinners.com/%s/find-answers-app/category/idnos/?template=help',
                     'alldata': 'https://www.datawinners.com/%s/find-answers-app/category/proj/?template=help'}
    
    page = request.GET['page']
    page = page.split('/')
    url_tokens = [each for each in page if each != '']
    text = text_dict[url_tokens[-1]]
    title = title_dict[url_tokens[-1]]
    help_url = help_url_dict[url_tokens[-1]] % _("wp_language")
    return render_to_response('dashboard/start.html',
                              {'text': text, 'title': title, 'active_tab': tabs_dict[url_tokens[-1]],
                               'help_url': help_url, 'is_pro_sms': get_organization(request).is_pro_sms},
                              context_instance=RequestContext(request))
Exemple #15
0
def access_denied(request):
    org = get_organization(request)
    return render_to_response("accountmanagement/account/access_denied.html", {
        'is_pro_sms': org.is_pro_sms,
        'current_lang': get_language()
    },
                              context_instance=(RequestContext(request)))
Exemple #16
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:
        messages.error(
            request,
            _("Your organization's account Administrator %s cannot be deleted")
            % (ngo_admin_user_profile.user.first_name), "error_message")
    else:
        detail = user_activity_log_details(
            User.objects.filter(id__in=django_ids))
        delete_datasenders_from_project(manager, all_ids)
        for user_id in django_ids:
            handle_feature_toggle_impact_for_deleted_user(user_id)

        delete_entity_instance(manager, all_ids, REPORTER, transport_info)
        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}))
Exemple #17
0
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}))
Exemple #18
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}))
Exemple #19
0
def create_poll(request):
    if request.method == 'POST':
        organization = get_organization(request)
        if not _is_smsc_configured(organization):
            return HttpResponse(
                json.dumps({
                    'success':
                    False,
                    'error_message':
                    _("Your message could not be sent.")
                }))

        manager = get_database_manager(request.user)
        is_active, project_id, project_name = get_active_form_model_name_and_id(
            manager)
        if not is_active:
            response_dict = _create_response_dict(request)
            return HttpResponse(json.dumps(response_dict))

        else:
            return HttpResponse(
                json.dumps({
                    'success': False,
                    'error_message': 'Another poll is active',
                    'project_name_unique': project_name
                }))
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}))
Exemple #21
0
def _create_project_post_response(request, manager):
    project_info = json.loads(request.POST['profile_form'])
    try:
        ngo_admin = NGOUserProfile.objects.get(user=request.user)
        is_open_survey_allowed = _is_open_survey_allowed(request, request.POST.get('is_open_survey'))
        questionnaire = create_questionnaire(post=request.POST, manager=manager, name=project_info.get('name'),
                                             language=project_info.get('language', request.LANGUAGE_CODE),
                                             reporter_id=ngo_admin.reporter_id,
                                             is_open_survey=is_open_survey_allowed)
    except (QuestionCodeAlreadyExistsException, QuestionAlreadyExistsException,
            EntityQuestionAlreadyExistsException) as ex:
        return {'success': False, 'error_message': _(ex.message), 'error_in_project_section': False}

    org = get_organization(request)

    code_has_errors, error_message, name_has_errors = validate_questionnaire_name_and_code(questionnaire, org)

    if not code_has_errors and not name_has_errors:
        associate_account_users_to_project(manager, questionnaire)
        questionnaire.update_doc_and_save()
        UserActivityLog().log(request, action=CREATED_QUESTIONNAIRE, project=questionnaire.name,
                              detail=questionnaire.name)
        return {'success': True, 'project_id': questionnaire.id}

    return {'success': False,
            'error_message': error_message,
            'error_in_project_section': False,
            'code_has_errors': code_has_errors,
            'name_has_errors': name_has_errors}
Exemple #22
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))
Exemple #23
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))
def show_log(request):
    org_id = get_organization(request).org_id
    args = dict(organization=org_id)
    if request.method == 'GET':
        form = LogFilterForm(request=request)
    else:
        form = LogFilterForm(request.POST, request=request)
        filter = form.data.copy()
        filter.pop("csrfmiddlewaretoken")
        for key, value in filter.items():
            if value != "":
                if key == "daterange":
                    dates = value.split(" %s " % ugettext("to"))
                    args["log_date__gte"] = convert_dmy_to_ymd(dates[0])
                    try:
                        args[
                            "log_date__lte"] = "%s 23:59:59" % convert_dmy_to_ymd(
                                dates[1])
                    except KeyError:
                        args["log_date__lte"] = "%s 23:59:59" % date.today()
                    continue
                args[key] = value
    log_data = UserActivityLog.objects.select_related().filter(
        **args).order_by("-log_date")
    return render_to_response(
        "activitylog/activitylog.html", {
            'form': form,
            'log_data': repr(encode_json([log.to_render()
                                          for log in log_data]))
        },
        context_instance=RequestContext(request))
Exemple #25
0
def new_user(request):
    org = get_organization(request)
    add_user_success = False
    if request.method == 'GET':
        profile_form = UserProfileForm()
        return render_to_response("accountmanagement/account/add_user.html", {'profile_form': profile_form,
                                                                              'is_pro_sms': org.is_pro_sms,
                                                                              'current_lang': get_language(),
                                                                              },
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        manager = get_database_manager(request.user)
        org = get_organization(request)
        form = UserProfileForm(organization=org, data=request.POST)

        if form.is_valid():
            username = form.cleaned_data.get('username')
            if not form.errors:
                user = User.objects.create_user(username, username, 'test123')
                user.first_name = form.cleaned_data['full_name']
                group = Group.objects.filter(name="Project Managers")
                user.groups.add(group[0])
                user.save()
                mobile_number = form.cleaned_data['mobile_phone']
                ngo_user_profile = NGOUserProfile(user=user, title=form.cleaned_data['title'],
                                                  mobile_phone=mobile_number,
                                                  org_id=org.org_id)
                ngo_user_profile.reporter_id = make_user_as_a_datasender(manager=manager, organization=org,
                                                                         current_user_name=user.get_full_name(),
                                                                         mobile_number=mobile_number, email=username)
                ngo_user_profile.save()
                associate_user_with_existing_project(manager, ngo_user_profile.reporter_id)
                reset_form = PasswordResetForm({"email": username})
                if reset_form.is_valid():
                    send_email_to_data_sender(reset_form.users_cache[0], request.LANGUAGE_CODE, request=request,
                                              type="created_user",organization=org)
                    name = form.cleaned_data.get("full_name")
                    form = UserProfileForm()
                    add_user_success = True
                    detail_dict = dict({"Name": name})
                    UserActivityLog().log(request, action=ADDED_USER, detail=json.dumps(detail_dict))

        return render_to_response("accountmanagement/account/add_user.html",
                                  {'profile_form': form, 'add_user_success': add_user_success,
                                   'current_lang': get_language()},
                                  context_instance=RequestContext(request))
Exemple #26
0
    def response_for_post_request(self, is_update=None):
        questionnaire_form = self.form(self.request.POST)
        quota_reached = is_quota_reached(self.request)
        if not questionnaire_form.is_valid() or quota_reached:
            form_context = get_form_context(self.questionnaire,
                                            questionnaire_form, self.manager,
                                            self.hide_link_class,
                                            self.disable_link_class)
            form_context.update({'is_quota_reached': quota_reached})
            return render_to_response(self.template,
                                      form_context,
                                      context_instance=RequestContext(
                                          self.request))

        success_message = None
        error_message = None
        # if self.is_data_sender:
        #     questionnaire_form.cleaned_data['eid'] = self.request.user.get_profile().reporter_id
        try:
            created_request = helper.create_request(questionnaire_form,
                                                    self.request.user.username,
                                                    is_update=is_update)
            reporter_id = self.request.POST.get('dsid')
            response = self.player_response(created_request, reporter_id)
            if response.success:
                ReportRouter().route(
                    get_organization(self.request).org_id, response)
                success_message = _("Successfully submitted")
            else:
                questionnaire_form._errors = helper.errors_to_list(
                    response.errors, self.questionnaire.fields)
        except DataObjectNotFound as exception:
            logger.exception(exception)
            message = exception_messages.get(DataObjectNotFound).get(WEB)
            error_message = _(message) % (self.questionnaire.entity_type[0],
                                          self.questionnaire.entity_type[0])
        except Exception as exception:
            logger.exception('Web Submission failure:-')
            error_message = _(
                get_exception_message_for(exception=exception,
                                          channel=Channel.WEB))

        _project_context = get_form_context(self.questionnaire,
                                            questionnaire_form,
                                            self.manager,
                                            self.hide_link_class,
                                            self.disable_link_class,
                                            is_update=is_update)

        _project_context.update({
            'success_message': success_message,
            'error_message': error_message,
            'questionnaire_form': self.form(),
        })

        return render_to_response(self.template,
                                  _project_context,
                                  context_instance=RequestContext(
                                      self.request))
Exemple #27
0
def get_page_heading(request):
    organization = get_organization(request)
    if request.user.get_profile().reporter:
        return "Data Submission"
    if organization.is_pro_sms:
        return "Questionnaires & Polls"
    else:
        return "Questionnaires"
Exemple #28
0
def upgrade(request, token=None):
    profile = request.user.get_profile()
    organization = get_organization(request)
    if request.method == 'GET':
        form = UpgradeForm()
        organization_form = OrganizationForm(instance=organization)
        profile_form = EditUserProfileForm(
            data=dict(title=profile.title,
                      first_name=profile.user.first_name,
                      last_name=profile.user.last_name,
                      username=profile.user.username,
                      mobile_phone=profile.mobile_phone))
        return render_to_response("registration/upgrade.html", {
            'organization': organization_form,
            'profile': profile_form,
            'form': form
        },
                                  context_instance=RequestContext(request))
    if request.method == 'POST':
        form = UpgradeForm(request.POST)
        organization = Organization.objects.get(org_id=request.POST["org_id"])
        organization_form = OrganizationForm(request.POST,
                                             instance=organization).update()
        profile_form = EditUserProfileForm(request.POST)
        if form.is_valid() and organization_form.is_valid(
        ) and profile_form.is_valid():
            organization.save()

            invoice_period = form.cleaned_data['invoice_period']
            preferred_payment = form.cleaned_data['preferred_payment']

            payment_details = PaymentDetails.objects.model(
                organization=organization,
                invoice_period=invoice_period,
                preferred_payment=preferred_payment)
            payment_details.save()
            message_tracker = MessageTracker(organization=organization,
                                             month=datetime.datetime.today())
            message_tracker.save()

            DataSenderOnTrialAccount.objects.filter(
                organization=organization).delete()
            _send_upgrade_email(request.user, request.LANGUAGE_CODE)
            _update_user_and_profile(request, profile_form)
            messages.success(request, _("upgrade success message"))
            if token:
                request.user.backend = 'django.contrib.auth.backends.ModelBackend'
                sign_in(request, request.user)
                Token.objects.get(pk=token).delete()
            return HttpResponseRedirect(django_settings.LOGIN_REDIRECT_URL)

        return render_to_response("registration/upgrade.html", {
            'organization': organization_form,
            'profile': profile_form,
            'form': form
        },
                                  context_instance=RequestContext(request))
Exemple #29
0
def find_dbm_for_web_sms(request):
    incoming_request = dict()
    MangroveWebSMSRequestProcessor().process(http_request=request, mangrove_request=incoming_request)
    incoming_request['organization'] = get_organization(request)
    incoming_request['next_state'] = submit_to_player
    import logging
    websubmission_logger = logging.getLogger("websubmission")
    incoming_request["logger"] = websubmission_logger
    return incoming_request
Exemple #30
0
 def log(self, request, *args, **kwargs):
     from datawinners.utils import get_organization
     ong = get_organization(request)
     user = request.user
     entry = UserActivityLog(user=user,
                             organization=ong.org_id,
                             *args,
                             **kwargs)
     entry.save()