def HandleRelease(self, json_request, org): """Releases a site for an organization, if it was claimed by the organization.""" site = self.GetSite(json_request['id']) if not site: return claimed_by = None try: claimed_by = site.claimed_by except db.ReferencePropertyResolveError: # Treat the site as if it has no organization. logging.warning('failed to find organization for site %s' % json_request['id']) pass if claimed_by and claimed_by.key().id() == org.key().id(): site.claimed_by = None site_db.PutAndCache(site) return if claimed_by: self.HandleBadRequest('This site is claimed by ' + claimed_by.name + '.', status=FORBIDDEN) else: self.HandleBadRequest('This site is currently unclaimed.', status=FORBIDDEN)
def HandleClaim(self, json_request, org): """Claims a site for an organization, if it's not already taken.""" site = self.GetSite(json_request['id']) if not site: return claimed_by = None try: claimed_by = site.claimed_by except db.ReferencePropertyResolveError: # Treat the site as if it has no organization. logging.warning('failed to find organization for site %s' % json_request['id']) pass if not claimed_by: site.claimed_by = org site_db.PutAndCache(site) return if site.claimed_by.key().id() == org.key().id(): self.response.out.write( 'This site was already claimed by your organization.') else: self.HandleBadRequest( 'Sorry, this site has already been claimed by %s' % site.claimed_by.name, status=FORBIDDEN)
def HandleUpdate(self, json_request, org): if not self.CheckRequiredKeys(json_request, ['update']): return VALIDATORS = { 'status': lambda field, status: status in site_db.Site.status.choices, } unsupported_fields = [ f for f in json_request['update'] if f not in VALIDATORS ] if unsupported_fields: self.HandleBadRequest('cannot update these fields: %s' % ', '.join(unsupported_fields)) return invalid_fields = [] for field, value in json_request['update'].iteritems(): validator = VALIDATORS[field] if not validator(field, value): invalid_fields.append(field) if invalid_fields: self.HandleBadRequest('invalid values for these fields: %s' % ', '.join(invalid_fields)) return site = self.GetSite(json_request['id']) if not site: return for field, value in json_request['update'].iteritems(): setattr(site, field, value) if "status" in json_request['update']: if not site.claimed_by: setattr(site, "claimed_by", org) setattr(site, "claim_for_org", "y") site_db.PutAndCache(site) logging.debug('updated site')
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" }))
def AuthenticatedGet(self, org, event): f = open('sheet1.csv') fileReader = csv.reader(f) firstRow = None all_sites = [] for row in fileReader: if not firstRow: firstRow = row else: m = [(firstRow[i], row[i]) for i in range(len(row))] all_sites.append(dict(m)) for s in all_sites: if s["Contact Name"] == "": s["Contact Name"] = "Unknown" self.response.write(s["Contact Name"] + "<br />") lookup = site_db.Site.gql( "WHERE name = :name and address = :address and zip_code = :zip_code LIMIT 1", name=s["Contact Name"], address=s["Street Address"], zip_code=s["Zip Code"]) site = None for l in lookup: site = l def IfSet(c): if s[c] != "": return " " + c + ": " + s[c] return "" if not site: # Save the data, and redirect to the view page logging.critical(s["Contact Name"]) site = site_db.Site( status="Open, unassigned", address=str(s["Street Address"]), name=s["Contact Name"], phone1=str(s["Phone Number"]), county=s["County"], city=s["City"], state=s["State"], latitude=float(s["Latitude"]), longitude=float(s["Longitude"]), zip_code=str(s["Zip Code"]), notes=IfSet("Other Needs") + IfSet("Tools or Skills Needed") + IfSet("Other Information") + IfSet("Crew Size Needed") + IfSet("Estimated Length of Job") + IfSet("Damaged Appliance/Furniture/Flooring?") + IfSet("Functioning Utilities") + IfSet("Primary Home?") + IfSet("Age of Other Residents") + IfSet("Structural Damage to Home?") + IfSet("Mold Growing?") + IfSet("Contacted Insurance?") + IfSet("Water Level in Home") + IfSet("Contacted Landlord?") + IfSet("Part of House Flooded") + IfSet("Text") + IfSet("Waiting for Insurance Company?") + IfSet("Email") + IfSet("Source Name"), other_hazards=IfSet("Hazards to Look Out For") + IfSet("Hazardous Materials on Property?"), electrical_lines="yes" in s["Power Lines Down on Property?"].lower(), prepared_by=s["Person Reporting"], disabled="yes" in s["Disabled?"].lower(), older_than_60="yes" in s["Elderly?"].lower(), work_requested=s["Description"] + " Damage: " + s["Damage Incurred"], standing_water="yes" in s["Currently Water in Home?"].lower(), electricity="no" in s["Gas/Electricity Turned Off?"].lower(), insurance=s["Have Insurance?"]) try: if len(s["Priority"]) > 0: site.priority = int(s["Priority"][0]) except ValueError: pass if 'yes' in s["Homeowner?"].lower(): site.rent_or_own = "Own" site.claimed_by = org event_db.AddSiteToEvent(site, event.key().id()) #logging.critical('No lat/lng: ' + site.name + " " + s["Lat, Long"]) site_db.PutAndCache(site)