예제 #1
0
    def get(self, request, *args, **kwargs):
        if not self.get_object() and is_external_user(self.request.user):
            # external user cannot create bushfire
            return TemplateResponse(request,
                                    'bfrs/error.html',
                                    context={
                                        'is_external_user': True,
                                        'status': 401
                                    },
                                    status=401)

        return super(BushfireUpdateView, self).get(request, *args, **kwargs)
예제 #2
0
 def get_template_names(self):
     obj = self.get_object()
     if is_external_user(self.request.user):
         return [self.template_summary]
     elif 'initial' in self.request.get_full_path(
     ) and obj.is_init_authorised:
         return [self.template_summary]
     elif 'final' in self.request.get_full_path(
     ) and obj.is_final_authorised and not can_maintain_data(
             self.request.user):
         return [self.template_summary]
     return super(BushfireUpdateView, self).get_template_names()
예제 #3
0
파일: api.py 프로젝트: rockychen-dpaw/bfrs
    def obj_update(self, bundle, **kwargs):
        try:
            # Allows BFRS and SSS to perform update only if permitted
            if is_external_user(bundle.request.user):
                raise ImmediateHttpResponse(response=HttpUnauthorized())

            if not can_maintain_data(
                    bundle.request.user
            ) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
                raise ImmediateHttpResponse(response=HttpUnauthorized())

            if bundle.request.GET.has_key(
                    'checkpermission'
            ) and bundle.request.GET['checkpermission'] == 'true':
                #this is a permission checking request,return directly.
                raise ImmediateHttpResponse(response=HttpAccepted())

            self.full_hydrate(bundle)
            #invalidate current bushfire if required.
            bundle.obj, invalidated = invalidate_bushfire(
                bundle.obj, bundle.request.user) or (bundle.obj, False)

            if not invalidated:
                bundle.obj.save()

            if bundle.data.has_key('area'):
                if (bundle.data.get('area') or {}).get('total_area') == None:
                    #no burning area,
                    bundle.obj.tenures_burnt.all().delete()
                else:
                    #print("Clear tenure burnt data")
                    if bundle.obj.report_status != Bushfire.STATUS_INITIAL and bundle.data[
                            'area'].get('layers'):
                        #report is not a initial report, and has area burnt data, save it.
                        #print("Populate new tenure burnt data")
                        update_areas_burnt(bundle.obj, bundle.data['area'])
                    else:
                        #report is a initial report,or has no area burnt data. clear the existing area burnt data
                        #area burnt data is unavailable for initial report
                        bundle.obj.tenures_burnt.all().delete()

            #save plantations
            if bundle.data.has_key("plantations"):
                #need to update plantations
                if bundle.data.get("plantations"):
                    #has plantation data
                    BushfireProperty.objects.update_or_create(
                        bushfire=bundle.obj,
                        name="plantations",
                        defaults={
                            "value": json.dumps(bundle.data.get("plantations"))
                        })
                else:
                    #no plantation data,remove the plantations data from table
                    BushfireProperty.objects.filter(
                        bushfire=bundle.obj, name="plantations").delete()

            if bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
                if bundle.obj.fire_boundary.contains(bundle.obj.origin_point):
                    # if bushfire has been authorised, update snapshot and archive old snapshot
                    serialize_bushfire('final', 'SSS Update', bundle.obj)
                else:
                    if bundle.obj.is_reviewed:
                        update_status(
                            bundle.request,
                            bundle.obj,
                            "delete_review",
                            action_desc=
                            "Delete review because origin point is outside of fire boundary after uploading from SSS",
                            action_name="Upload")

                    if bundle.obj.is_final_authorised:
                        update_status(
                            bundle.request,
                            bundle.obj,
                            "delete_final_authorisation",
                            action_desc=
                            "Delete final auth because origin point is outside of fire boundary after uploading from SSS",
                            action_name="Upload")

                #print("serizlie bushfire")

            if invalidated:
                raise ImmediateHttpResponse(response=JsonResponse(
                    {
                        "id": bundle.obj.id,
                        "fire_number": bundle.obj.fire_number
                    },
                    status=280))
            else:
                return bundle
        except:
            if bundle.request.GET.has_key(
                    'checkpermission'
            ) and bundle.request.GET['checkpermission'] == 'true':
                #for permission checking purpose, don't log the exception in log file.
                pass
            else:
                traceback.print_exc()
            raise
