def injury_types(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)

        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  injury_types->>'injury_type' as injury,
  COUNT(injury_types->'injury_type') as num
FROM
  incidents_incident INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id,
  json_array_elements(incidents_incident.incident_data -> 'field_52d4798f6d227') as injury_types
WHERE
  resort_id = %d
  AND custom_user_users.user_connected = %d
  AND dt_Created IS NOT NULL AND dt_Created >= '%s' AND dt_Created <= '%s'
  AND incidents_incident.incident_status_id <> 9
GROUP BY injury_types->>'injury_type';""" %
                           (resort.resort_pk, request.user.user_connected,
                            dateFrom, dateTo))

            data = dictfetchall(cursor)

        return Response({'success': True, 'data': data}, status=200)
    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)
    def alcohol(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)

        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  extract(year from dt_created) as year,
  extract(month from dt_created) as month,
  SUM(case when incidents_incident.incident_data->>'field_52ca437b62b9c' = 'yes' then  1 else 0 end) as drugs,
  SUM(case when incidents_incident.incident_data->>'field_52ca3fcc59d29' = 'yes' then  1 else 0 end) as alcohol
FROM incidents_incident
INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id
WHERE resort_id = %d AND custom_user_users.user_connected = %d AND dt_Created IS NOT NULL AND dt_created >= '%s' AND dt_created <= '%s' AND incidents_incident.incident_status_id <> 9
GROUP BY 1,2
ORDER BY 1,2;""" % (resort.resort_pk, request.user.user_connected, dateFrom,
                    dateTo))

            data = dictfetchall(cursor)

        return Response({'success': True, 'data': data}, status=200)
    def referred_to(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)

        with connection.cursor() as cursor:
            cursor.execute(
                """SELECT
  incident_data ->>'field_52d48077a16be' AS referred_to ,
  COUNT(incident_data->>'field_52d48077a16be') AS num,
  ROUND((COUNT(incident_data->>'field_52d48077a16be')*100.0)/(SELECT CASE COUNT(*) WHEN 0 THEN 1 ELSE COUNT(*) END AS  total FROM incidents_incident WHERE resort_id = %s AND CAST(incidents_incident.incident_data->>'field_52d48077a16be' AS integer)>0 AND dt_created >= %s AND dt_created <= %s AND incident_status_id <> 9)) AS percent,
  (SELECT COUNT(*) AS  total FROM incidents_incident WHERE resort_id = %s AND CAST(incident_data->>'field_52d48077a16be' AS integer) > 0 AND dt_created >= %s AND dt_created <= %s AND incident_status_id <> 9)
FROM incidents_incident
INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id
WHERE resort_id = %s AND custom_user_users.user_connected = %s AND CAST(incident_data->>'field_52d48077a16be' AS integer) > 0  AND dt_created IS NOT NULL AND dt_created >= %s AND dt_created <= %s AND incident_status_id <> 9
GROUP BY 1;""", [
                    resort.resort_pk, dateFrom, dateTo, resort.resort_pk,
                    dateFrom, dateTo, resort.resort_pk,
                    request.user.user_connected, dateFrom, dateTo
                ])

            data = dictfetchall(cursor)

        return Response({'success': True, 'data': data}, status=200)
예제 #5
0
    def post(self, request, *args, **kwargs):

        user = request.user
        resort = get_resort_for_user(user)
        operation = request.GET.get('operation', 'generate')

        # Only manager has the permission to access the resource
        if resort is not None:
            role = get_roleid_user(resort=resort, user=user)
            if role != 3:
                return Response(
                    {_('detail'): _('you do not have permission to resource')},
                    status=400)
        else:
            return Response({_('detail'): _('no resort associated with user')},
                            status=400)

        if operation == 'generate':
            # If oauth app already exists then return existing credential
            try:
                app = ResortOauthApp.objects.get(resort=resort, is_active=True)
                app = app.oauth_app
            except:
                app = Application(
                    user=user,
                    authorization_grant_type='client-credentials',
                    client_type='confidential',
                    name=resort.resort_name)
                app.save()

                resort_oauth = ResortOauthApp(resort=resort, oauth_app=app)
                resort_oauth.save()
        elif operation == 'regenerate':
            try:
                app = ResortOauthApp.objects.get(resort=resort, is_active=True)
                oauth_app = app.oauth_app
                oauth_app.delete()
            except:
                pass

            app = Application(user=user,
                              authorization_grant_type='client-credentials',
                              client_type='confidential',
                              name=resort.resort_name)
            app.save()

            resort_oauth = ResortOauthApp(resort=resort, oauth_app=app)
            resort_oauth.save()

        return Response(
            {
                'client_id': app.client_id,
                'client_secret': app.client_secret
            },
            status=200)
