def age(self, request):

        dateFrom, dateTo, resort = get_param(request)

        user_role = get_roleid_user(resort, request.user)

        if user_role == 1:
            return Response(
                {
                    _("detail"):
                    _("You do not have permission to view analytics")
                },
                status=403)

        data_key = get_data_key(resort)

        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  SUM(case when age_years>=0 and age_years <= 10 then 1 else 0 end) AS G0_10,
  SUM(case when age_years>=11 and age_years <= 15 then 1 else 0 end) AS G11_15,
  SUM(case when age_years>=16 and age_years <= 18 then 1 else 0 end) AS G16_18,
  SUM(case when age_years>=19 and age_years <= 21 then 1 else 0 end) AS G19_21,
  SUM(case when age_years>=22 and age_years <= 30 then 1 else 0 end) AS G22_30,
  SUM(case when age_years>=31 and age_years <= 100 then 1 else 0 end) AS G31_
FROM incidents_incident INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id, incidents_patients, date_part('year',age(to_timestamp(pgp_sym_decrypt(incidents_patients.dob, '%s'::TEXT),'YYYYMMDD'))) as age_years
WHERE incidents_incident.incident_pk = incidents_patients.incident_id
AND incidents_incident.resort_id = %d AND custom_user_users.user_connected = %d AND incidents_incident.dt_created IS NOT NULL
AND incidents_incident.dt_created >= '%s' AND incidents_incident.dt_created <= '%s'
AND incidents_incident.incident_status_id <> 9;""" %
                           (data_key, resort.resort_pk,
                            request.user.user_connected, dateFrom, dateTo))

            data = dictfetchall(cursor)

        return Response({'success': True, 'data': data[0]}, status=200)
Exemplo n.º 2
0
    def patient(self, request, pk=None):

        try:
            incident = Incident.objects.get(incident_id=pk)
            if incident.incident_status.order == 9:
                raise Exception
        except:
            return Response({_('detail'): _('incident does not exists')}, status=400)

        data_key = get_data_key(incident.resort)
        return Response(get_patient_info(incident.incident_pk, data_key), status=200)
Exemplo n.º 3
0
def public_incident(request):
    access_token = request.META['HTTP_AUTHORIZATION'].split(' ')[1]
    access_token_object = AccessToken.objects.get(token=access_token)
    resort = None

    try:
        resort_oauth_application = ResortOauthApp.objects.get(oauth_app=access_token_object.application)
        resort_network_key = request.data.get('resort_network_key')
        if resort_network_key is not None:
            resort = Resort.objects.get(network_key=resort_network_key)
            if resort != resort_oauth_application.resort:
                raise Exception
        else:
            return Response({_('detail'): _('resort_network_key is not provided')}, status=400)
    except:
        return Response({_('detail'): _('you do not have access to this resource')}, status=400)

    missing_field = []
    for key in ['reporter_name', 'reporter_phone', 'field_52ca456962ba8']:
        if not request.data.has_key(key):
            missing_field.append(key)
    if missing_field:
        return Response({_('detail'): "missing the field %s" % ','.join(missing_field)}, status=400)

    status = IncidentStatus.objects.get(pk=1)
    incoming_data = request.data
    incoming_data.pop('resort_network_key', None)
    incoming_data, validation_error, missing_fields_with_data = validate_incident_data(incoming_data, resort)

    if validation_error:
        return Response(validation_error, status=400)

    if resort.use_sequential_incident_id == 1:
        incident_sequence = get_incident_sequence(resort)
    else:
        incident_sequence = 0

    user_role = UserRoles.objects.get(role_id=2)
    assigned_user = UserResortMap.objects.filter(resort=resort, role=user_role, user__user_connected=1).first()

    try:
        new_incident = Incident(resort=resort, assigned_to=assigned_user.user, incident_status=status,
                                incident_sequence=incident_sequence)
        new_incident.save()
        data_key = get_data_key(resort)
        incident_json = update_patient(incoming_data, new_incident.incident_pk, True, data_key)
    except:
        return Response({_('detail'): _('invalid incident information provided')}, status=400)

    return Response({'incident_id': new_incident.incident_id}, status=200)
Exemplo n.º 4
0
    def create(self, request):
        incoming_data = request.data
        incoming_data.pop('dateTimeFormat', None)
        user = request.user
        resort = get_resort_for_user(user)
        incoming_data, validation_error, missing_fields_with_data = validate_incident_data(incoming_data, resort)

        if validation_error:
            return Response(validation_error, status=400)

        logger.info("Create Incident",
                    extra={'request': request, 'tags': {'user': user.email}, 'data': {"data": request.data}})

        status = IncidentStatus.objects.get(pk=1)

        if resort.use_sequential_incident_id == 1 and user.user_connected == 1:
            incident_sequence = get_incident_sequence(resort)
        else:
            incident_sequence = 0

        try:
            new_incident = Incident(resort=resort, assigned_to=user, incident_status=status,
                                    incident_sequence=incident_sequence)
            new_incident.save()
            data_key = get_data_key(resort)
            incident_json = update_patient(incoming_data, new_incident.incident_pk, True, data_key)
        except:
            return Response({_('detail'): _('invalid incident information provided')}, status=400)

        notes = incident_note(incident_json, user, new_incident)
        if notes:
            new_incident.incident_json['notes'] = notes
            new_incident.save()

        audit_incident(new_incident, resort, user, user, user, incident_json)

        status_history(new_incident, status, user)

        return Response({"incident_id": new_incident.incident_id,
                         "incident_pk": new_incident.incident_sequence if resort.use_sequential_incident_id == 1 else new_incident.incident_pk},
                        status=200)
Exemplo n.º 5
0
    def retrieve(self, request, pk=None):
        user = request.user
        incident = Incident.objects.filter(incident_id=pk).first()

        # If incident status is deleted then allow incident to be fetched
        if incident.incident_status.order == 9:
            incident = None

        if incident is not None:
            user_role = get_roleid_user(incident.resort, user)
            if user_role == 1 or user.user_connected == 0:
                if incident.assigned_to != user:
                    return Response({_("detail"): _("You do not have permission to retrieve the incident")}, status=403)

            response_data = get_incident_data(incident.incident_pk)
            response_data = clean_data(incident.resort, response_data)
            response_data['incident_id'] = str(incident.incident_id)
            if incident.resort.use_sequential_incident_id == 1:
                response_data['incident_pk'] = incident.incident_sequence
            else:
                response_data['incident_pk'] = incident.incident_pk

            response_data['assigned_to'] = str(incident.assigned_to.user_id)
            incident_status_data = IncidentStatusSerializer(incident.incident_status)
            response_data['incident_status'] = incident_status_data.data
            response_data['dt_created'] = datetime.strftime(incident.dt_created, "%Y-%m-%d %H:%M:%S")

            notes = IncidentNotes.objects.filter(incident=incident).order_by('-note_date')

            response_data['notes'] = IncidentNotesSerializer(notes, fields=('note_id', 'note_date', 'note', 'user'),
                                                             many=True).data
            data_key = get_data_key(incident.resort)
            response_data.update(get_patient_info(incident.incident_pk, data_key))
            return Response(response_data, status=200)
        else:
            return Response({_("detail"): _("Incident does not exist")}, status=400)
Exemplo n.º 6
0
    def bar(self, request):
        tempdata = []
        output_format = request.query_params.get('output_format', 'json')

        if request.user.user_connected == 0:
            return Response(
                {_('detail'): _('you do not have access to report')},
                status=403)

        resort = get_resort_for_user(request.user)
        text_data_key = get_data_key(resort)
        b = incident_template_field_type_mapping(resort.incident_template)
        datetime_object = extract_date_chart(request.data, resort)

        for idx, value in enumerate(request.data):
            from_query = ''
            where_query = ''
            inner_join = ''
            cross_join = ''
            table_no = 0
            inner_patient = False
            inner_note = False
            where_parameter = []
            group_by_query = ''
            order_by_query = ''
            dateFrom, dateTo = datetime_object[idx][
                'dateFrom'], datetime_object[idx]['dateTo']
            scale = scale_mapping[value.get('scale', 'date')]

            if scale == 'date':
                column_query = 'incidents_incident.dt_created::TIMESTAMP::DATE as columndetail'
            else:
                if scale in ["hour", "dow"]:
                    column_query = 'extract( ' + scale + ' FROM incidents_incident.dt_created::TIMESTAMP) + 1 as columndetail'
                elif scale == 'hdow':
                    column_query = "extract(DOW FROM incidents_incident.dt_created::TIMESTAMP) + 1 as columndetail, extract( HOUR FROM incidents_incident.dt_created::TIMESTAMP) + 1 as columndetail1"
                    group_by_query = ',columndetail1'
                    order_by_query = ',columndetail1'
                else:
                    column_query = 'extract( ' + scale + ' FROM incidents_incident.dt_created::TIMESTAMP) as columndetail'

            for data_key, data_value in value['data'].iteritems():
                if data_key == 'total_incident':
                    pass
                elif data_key in patient_fields:
                    if not inner_patient:
                        inner_join += ' INNER JOIN incidents_patients ON incidents_patients.incident_id = incidents_incident.incident_pk'
                        cross_join += """CROSS JOIN (SELECT '%s' As datakey) As keys""" % (
                            text_data_key)
                        inner_patient = True
                    for id, value in enumerate(data_value):
                        if data_key in encrypted_fields:
                            where_query += " AND pgp_sym_decrypt(incidents_patients.%s, keys.datakey) ILIKE %s" % (
                                data_key, '%s')
                            where_parameter.append("%" + data_value[id] + "%")
                        elif data_key == 'sex':
                            where_query += " AND incidents_patients.%s = %s" % (
                                'sex', '%s')
                            where_parameter.append(data_value[id].lower())
                        else:
                            where_query += " AND incidents_patients.%s = %s" % (
                                data_key, '%s')
                            where_parameter.append(data_value[id])
                elif data_key in note_fields:
                    if not inner_note:
                        inner_join += ' INNER JOIN incidents_incidentnotes ON incidents_incidentnotes.incident_id = incidents_incident.incident_pk'
                        inner_note = True
                    for id, value in enumerate(data_value):
                        where_query += " AND incidents_incidentnotes.%s = %s" % (
                            note_field_map[data_key], '%s')
                        where_parameter.append(data_value[id])
                elif data_key in location_field:
                    if not 'field_52ca456962ba8' in from_query:
                        from_query += ", CAST((incidents_incident.incident_data -> 'field_52ca456962ba8') AS JSON) as location_json"
                    for id, value in enumerate(data_value):
                        where_query += " AND (location_json ->> '%s') = %s" % (
                            data_key.split('____')[1], '%s')
                        where_parameter.append(data_value[id])
                elif b[data_key]['type'] == 'text' or b[data_key][
                        'type'] == 'int':
                    for id, value in enumerate(data_value):
                        where_query += " AND (incident_data ->> '%s') = %s" % (
                            b[data_key]['key'], '%s')
                        where_parameter.append(data_value[id])
                elif b[data_key]['type'] == 'array':
                    if not b[data_key]['key'] in from_query:
                        from_query += ", json_array_elements(incidents_incident.incident_data -> '%s') as table%d" % (
                            b[data_key]['key'], table_no)
                    for id, value in enumerate(data_value):
                        where_query += " AND CAST(table%d AS TEXT) = %s" % (
                            table_no, '%s')
                        where_parameter.append('"' + data_value[id] + '"')
                    table_no += 1
                elif 'repeating' in b[data_key]['type']:
                    if not b[data_key]['key'] in from_query:
                        from_query += ", CAST(json_array_elements(incidents_incident.incident_data -> '%s') AS JSON) as table%d" % (
                            b[data_key]['key'], table_no)
                    for id, value in enumerate(data_value):
                        where_query += " AND (table%d ->> '%s') = %s" % (
                            table_no, b[data_key]['sub_key'], '%s')
                        where_parameter.append(data_value[id])
            with connection.cursor() as cursor:
                query = """SELECT %d as field, %s , count(*) count FROM incidents_incident INNER JOIN custom_user_users ON assigned_to_id = custom_user_users.user_pk INNER JOIN incidents_incidentstatus ON (incidents_incident.incident_status_id = incidents_incidentstatus.incident_status_id)%s %s %s WHERE resort_id = %d AND custom_user_users.user_connected = 1 AND dt_created IS NOT NULL AND dt_created >= '%s' AND dt_created <= '%s' AND incidents_incidentstatus.order IN (1,2,3,4,5,6,7,8) %s GROUP BY columndetail %s ORDER BY columndetail%s;""" % \
                        ( idx + 1, column_query, inner_join, from_query, cross_join, resort.resort_pk, dateFrom, dateTo, where_query, group_by_query, order_by_query)
                cursor.execute('BEGIN;')
                cursor.execute("SET LOCAL TIME ZONE %s;", [resort.timezone])
                cursor.execute(query, where_parameter)
                data = dictfetchall(cursor)
                cursor.execute('END;')
                tempdata.append(
                    add_missing_data(data, idx + 1, dateFrom, dateTo, scale))

        final_data = merge_compare_data(tempdata)

        if output_format == 'csv':
            scale = scale_mapping[request.data[0].get('scale', 'date')]
            return sendfile(request,
                            settings.MEDIA_ROOT +
                            dict_to_csv_report(final_data, 'bar', scale),
                            attachment=True)

        return Response(final_data)
Exemplo n.º 7
0
    def table(self, request):

        if request.user.user_connected == 0:
            return Response(
                {_('detail'): _('you do not have access to report')},
                status=403)

        dateFrom, dateTo, resort = get_param_post(request)
        text_data_key = get_data_key(resort)

        chunk = int(request.query_params.get('chunk', 100))
        offset = int(request.query_params.get('offset', 0))
        output_format = request.query_params.get('output_format', 'json')
        from_query = ''
        where_query = ''
        inner_join = ''
        cross_join = ''
        table_no = 0
        inner_patient = False
        inner_note = False
        response_data = {}
        where_parameters = []

        b = incident_template_field_type_mapping(resort.incident_template)

        def shouldRegex(field):
            if field == 'field_539158b37814e': return False
            if field == 'field_52dd8a24e95a6': return False
            if field == 'field_53c386190a2dd': return False
            if field == 'field_5334b101c8779': return False
            if field == 'field_52ca437b62b9c': return False
            if field == 'field_52ca43f362ba0': return False
            if field == 'field_52ca429c62b98': return False
            if field == 'field_52ca405959d2c': return False
            if field == 'field_52ca3fcc59d29': return False
            if field == 'field_52ca431e62b9b': return False
            if field == 'field_54b084fb2d255': return False
            return True

        for data_key, data_value in request.data.iteritems():

            if data_key in patient_fields:
                if not inner_patient:
                    inner_join += ' INNER JOIN incidents_patients ON incidents_patients.incident_id = incidents_incident.incident_pk'
                    cross_join += """CROSS JOIN (SELECT '%s'::TEXT As datakey) As keys""" % (
                        text_data_key)
                    inner_patient = True
                data_length = len(data_value)

                if data_length == 1:
                    if data_key in encrypted_fields:
                        where_query += " AND pgp_sym_decrypt(incidents_patients.%s, keys.datakey) ILIKE %s" % (
                            data_key, '%s')
                        where_parameters.append("%" + data_value[0] + "%")
                    elif data_key == 'sex':
                        where_query += " AND incidents_patients.%s = %s" % (
                            'sex', '%s')
                        where_parameters.append(data_value[0].lower())
                    else:
                        where_query += " AND incidents_patients.%s ILIKE %s" % (
                            data_key, '%s')
                        where_parameters.append(data_value[0])
                else:
                    temp_query = ''
                    for id, value in enumerate(data_value):
                        if data_key in encrypted_fields:
                            temp_query += "%spgp_sym_decrypt(incidents_patients.%s, keys.datakey) ILIKE %s" % (
                                " OR " if id > 0 else "", data_key, '%s')
                            where_parameters.append("%" + data_value[id] + "%")
                        elif data_key == 'sex':
                            temp_query += "%sincidents_patients.%s = %s" % (
                                " OR " if id > 0 else "", 'sex', '%s')
                            where_parameters.append(data_value[id].lower())
                        else:
                            temp_query += "%sincidents_patients.%s ILIKE %s" % (
                                " OR " if id > 0 else "", data_key, '%s')
                            where_parameters.append(data_value[id])
                    where_query += " AND " + "(" + temp_query + ")"

            elif data_key in note_fields:
                if not inner_note:
                    inner_join += ' INNER JOIN incidents_incidentnotes ON incidents_incidentnotes.incident_id = incidents_incident.incident_pk'
                    inner_note = True
                data_length = len(data_value)

                if data_length == 1:
                    where_query += " AND incidents_incidentnotes.%s ILIKE %s" % (
                        note_field_map[data_key], '%s')
                    where_parameters.append("%" + data_value[0] + "%")
                else:
                    temp_query = ""
                    for id, value in enumerate(data_value):
                        temp_query += "%sincidents_incidentnotes.%s ILIKE %s" % (
                            " OR " if id > 0 else "", note_field_map[data_key],
                            '%s')
                        where_parameters.append("%" + data_value[id] + "%")
                    where_query += " AND " + "(" + temp_query + ")"

            elif data_key in location_field:
                if not 'field_52ca456962ba8' in from_query:
                    from_query += ", CAST((incidents_incident.incident_data -> 'field_52ca456962ba8') AS JSON) as location_json"
                data_length = len(data_value)

                if data_length == 1:
                    where_query += " AND (location_json ->> '%s') ILIKE %s" % (
                        data_key.split('____')[1], '%s')
                    where_parameters.append("%" + data_value[0] + "%")
                else:
                    temp_query = ""
                    for id, value in enumerate(data_value):
                        temp_query += "%s(location_json ->> '%s') ILIKE %s" % (
                            " OR " if id > 0 else "",
                            data_key.split('____')[1], '%s')
                        where_parameters.append("%" + data_value[id] + "%")
                    where_query += " AND " + "(" + temp_query + ")"

            elif b[data_key]['type'] == 'text' or b[data_key]['type'] == 'int':
                data_length = len(data_value)

                if data_length == 1:
                    where_query += " AND (incident_data ->> '%s') %s %s" % (
                        b[data_key]['key'], "ILIKE" if type(
                            data_value[0]) in [str, unicode] else "=", '%s')
                    if shouldRegex(data_key):
                        where_parameters.append(
                            "%" + data_value[0] + "%" if type(data_value[0]) in
                            [str, unicode] else str(data_value[0]))
                    else:
                        where_parameters.append(data_value[0])
                else:
                    temp_query = ""
                    for id, value in enumerate(data_value):
                        temp_query += "%s(incident_data ->> '%s') %s %s" % (
                            " OR " if id > 0 else "", b[data_key]['key'],
                            "ILIKE" if type(data_value[0]) in [str, unicode]
                            else "=", '%s')
                        where_parameters.append(
                            "%" + data_value[id] +
                            "%" if type(data_value[id]) in
                            [str, unicode] else str(data_value[id]))
                    where_query += " AND " + "(" + temp_query + ")"
            elif b[data_key]['type'] == 'array':
                if not b[data_key]['key'] in from_query:
                    from_query += ", json_array_elements(incidents_incident.incident_data -> '%s') as table%d" % (
                        b[data_key]['key'], table_no)
                data_length = len(data_value)

                if data_length == 1:
                    where_query += " AND CAST(table%d AS TEXT) = %s" % (
                        table_no, '%s')
                    where_parameters.append('"' + data_value[0] + '"')
                else:
                    temp_query = ""
                    for id, value in enumerate(data_value):
                        temp_query += "%sCAST(table%d AS TEXT) = %s" % (
                            " OR " if id > 0 else "", table_no, '%s')
                        where_parameters.append('"' + data_value[id] + '"')
                    where_query += " AND " + "(" + temp_query + ")"
                table_no += 1
            elif 'repeating' in b[data_key]['type']:
                if not b[data_key]['key'] in from_query:
                    from_query += ", CAST(json_array_elements(incidents_incident.incident_data -> '%s') AS JSON) as table%d" % (
                        b[data_key]['key'], table_no)

                data_length = len(data_value)

                if data_length == 1:
                    where_query += " AND (table%d ->> '%s') ILIKE %s" % (
                        table_no, b[data_key]['sub_key'], '%s')
                    where_parameters.append("%" + data_value[0] + "%")
                else:
                    temp_query = ""
                    for id, value in enumerate(data_value):
                        temp_query += "%s(table%d ->> '%s') ILIKE %s" % (
                            " OR " if id > 0 else "", table_no,
                            b[data_key]['sub_key'], '%s')
                        where_parameters.append("%" + data_value[id] + "%")
                    where_query += " AND " + "(" + temp_query + ")"
                table_no += 1

        with connection.cursor() as cursor:
            if output_format == 'json':
                query = """SELECT count(*) OVER() AS full_count, incident_pk