예제 #4
0
    def get_context_data(self, **kwargs):
        try:
            context = super(BushfireUpdateView,
                            self).get_context_data(**kwargs)
        except:
            context = {}

        bushfire = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        area_burnt_formset = None
        if self.request.POST.has_key('sss_create'):
            sss = json.loads(self.request.POST['sss_create'])
            if sss.has_key('area') and sss['area'].has_key(
                    'total_area') and sss['area']['total_area'] > 0:
                area_burnt_formset = create_areas_burnt(
                    None, sss['area']['layers'])

        if not area_burnt_formset:
            area_burnt_formset = AreaBurntFormSet(instance=bushfire,
                                                  prefix='area_burnt_fs')

        injury_formset = InjuryFormSet(instance=bushfire, prefix='injury_fs')
        damage_formset = DamageFormSet(instance=bushfire, prefix='damage_fs')

        # Determine if form template should be rean-only or editable (is_authorised=True --> read-only)
        if is_external_user(self.request.user) or self.request.POST.get(
                'authorise_final') or self.request.POST.has_key(
                    'submit_initial'):
            # Display both reports readonly
            is_authorised = True
            is_init_authorised = True
            static = True
        else:
            # which url was clicked - initial or final
            if bushfire:
                if 'final' in self.request.get_full_path():
                    # rpt s/b editable for FSSDRS even after final authorisation
                    is_authorised = bushfire.is_final_authorised and not can_maintain_data(
                        self.request.user)
                    is_init_authorised = True
                else:
                    is_authorised = True if bushfire.is_init_authorised else False
                    is_init_authorised = bushfire.is_init_authorised
            else:
                # create new bushfire
                is_authorised = False
                is_init_authorised = False

        if self.request.POST.has_key('sss_create'):
            # don't validate the form when initially displaying
            form.is_bound = False

        context.update({
            'form':
            form,
            'area_burnt_formset':
            area_burnt_formset,
            'injury_formset':
            injury_formset,
            'damage_formset':
            damage_formset,
            'is_authorised':
            is_authorised,  # If True, will make Report section of template read-only
            'is_init_authorised':
            is_init_authorised,  # If True, will make Notifications section of template read-only
            'snapshot':
            bushfire,
            'create':
            True if 'create' in self.request.get_full_path() else False,
            'initial':
            True if 'initial' in self.request.get_full_path() else False,
            'final':
            True if 'final' in self.request.get_full_path() else False,
            'static':
            True
            if self.template_summary in self.get_template_names() else False,
            'can_maintain_data':
            can_maintain_data(self.request.user),
            'is_external_user':
            is_external_user(self.request.user),
            'area_threshold':
            settings.AREA_THRESHOLD,
            'sss_data':
            json.loads(self.request.POST.get('sss_create'))
            if self.request.POST.has_key('sss_create') else
            None,  # needed since no object created yet
            'sss_url':
            settings.SSS_URL,
            'test': [{
                'damage_type': 'Other Property',
                'number': '1'
            }],
        })
        return context