예제 #6
0
    def post(self, request, *args, **kwargs):
        with transaction.atomic():
            incident_id = kwargs.get('uuid')

            if not uuid(incident_id):
                return Response({_('detail'): _('not a valid UUID')}, status=400)

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

            user_role = get_roleid_user(incident.resort, request.user)
            status_id = int(request.data.get('status_type_id'))

            if user_role != 3 and incident.incident_status.order == 8:
                return Response({_("detail"): _("You do not have permission to open this incident")}, status=403)
            elif user_role == 1 and status_id == 9:
                return Response({_("detail"): _("You do not have permission to delete this incident")}, status=403)

            if status_id is not None:
                try:
                    status = IncidentStatus.objects.get(incident_status_id=status_id)
                except ObjectDoesNotExist:
                    return Response({_("detail"): _("incident status not found")}, status=400)

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

            if updated_by is not None:
                try:
                    updated_user = get_user_model().objects.get(user_id=updated_by)
                except ObjectDoesNotExist:
                    return Response({_("detail"): _("updated_by user not found")}, status=400)
            else:
                updated_user = request.user

            incident.incident_status = status
            incident.save()

            if request.data.get('status_date') is not None:
                timestamp = datetime.strptime(request.data.get('status_date'), "%Y-%m-%d %H:%M:%S")
            else:
                timestamp = timezone.now()

            status_history(incident, status, updated_user, timestamp)

            return Response({"incident_id": incident.incident_id}, status=200)
    def patrollers(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)

        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  json_array_elements(CAST (resorts_resort.incident_template AS JSON)->'DashboardItems'->'field_52d47aac9bd13'->'RepeatingQuestions'->'patroller'->'Values') ->> (patrollers_incident->>'patroller') as name,
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"170"' THEN 1 ELSE 0 END) AS "primary",
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"171"' THEN 1 ELSE 0 END) AS secondary,
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"172"' THEN 1 ELSE 0 END) AS assist
FROM
    incidents_incident INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id,
    json_array_elements(incidents_incident.incident_data->'field_52d47aac9bd13') as patrollers_incident
LEFT JOIN resorts_resort ON resorts_resort.resort_pk = %d
WHERE
    CAST (patrollers_incident AS text) <> '[]'
    AND CAST (patrollers_incident AS text) <> 'false'
    AND CAST (patrollers_incident AS text) <> ''
    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
GROUP BY 1;""" % (resort.resort_pk, request.user.user_connected,
                  resort.resort_pk, dateFrom, dateTo))

            data = dictfetchall(cursor)

            if data:
                data.pop(0)

        return Response({'success': True, 'data': data}, status=200)
예제 #8
0
    def resort_setting(self, request, pk=None):
        return_data = {}
        user = request.user

        try:
            resort = Resort.objects.get(resort_id=pk)
        except:
            return Response({_('detail'): _('no resort associated with user')},
                            status=400)

        if request.method == 'PUT':
            role = get_roleid_user(resort=resort, user=user)
            if role != 3:
                return Response(
                    {_('detail'): _('you do not have permission to resource')},
                    status=400)

        if request.method == 'GET':
            return_data = get_setting_data_for_resort(resort=resort)
        elif request.method == 'PUT':
            data = transform_resort_settings_request(request.data)
            resort_serialized_data = ResortSerializer(resort,
                                                      data=data,
                                                      partial=True)

            if resort_serialized_data.is_valid():
                resort = resort_serialized_data.save()
            else:
                return Response(resort_serialized_data.errors, status=400)

            return_data = get_setting_data_for_resort(resort=resort)
        if "map_kml" in return_data and return_data["map_kml"]:
            try:
                return_data["geojson"] = json.loads(
                    open(urllib.urlretrieve(return_data["map_kml"])[0]).read())
            except:
                pass
        return Response(return_data, status=200)
    def gender(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)

        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  extract(year from incidents_incident.dt_created) as year,
  extract(month from incidents_incident.dt_created) as month,
  SUM(CASE WHEN incidents_patients.sex  = 'male' then 1 else 0 end) as Male,
  SUM(CASE WHEN incidents_patients.sex = 'female' then 1 else 0 end) as Female,
  SUM(CASE WHEN incidents_patients.sex = '' then 1 else 0 end) as Unknown
FROM
  incidents_incident
LEFT JOIN incidents_patients ON incidents_incident.incident_pk = incidents_patients.incident_id
INNER JOIN custom_user_users ON assigned_to_id = custom_user_users.user_pk
WHERE
  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
GROUP BY 1,2
ORDER BY 1,2;""" % (resort.resort_pk, request.user.user_connected, dateFrom,
                    dateTo))

            data = dictfetchall(cursor)

        return Response({'success': True, 'data': data}, status=200)
