def AuthenticatedGet(self, org, event):
        csv_id = self.request.get('id', None)

        # get csv rows & unpickle fields
        csv_file_obj = CSVFile.get_by_id(int(csv_id))
        csv_rows = db.GqlQuery(
            "SELECT * from CSVRow WHERE csv_file=:1 ORDER BY num ASC",
            csv_file_obj.key())
        annotated_rows = [{
            'num':
            cro.num,
            'row':
            cro.row,
            'row_dict':
            pickle.loads(cro.row_dict),
            'validation':
            pickle.loads(cro.validation),
            'geocoded_address':
            pickle.loads(cro.geocoded_address),
        } for cro in csv_rows]

        # write out page
        field_names = get_field_names(event)
        self.response.out.write(
            check_template.render({
                ##'global_admin': global_admin,
                'event':
                event,
                'form':
                site_db.StandardSiteForm(),
                'csv_file_obj':
                csv_file_obj,
                'csv_id':
                csv_id,
                'field_names':
                field_names,
                'annotated_rows':
                annotated_rows,
                'valid_row_count':
                csv_file_obj.valid_row_count,
                'invalid_row_count':
                csv_file_obj.invalid_row_count,
            }))
Ejemplo n.º 2
0
    def AuthenticatedPost(self, org, event):
        if org.permissions == "Situational Awareness":
            self.redirect("/sit_aware_redirect")
            return
        my_string = ""
        for k, v in self.request.POST.iteritems():
            if v == "":
                v = "stub"
            my_string += k + " = '" + v + "', "

        data = site_db.StandardSiteForm(self.request.POST)
        post_dict = dict(self.request.POST)
        post_json = json.dumps(post_dict)

        #single_site_template = jinja_environment.get_template('single_site.html')

        #if event.short_name in [HATTIESBURG_SHORT_NAME, GEORGIA_SHORT_NAME]:
        #single_site_template = jinja_environment.get_template('single_site_derechos.html')

        claim_for_org = self.request.get("claim_for_org") == "y"
        #data = None
        #if event.short_name in [HATTIESBURG_SHORT_NAME, GEORGIA_SHORT_NAME]:
        #data = site_db.DerechosSiteForm(self.request.POST)
        #else:
        #data = site_db.SiteForm(self.request.POST)

        # un-escaping data caused by base.py = self.request.POST[i] = cgi.escape(self.request.POST[i])
        data.name.data = site_util.unescape(data.name.data)
        data.priority.data = int(data.priority.data)

        data.name.validators = data.name.validators + [
            wtforms.validators.Length(
                min=1,
                max=100,
                message="Name must be between 1 and 100 characters")
        ]
        data.phone1.validators = data.phone1.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a primary phone number")
        ]
        data.city.validators = data.city.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a city name")
        ]
        data.state.validators = data.state.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a state name")
        ]
        data.work_type.validators = data.work_type.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please set a primary work type")
        ]
        if data.validate():
            lookup = site_db.Site.gql(
                "WHERE name = :name and address = :address LIMIT 1",
                name=data.name.data,
                address=data.address.data)
            site = None
            for l in lookup:
                # See if this same site is for a different event.
                # If so, we'll make a new one.
                if l.event and l.event.name == event.name:
                    site = l
                    break

            if not site:
                # Save the data, and redirect to the view page
                site = site_db.Site(address=data.address.data,
                                    name=data.name.data,
                                    priority=int(data.priority.data))
            for k, v in self.request.POST.iteritems():
                if k not in site_db.STANDARD_SITE_PROPERTIES_LIST:
                    if k == "request_date":
                        date_saved = False
                        try:
                            date_object = datetime.strptime(
                                v, '%Y-%m-%d %H:%M:%S')
                            setattr(site, k, date_object)
                            date_saved = True
                        except:
                            date_saved = False
                            pass
                        if date_saved is False:
                            try:
                                v = v.replace("/", "-")
                                date_object = datetime.strptime(v, '%Y-%m-%d')
                                setattr(site, k, date_object)
                                date_saved = True
                            except:
                                date_saved = False
                                pass
                        if date_saved is False:
                            try:
                                v = v.replace("/", "-")
                                date_object = datetime.strptime(v, '%m-%d-%Y')
                                setattr(site, k, date_object)
                                date_saved = True
                            except:
                                date_saved = False
                                pass

                    else:
                        setattr(site, k, v)
            try:
                data.populate_obj(site)
            except:
                raise Exception("populate")
            site.reported_by = org
            if claim_for_org:
                site.claimed_by = org

            # clear assigned_to if status is unassigned
            if data.status.data == 'Open, unassigned':
                site.assigned_to = ''
            # attempt to save site

            similar_site = None
            if site.similar(event) and not self.request.get(
                    'ignore_similar', None):
                similar_site = site.similar(event)
                message = None
            elif site.event or event_db.AddSiteToEvent(site, event.key().id()):
                site_db.PutAndCache(site)
                try:
                    audit_db.create(site, "create", org)
                except:
                    logging.error("Audit exception")