FROM incidents_incident INNER JOIN custom_user_users ON assigned_to_id = custom_user_users.user_pk INNER JOIN incidents_incidentstatus
    ON (incidents_incident.incident_status_id = incidents_incidentstatus.incident_status_id)%s%s
%s
WHERE resort_id = %d AND custom_user_users.user_connected = 1 AND dt_created IS NOT NULL AND dt_created >= '%s' AND dt_created <= '%s' AND incidents_incidentstatus.order IN (1,2,3,4,5,6,7,8)%s
GROUP BY incident_pk
ORDER BY incidents_incident.dt_created DESC
OFFSET %d
LIMIT %d;""" % (inner_join, from_query, cross_join, resort.resort_pk, dateFrom,
                dateTo, where_query, offset, chunk)
            elif output_format == 'csv':
                query = """SELECT count(*) OVER() AS full_count, incident_pk
FROM incidents_incident INNER JOIN custom_user_users ON assigned_to_id = custom_user_users.user_pk INNER JOIN incidents_incidentstatus
    ON (incidents_incident.incident_status_id = incidents_incidentstatus.incident_status_id)%s%s
%s
WHERE resort_id = %d AND custom_user_users.user_connected = 1 AND dt_created IS NOT NULL AND dt_created >= '%s' AND dt_created <= '%s' AND incidents_incidentstatus.order IN (1,2,3,4,5,6,7,8)%s
GROUP BY incident_pk
ORDER BY incidents_incident.dt_created DESC;""" % (
                    inner_join, from_query, cross_join, resort.resort_pk,
                    dateFrom, dateTo, where_query)
            cursor.execute(query, where_parameters)
            data = dictfetchall(cursor)

        incident_data = []
        if output_format == 'json':
            for val in data:
                incident_info = IncidentReportSerializer(
                    Incident.objects.get(incident_pk=val['incident_pk']),
                    fields=('incident_pk', 'incident_id', 'dt_created',
                            'incident_status', 'assigned_to'),
                    context={
                        'data_key': text_data_key
                    }).data
                incident_data.append(incident_info)

            response_data['offset'] = offset
            response_data['chunk'] = chunk
            response_data['count'] = data[0]['full_count'] if len(
                data) > 0 else 0
            response_data['results'] = incident_data

        elif output_format == 'csv':
            return sendfile(
                request,
                settings.MEDIA_ROOT + dict_to_csv_report(
                    get_report_data_for_csv(data, resort, text_data_key)),
                attachment=True)

        return Response(response_data, status=200)
Exemplo n.º 8
0
    def list(self, request, *args, **kwargs):
        user = self.request.user
        resort_id = request.query_params.get('resort_id')
        assigned_to = request.query_params.get('assigned_to')
        order_by = request.query_params.get('order_by', 'incident_pk')
        order_by_direction = request.query_params.get('order_by_direction', 'desc')
        include_status = map(int, request.query_params.get('include_status', '1, 2, 3, 4, 5, 6, 7, 8').split(','))

        if order_by_direction == 'desc':
            order = '-' + order_by
        elif order_by_direction == 'asc':
            order = order_by

        if resort_id is None:
            if not user.is_admin:
                resort = get_resort_for_user(user)
            else:
                resort = None
        else:
            if not uuid(resort_id):
                return Response({_('detail'): _('not a valid UUID')}, status=400)
            try:
                resort = Resort.objects.get(resort_id=resort_id)
            except ObjectDoesNotExist:
                return Response({_("detail"): _("Resort does not exists")}, status=400)

        user_role = get_roleid_user(resort, user)

        dateFrom = request.query_params.get('date_from', None)
        if dateFrom is None:
            dateFrom = datetime.today()
            dateFrom = dateFrom.strftime("%Y-%m-%d 00:00:00")
        else:
            dateFrom = (datetime.strptime(dateFrom, "%Y-%m-%d %H:%M:%S"))

        dateTo = request.query_params.get('date_to', None)
        if dateTo is None:
            dateTo = datetime.today()
            dateTo = dateTo.strftime("%Y-%m-%d 23:59:59")
        else:
            dateTo = (datetime.strptime(dateTo, "%Y-%m-%d %H:%M:%S"))

        # if request.query_params.get('date_from') is not None:
        #     date_from = datetime.datetime.strptime(request.query_params.get('date_from'), "%Y-%m-%d %H:%M:%S")
        # else:
        #     date_from = datetime.datetime.combine(timezone.now().date(), datetime.time(12, 0, 0))
        #
        # if request.query_params.get('date_to') is not None:
        #     date_to = datetime.datetime.strptime(request.query_params.get('date_to'), "%Y-%m-%d %H:%M:%S")
        # else:
        #     date_to = datetime.datetime.combine(timezone.now().date() + datetime.timedelta(days=1), datetime.time(12, 0, 0))

        if request.query_params.get('assigned_to') is not None:
            try:
                assigned_to = get_user_model().objects.get(user_id=request.query_params.get('assigned_to'))
            except ObjectDoesNotExist:
                return Response({_("detail"): _("assigned_to user does not exists")}, status=400)

        # If user is admin then show all the incidents across all the resorts
        if user.is_admin:
            if resort is None:
                query = Incident.objects.filter(dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)
            else:
                query = Incident.objects.filter(resort=resort, dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)

        # If user is resort patroller (or) connected to resort as SOLO user then only return incidents assigned to him
        elif user_role == 1 or user.user_connected == 0:
            query = Incident.objects.filter(resort=resort, assigned_to=user, dt_created__gte=dateFrom,
                                            dt_created__lte=dateTo, incident_status__order__in=include_status).order_by(
                order)

        # For manager, dispatcher connected with resort as networked user show all the incidents if assigned_to is not provided
        else:
            if assigned_to is None:
                query = Incident.objects.filter(resort=resort, dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                assigned_to__user_connected=1,
                                                incident_status__order__in=include_status).order_by(order)
            else:
                query = Incident.objects.filter(resort=resort, assigned_to=assigned_to, dt_created__gte=dateFrom,
                                                dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)

        queryset = self.filter_queryset(query)

        page = self.paginate_queryset(queryset)
        if page is not None:
            data_key = get_data_key(resort)
            serializer = IncidentListSerializer(page, fields=(
            'incident_pk', 'incident_id', 'dt_created', 'resort', 'incident_status', 'assigned_to'),
                                            many=True, context={'data_key': data_key})
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
Exemplo n.º 9
0
    def update(self, request, pk=None):
        incoming_data = request.data
        incoming_data.pop('dateTimeFormat', None)
        user = request.user
        resort = get_resort_for_user(user)
        incoming_data, validation_error, missing_fields_with_data = validate_incident_data(incoming_data, resort)

        if validation_error:
            logger.error("validation error",
                         extra={'request': request, 'detail': validation_error, 'tags': {'user': user.email},
                                'data': {"data": request.data}, "missing field": missing_fields_with_data})
            return Response(validation_error, status=400)

        logger.info("Update Incident",
                    extra={'request': request, 'tags': {'user': user.email}, 'data': {"data": request.data}})

        with transaction.atomic():
            incident = Incident.objects.select_for_update().filter(incident_id=pk).first()
            incoming_data = check_drug_administered(incoming_data, incident, user)
            data = incoming_data
            current_assigned = incident.assigned_to

            assigned_to = request.data.get('assigned_to')

            # Remove the redundant data from incident json
            data.pop('assigned_to', None)
            data.pop('incident_status', None)
            data.pop('incident_id', None)
            data.pop('incident_pk', None)
            data.pop('dateTimeFormat', None)

            assigned_user = None
            user_role = get_roleid_user(resort, user)

            # If incident status is deleted then dont allow the update of incident
            if incident.incident_status.order == 9:
                incident = None

            if incident is not None:
                # If user is patroller, then he/she can only update incident if following conditions are met
                # If incident is assigned to patroller
                # If incident is not in closed status
                if user_role == 1:
                    if incident.assigned_to != user or incident.incident_status.order == 8:
                        return Response({_("detail"): _("You do not have permission to edit this incident")},
                                        status=403)

                # If user is SOLO and incident is not assigned to him then deny the permission
                if user.user_connected == 0:
                    if incident.assigned_to != user:
                        return Response({_("detail"): _("You do not have permission to edit this incident")},
                                        status=403)

                if assigned_to is not None:
                    # Patroller does not have the permission to assign incident
                    assigned_user = get_user_model().objects.filter(user_id=assigned_to).first()
                    if assigned_user is None:
                        return Response({_("detail"): _("assigned_user does not exist")}, status=400)
                    if user_role == 1 and (not incident.assigned_to == assigned_user):
                        return Response({_("detail"): _("You do not have permission to assign this incident")},
                                        status=403)

                    incident.assigned_to = assigned_user
                else:
                    assigned_user = incident.assigned_to

                notes = incident_note(data, user, incident)
                if notes:
                    data['notes'] = notes

                # If incoming data contains dt_crated then update the it for incident
                if data.get('dt_created', ''):
                    dt_created = datetime.strptime(data.get('dt_created'), "%Y-%m-%d %H:%M:%S")
                    # if dt_created > (datetime.now() + timedelta(seconds=10)):
                    #     return Response({_("detail"): _("dt_created can not be a future date")}, status=400)
                    incident.dt_created = dt_created
                    data.pop('dt_created', None)

                incident_data = get_incident_data(incident.incident_pk)
                incident_data = clean_data(incident.resort, incident_data)
                data = merge_incident_data(incident_data, data)

                patient = Patients.objects.filter(incident=incident)

                data_key = get_data_key(resort)
                if patient:
                    # If incoming data has incident data then extract the patient data from it and also update the incident json
                    data = update_patient(data, incident.incident_pk, False, data_key)
                else:
                    data = update_patient(data, incident.incident_pk, True, data_key)

                incident.save()
                audit_incident(incident, resort, assigned_user, current_assigned, user, data)

                return Response({"incident_id": incident.incident_id}, status=200)
            else:
                return Response({_("detail"): _("Incident does not exist")}, status=400)
Exemplo n.º 10
0
    def save(self, *args, **kwargs):
        from apps.incidents.utils import get_data_key
        from apps.resorts.utils import template_update
        if self.domain_id is None:
            self.domain_id = Domains.objects.get(pk=1)

        # If this is a new resort then do the following
        # Update the template
        # If KMS is enabled then create new customer master key and generate new data_key using that CMK
        if self.pk is None:
            self.incident_template = template_update(self, True)
            client = create_client()
            if self.kms_enabled is True:
                response = client.create_key(Description=self.resort_name, KeyUsage='ENCRYPT_DECRYPT')
                self.kms_cmk = response['KeyMetadata']['Arn']

                response = client.generate_data_key(
                    KeyId=self.kms_cmk,
                    KeySpec='AES_256',
                )
                self.enc_data_key = base64.b64encode(response['CiphertextBlob'])
            else:
                self.kms_cmk = settings.GLOBAL_KMS_KEY_ID
                response = client.generate_data_key(
                    KeyId=self.kms_cmk,
                    KeySpec='AES_256',
                )
                self.enc_data_key = base64.b64encode(response['CiphertextBlob'])
            super(Resort, self).save(*args, **kwargs)  # Call the "real" save() method.
            update_resort_discovery(self, self.domain_id)
        # If the resort is already created then
        # Check if sequential numbering is on (or) not and perform operation accordingly
        # if KMS is enabled then create new master key and also create new data key using that CMK
        else:
            self.incident_template = template_update(self, False)
            resort = Resort.objects.get(resort_pk=self.pk)

            if resort.use_sequential_incident_id == OFF and self.use_sequential_incident_id == ON:
                if self.season_start_date:
                    startDate = dt.datetime.combine(self.season_start_date, dt.time())
                    endDate = startDate + dt.timedelta(days=365)

                    while startDate.date() <= dt.date.today():
                        for index, incident in enumerate(
                                Incident.objects.filter(dt_created__gte=startDate, dt_created__lte=endDate,
                                                        resort=self).exclude(incident_status__order=9).order_by(
                                    'dt_created')):
                            incident.incident_sequence = index + 1
                            incident.save()
                        startDate = startDate + dt.timedelta(days=365)
                        endDate = startDate + dt.timedelta(days=365)

            if (self.kms_enabled is True) and ((resort.kms_cmk == '') or (resort.kms_cmk is None)):
                client = create_client()
                response = client.create_key(Description=self.resort_name, KeyUsage='ENCRYPT_DECRYPT')
                self.kms_cmk = response['KeyMetadata']['Arn']

                pre_data_key = get_data_key(self)

                response = client.generate_data_key(
                    KeyId=self.kms_cmk,
                    KeySpec='AES_256',
                )
                self.enc_data_key = base64.b64encode(response['CiphertextBlob'])
                encrypt_patient_data_kms(self, pre_data_key, base64.b64encode(response['Plaintext']))
                upload_status, message = encrypt_s3_files(self, self.kms_cmk)

                if not upload_status:
                    raise Exception

            super(Resort, self).save(*args, **kwargs)  # Call the "real" save() method.
            if((resort.resort_name != self.resort_name) or (resort.domain_id != self.domain_id) or (resort.network_key != self.network_key)):
                update_resort_discovery(self, self.domain_id)