예제 #10
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)
예제 #11
0
    def patrollers(self, request):
        order_by_fields = ['name', 'primary', 'secondary', 'assist', 'total']

        dateFrom, dateTo, resort, chunk, offset, orderBy, orderByDirection, outputFormat = get_param_with_pagination(
            request)
        user_role = get_roleid_user(resort, request.user)
        original_data_len = 0

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

        if orderBy not in order_by_fields:
            orderBy = order_by_fields[0]
        with connection.cursor() as cursor:
            cursor.execute("""SELECT
  json_array_elements(CAST (resorts_resort.incident_template AS JSON)->'DashboardItems'->'field_52d47aac9bd13'->
  'RepeatingQuestions'->'patroller'->'Values') ->> (patrollers_incident->>'patroller') as name,
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"170"' THEN 1 ELSE 0 END) AS "primary",
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"171"' THEN 1 ELSE 0 END) AS "secondary",
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"172"' THEN 1 ELSE 0 END) AS "assist",
  SUM(CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"170"' THEN 1 ELSE 0 END +
  CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"171"' THEN 1 ELSE 0 END +
  CASE WHEN CAST (patrollers_incident->'incident_role' AS text) = '"172"' THEN 1 ELSE 0 END) AS "total"
FROM
    incidents_incident INNER JOIN custom_user_users ON custom_user_users.user_pk = incidents_incident.assigned_to_id,
    json_array_elements(incidents_incident.incident_data->'field_52d47aac9bd13') as patrollers_incident
LEFT JOIN resorts_resort ON resorts_resort.resort_pk = %d
WHERE
    CAST (patrollers_incident AS text) <> '[]'
    AND CAST (patrollers_incident AS text) <> 'false'
    AND CAST (patrollers_incident AS text) <> ''
    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
GROUP BY 1
ORDER BY %s %s;""" % (resort.resort_pk, resort.resort_pk,
                      request.user.user_connected, dateFrom, dateTo,
                      "\"" + orderBy + "\"", orderByDirection))
            data = dictfetchall(cursor)
            print resort, request.user
            if data:
                # Delete the global group row.
                pop_index = 0 if orderByDirection == 'DESC' else (len(data) -
                                                                  1)
                data.pop(pop_index)
                original_data_len = len(data)
                # Pagination
                if offset is not 0:
                    data = data[offset:]
                if chunk is not None:
                    chunk = chunk if chunk <= len(data) else len(data)
                    data = data[:chunk]

        if outputFormat.upper() == 'CSV':

            def toCSV(content):
                csvfile = StringIO.StringIO()
                csvwriter = csv.writer(csvfile)
                csvwriter.writerow(
                    ["name", "primary", "secondary", "assist", "total"])
                yield csvfile.getvalue()
                for row in content:
                    csvfile = StringIO.StringIO()
                    csvwriter = csv.writer(csvfile)
                    csvwriter.writerow([
                        row["name"], row["primary"], row["secondary"],
                        row["assist"], row["total"]
                    ])
                    yield csvfile.getvalue()

            response = HttpResponse(toCSV(data), content_type='text/csv')
            response[
                'Content-Disposition'] = 'attachment; filename="patrollers_report.csv"'
            return response
        else:
            return Response(
                {
                    'success': True,
                    'data': data,
                    'total_rows': original_data_len
                },
                status=200)
예제 #12
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)
예제 #13
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)