예제 #5
0
    def form_valid(self,
                   request,
                   form,
                   area_burnt_formset=None,
                   injury_formset=None,
                   damage_formset=None):
        template_summary = 'bfrs/detail_summary.html'
        template_error = 'bfrs/error.html'

        if is_external_user(request.user):
            return TemplateResponse(request,
                                    template_error,
                                    context={
                                        'is_external_user': True,
                                        'status': 401
                                    },
                                    status=401)

        self.object = form.save(commit=False)
        if not hasattr(self.object, 'creator'):
            self.object.creator = request.user
        self.object.modifier = request.user

        # reset fields
        if self.object.cause and not self.object.cause.name.startswith(
                'Other'):
            self.object.other_cause = None
        if self.object.cause and not self.object.cause.name.startswith(
                'Escape P&W'):
            self.object.prescribed_burn_id = None
        if self.object.tenure and not self.object.tenure.name.startswith(
                'Other'):
            self.object.other_tenure = None
        if self.object.dispatch_pw:
            self.object.dispatch_pw = int(self.object.dispatch_pw)
        self.object.save()

        if not self.get_object():
            areas_burnt_updated = update_areas_burnt_fs(
                self.object, area_burnt_formset)
        injury_updated = update_injury_fs(self.object, injury_formset)
        damage_updated = update_damage_fs(self.object, damage_formset)

        # append/update 'Other' areas_burnt
        if self.request.POST.has_key(
                'private_area') and self.request.POST.has_key(
                    'other_crown_area'
                ):  # and self.object.final_fire_boundary:
            if self.request.POST.get('private_area'):
                private_tenure = self.request.POST.get('private_tenure')
                private_area = self.request.POST.get('private_area')
                self.object.tenures_burnt.update_or_create(
                    tenure=Tenure.objects.get(name=private_tenure),
                    defaults={"area": private_area})

            if self.request.POST.get('other_crown_area'):
                other_crown_tenure = self.request.POST.get(
                    'other_crown_tenure')
                other_crown_area = self.request.POST.get('other_crown_area')
                self.object.tenures_burnt.update_or_create(
                    tenure=Tenure.objects.get(name=other_crown_tenure),
                    defaults={"area": other_crown_area})
        elif self.object.area_limit:
            # if user selects there own final area, set the area to the tenure of ignition point (Tenure, Other Crown, (Other) Private Property)
            self.object.tenures_burnt.all().delete()
            if self.object.other_tenure == Bushfire.IGNITION_POINT_PRIVATE:
                self.object.tenures_burnt.update_or_create(
                    tenure=Tenure.objects.get(name='Private Property'),
                    defaults={"area": self.object.area})
            elif self.object.other_tenure == Bushfire.IGNITION_POINT_CROWN:
                self.object.tenures_burnt.update_or_create(
                    tenure=Tenure.objects.get(name='Other Crown'),
                    defaults={"area": self.object.area})
            elif not self.object.other_tenure:
                self.object.tenures_burnt.update_or_create(
                    tenure=self.object.tenure,
                    defaults={"area": self.object.area})

        refresh_gokart(self.request,
                       fire_number=self.object.fire_number,
                       region=self.object.region.id,
                       district=self.object.district.id)

        # This section to Submit/Authorise report, placed here to allow any changes to be cleaned and saved first - effectively the 'Submit' btn is a 'save and submit'
        if self.request.POST.has_key('submit_initial') or self.request.POST.has_key('authorise_final') or \
           (self.request.POST.has_key('_save') and self.request.POST.get('_save') and self.object.is_final_authorised):
            response = authorise_report(self.request, self.object)
            if response:
                return response

        if self.object.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
            # if bushfire has been authorised, update snapshot and archive old snapshot
            # That is, if FSSDRS group update the final report after it has been authorised, we archive the existing data
            try:
                serialize_bushfire('final', action, self.object)
            except NameError:
                # update is occuring after report has already been authorised (action is undefined) - ie. it is being Reviewed by FSSDRS
                serialize_bushfire('final', 'Review', self.object)

        self.object.save()

        if self.request.POST.has_key('_save_and_submit'):
            response = authorise_report(self.request, self.object)
            if response:
                return response

        return HttpResponseRedirect(self.get_success_url())
예제 #6
0
    def get_context_data(self, **kwargs):
        context = super(BushfireView, self).get_context_data(**kwargs)

        initial = {
        }  # initial parameter prevents the form from resetting, if the region and district filters had a value set previously
        profile = self.get_initial(
        )  # Additional profile Filters must also be added to the JS in bushfire.html- profile_field_list
        if self.request.GET.has_key('region'):
            initial.update({'region': self.request.GET['region']})
        elif profile['region']:
            initial.update({'region': profile['region'].id})
            self.object_list = self.object_list.filter(
                region=profile['region'])

        if self.request.GET.has_key('district'):
            initial.update({'district': self.request.GET['district']})
        elif profile['district']:
            initial.update({'district': profile['district'].id})
            self.object_list = self.object_list.filter(
                district=profile['district'])

        if not self.request.GET.has_key('include_archived'):
            self.object_list = self.object_list.exclude(archive=True)
        else:
            initial.update(
                {'include_archived': self.request.GET.get('include_archived')})

        if self.request.GET.has_key('exclude_missing_final_fire_boundary'):
            self.object_list = self.object_list.filter(
                final_fire_boundary=True)
        initial.update({
            'exclude_missing_final_fire_boundary':
            self.request.GET.get('exclude_missing_final_fire_boundary')
        })

        bushfire_list = self.object_list.order_by('-modified')
        paginator = Paginator(bushfire_list, self.paginate_by)
        page = self.request.GET.get('page')
        try:
            object_list_paginated = paginator.page(page)
        except PageNotAnInteger:
            object_list_paginated = paginator.page(1)
        except EmptyPage:
            object_list_paginated = paginator.page(paginator.num_pages)

        # update context with form - filter is already in the context
        context['form'] = BushfireFilterForm(initial=initial)
        context['object_list'] = object_list_paginated
        context['sss_url'] = settings.SSS_URL
        context['can_maintain_data'] = can_maintain_data(self.request.user)
        context['is_external_user'] = is_external_user(self.request.user)
        if paginator.num_pages == 1:
            context['is_paginated'] = False

        referrer = self.request.META.get('HTTP_REFERER')
        if referrer and not ('initial' in referrer or 'final' in referrer
                             or 'create' in referrer):
            refresh_gokart(
                self.request
            )  #, fire_number="") #, region=None, district=None, action='update')
        return context