#dict_dict_site = site_db.SiteToDict(site)
#raise Exception(dict_dict_site)
                self.redirect("/?message=" + "Successfully added " +
                              urllib2.quote(site.name))
                return
            else:
                message = "Failed to add site to event: " + event.name
        else:
            message = "Failed to validate"
            similar_site = None
        q = db.Query(form_db.IncidentForm)
        q.filter("incident =", event.key())
        query = q.get()

        # set it as form_stub
        # send to single site

        inc_form = None
        if query:
            inc_form = query.form_html

        single_site = single_site_template.render({
            "form":
            data,
            "org":
            org,
            "incident_form_block":
            inc_form,
        })
        self.response.out.write(
            template.render({
                "message":
                message,
                "similar_site":
                similar_site,
                "version":
                os.environ['CURRENT_VERSION_ID'],
                "errors":
                data.errors,
                "menubox":
                menubox_template.render({
                    "org": org,
                    "event": event
                }),
                "single_site":
                single_site,
                "form":
                data,
                "id":
                None,
                "page":
                "/",
                "post_json":
                post_json,
                "event_name":
                event.name
            }))
    def AuthenticatedPost(self, org, event):
        if org.permissions == "Situational Awareness":
            self.redirect("/sit_aware_redirect")
            return
        #if event.short_name in [HATTIESBURG_SHORT_NAME, GEORGIA_SHORT_NAME]:
        #single_site_template = jinja_environment.get_template('single_site_derechos.html')
        try:
            id = int(self.request.get('_id'))
        except:
            return
        site = site_db.Site.get_by_id(id)
        try:
            audit_db.create(site, "edit", org)
        except:
            logging.error("Audit exception")
        old_status = site.status
        data = site_db.StandardSiteForm(self.request.POST, site)
        new_status = data.status.data
        if old_status != new_status:
            if not site.claimed_by:
                site.claimed_by = org
                site.claim_for_org = "y"
        # raise Exception(old_status, new_status.data)
        #if event.short_name in [HATTIESBURG_SHORT_NAME, GEORGIA_SHORT_NAME]:
        #form = site_db.DerechosSiteForm(self.request.POST, site)

        # un-escaping data caused by base.py = self.request.POST[i] = cgi.escape(self.request.POST[i])
        data.name.data = site_util.unescape(data.name.data)

        data.priority.data = int(data.priority.data)
        data.name.validators = data.name.validators + [
            wtforms.validators.Length(
                min=1,
                max=100,
                message="Name must be between 1 and 100 characters")
        ]
        data.phone1.validators = data.phone1.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a primary phone number")
        ]
        data.city.validators = data.city.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a city name")
        ]
        data.state.validators = data.state.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please enter a state name")
        ]
        data.work_type.validators = data.work_type.validators + [
            wtforms.validators.Length(
                min=1, max=100, message="Please set a primary work type")
        ]

        case_number = site.case_number
        claim_for_org = self.request.get("claim_for_org") == "y"

        mode_js = self.request.get("mode") == "js"
        if data.validate():
            #setattr(site, "longitude", lng_float)
            #setattr(site, "latitude", lat_float)
            # Save the data, and redirect to the view page
            for f in data:
                # In order to avoid overriding fields that didn't appear
                # in this form, we have to only set those that were explicitly
                # set in the post request.
                in_post = self.request.get(f.name, default_value=None)
                if in_post is None:
                    continue
                setattr(site, f.name, f.data)
            if claim_for_org == "y":
                site.claimed_by = org
            # clear assigned_to if status is unassigned
            if data.status.data == 'Open, unassigned':
                site.assigned_to = ''

            for k, v in self.request.POST.iteritems():
                if k not in site_db.STANDARD_SITE_PROPERTIES_LIST:

                    if k == "request_date":
                        try:
                            date_object = datetime.strptime(
                                v, '%Y-%m-%d %H:%M:%S')
                            setattr(site, k, date_object)
                        except:
                            date_object = datetime.strptime(
                                v, '%Y-%m-%d %H:%M:%S.%f')
                            setattr(site, k, date_object)
                    else:
                        setattr(site, k, v)
            site_db.PutAndCache(site)

            if mode_js:
                # returning a 200 is sufficient here.
                return
            else:
                self.redirect('/map?id=%d' % id)
        else:
            q = db.Query(form_db.IncidentForm)
            q.filter("incident =", event.key())
            query = q.get()

            # set it as form_stub
            # send to single site

            inc_form = None
            form = None
            if query:
                inc_form = query.form_html

            post_json2 = site_db.SiteToDict(site)
            date_string = str(post_json2['request_date'])
            post_json2['request_date'] = date_string
            post_json2['event'] = site.event.name
            #post_json = {
            #"city": str(site.city),
            #"name": str(site.name),
            #"reported_by": str(site.reported_by.name),
            #}
            post_json = json.dumps(post_json2)

            single_site = single_site_template.render({
                "form":
                data,
                "org":
                org,
                "incident_form_block":
                inc_form,
            })
            if mode_js:
                self.response.set_status(400)
            self.response.out.write(
                template.render({
                    "mode_js":
                    mode_js,
                    "menubox":
                    menubox_template.render({
                        "org": org,
                        "event": event
                    }),
                    "errors":
                    data.errors,
                    "form":
                    data,
                    "single_site":
                    single_site,
                    "id":
                    id,
                    "post_json":
                    post_json,
                    "page":
                    "/edit"
                }))