예제 #7
0
파일: api.py 프로젝트: IndrayaniJadhav/bfrs
    def obj_update(self, bundle, **kwargs):

        if bundle.request.GET.has_key('checkpermission') and bundle.request.GET['checkpermission'] == 'true':
            # Allows SSS to perform permission check
            if is_external_user(bundle.request.user) or \
               (not can_maintain_data(bundle.request.user) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED):
                raise ImmediateHttpResponse(response=HttpUnauthorized())
            else:
                raise ImmediateHttpResponse(response=HttpAccepted())

        # Allows BFRS and SSS to perform update only if permitted
        if is_external_user(bundle.request.user):
            return bundle

        if not can_maintain_data(bundle.request.user) and bundle.obj.report_status >= Bushfire.STATUS_FINAL_AUTHORISED:
            raise ImmediateHttpResponse(response=HttpUnauthorized())

        self.full_hydrate(bundle)
        #bundle.obj.sss_data = json.dumps(bundle.data)
        sss_data = bundle.data
        #import ipdb; ipdb.set_trace()
        if sss_data.has_key('fire_boundary'):
            sss_data.pop('fire_boundary')
        #if sss_data.has_key('area') and sss_data.get('area').has_key('tenure_area'):
        #    sss_data.get('area').pop('tenure_area') # necessary for the initial create stagei for display in form, since object not yet saved
        bundle.obj.sss_data = json.dumps(sss_data)

        if bundle.data.has_key('tenure_ignition_point') and bundle.data['tenure_ignition_point'] and \
            bundle.data['tenure_ignition_point'].has_key('category') and bundle.data['tenure_ignition_point']['category']:
            try:
                bundle.obj.tenure = Tenure.objects.get(name__istartswith=bundle.data['tenure_ignition_point']['category'])
            except:
                bundle.obj.tenure = Tenure.objects.get(name__iendswith='other')
        elif bundle.data.has_key('tenure_ignition_point') and not bundle.data['tenure_ignition_point']:
            bundle.obj.tenure = Tenure.objects.get(name__iendswith='other')

        if bundle.data.has_key('area') and bundle.data['area'].has_key('layers') and bundle.data['area']['layers']:
            update_areas_burnt(bundle.obj, bundle.data['area']['layers'])


        if bundle.data.has_key('area') and bundle.data['area'].has_key('total_area') and bundle.data['area']['total_area']:
            if bundle.obj.report_status < Bushfire.STATUS_INITIAL_AUTHORISED:
                bundle.obj.area_unknown = False
                initial_area = round(float(bundle.data['area']['total_area']), 2)
                bundle.obj.initial_area = initial_area if initial_area > 0 else 0.01
            else:
                bundle.obj.area_limit = False
                area = round(float(bundle.data['area']['total_area']), 2)
                bundle.obj.area = area if area > 0 else 0.01

        if bundle.data.has_key('area') and bundle.data['area'].has_key('other_area') and bundle.data['area']['other_area']:
            other_area = round(float(bundle.data['area']['other_area']), 2)
            bundle.obj.other_area = other_area if other_area > 0 else 0.01

        if bundle.data.has_key('fire_position') and bundle.data['fire_position']:
            # only update if user has not over-ridden
            if not bundle.obj.fire_position_override:
                bundle.obj.fire_position = bundle.data['fire_position']

        if bundle.data.has_key('region_id') and bundle.data.has_key('district_id') and bundle.data['region_id'] and bundle.data['district_id']:
            if bundle.data['district_id'] != bundle.obj.district.id and bundle.obj.report_status == Bushfire.STATUS_INITIAL:
                district = District.objects.get(id=bundle.data['district_id'])
                invalidate_bushfire(bundle.obj, district, bundle.request.user)

        if bundle.obj.report_status >=  Bushfire.STATUS_FINAL_AUTHORISED:
            # if bushfire has been authorised, update snapshot and archive old snapshot
            serialize_bushfire('final', 'SSS Update', bundle.obj)

        bundle.obj.save()
        return bundle