def update_summary(query, date, cost, amount, bldg, unit, provider, utility_type, uom): #'electricity' dt = datetime(*(strptime(date, "%Y-%m-%d")[0:6])) #date = dt ## print dt ## print timezone.get_current_timezone() ## print timezone.get_default_timezone() ## print dir(timezone) #date = timezone.make_aware(dt, timezone.get_current_timezone()) #date = timezone.make_aware(dt, timezone.get_default_timezone()) date = timezone.make_aware(dt, timezone.utc) ## print date ## print matches = query.filter(start_date=date) if len(matches): updated = False summary = matches[0] #print "found something", summary.cost, cost, date if summary.cost != float(cost): print "Different costs:", float(cost) summary.cost = float(cost) updated = True if summary.amount != float(amount): summary.amount = float(amount) updated = True if updated: print "FOUND EXISTING! (and changes!)" summary.save() else: print date, cost, amount print "MAKING NEW!" summary = UtilitySummary() summary.building = bldg summary.unit = unit summary.type = utility_type summary.provider = provider summary.start_date = date summary.cost = float(cost) summary.amount = float(amount) summary.unit_of_measurement = uom summary.save()
def edit(request, city_tag=None, bldg_tag=None, unit_tag=None): (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag) results = '' #UtilityFormSet = formset_factory(UtilityOneRowForm, extra=12) UtilityFormSet = formset_factory(UtilityOneRowForm, extra=0) (provider_names, utility_providers) = make_provider_names(city) if request.method == 'POST': meta = MetaUtilityForm(request.POST, prefix='meta') #http://stackoverflow.com/questions/657607/setting-the-selected-value-on-a-django-forms-choicefield meta.fields['utility_provider'].choices = provider_names utility_set = UtilityFormSet(request.POST, prefix='months') if meta.is_valid() and utility_set.is_valid(): # All validation rules pass errors = False (provider, company_name) = parse_form_providers(meta) #keep query around for all rows main_query = None unit_updated = False #go through each item in utility_set for form in utility_set: #see if there is data if form.cleaned_data['cost'] or form.cleaned_data['amount']: #if we haven't done the initial lookup yet, do it now if not main_query: main_query = UtilitySummary.objects.filter(building=building, unit=unit, type=meta.cleaned_data['utility_type']) #look up the corresponding UtilitySummary model object subset = main_query.filter(start_date=form.cleaned_data['start_date']) updated = False #if len(subset): if subset.count(): #already have something in the database... #look at that and update accordingly #print "Updating existing entry:" #following equivalent? summary = subset[0] #summary = subset.first() #if different, apply and save changes if summary.cost != form.cleaned_data['cost']: summary.cost = form.cleaned_data['cost'] updated = True if summary.amount != form.cleaned_data['amount']: summary.amount = form.cleaned_data['amount'] updated = True if provider: if summary.provider != provider: summary.provider = provider updated = True else: if summary.vendor != company_name: summary.vendor = company_name updated = True else: summary = UtilitySummary() summary.building = building summary.unit = unit summary.type = meta.cleaned_data['utility_type'] #should set one of these if provider: summary.provider = provider else: summary.vendor = company_name summary.start_date = form.cleaned_data['start_date'] summary.cost = form.cleaned_data['cost'] summary.amount = form.cleaned_data['amount'] #summary.save() #print "Saving new!!" updated = True if updated: #TODO: #consider logging any changes to prevent data loss summary.save() #print "Changes saved" unit_updated = True if unit_updated: #this takes care of updating corresponding averages and scores unit.save_and_update(request) #TODO: #would be better to redirect back to the building detail page #and show a thank you message #that message should include options to share, tweet, etc #in chrome, the original post url stays in the address bar... #finished_url = reverse('utility.views.thank_you') finished_url = thankyou_url(unit) return redirect(finished_url) else: #form = ShareForm() now = timezone.now() months = previous_months() months.reverse() #for i in range(1,13): # print i initial = [] for month in months: initial.append( {'start_date': month} ) utility_set = UtilityFormSet(initial=initial, prefix='months') meta = MetaUtilityForm(initial={'start_date':months[-1], 'end_date':months[0]}, prefix='meta') meta.fields['utility_provider'].choices = provider_names #meta.start_date = months[-1] #meta.end_date = months[0] #view_url = reverse('utility.views.upload_handler') view_url = request.path #print unit context = { 'city': city.name, #'state': state, 'bldg': building, 'unit': unit, #forms: 'meta': meta, 'utility': utility_set, 'providers': json.dumps(utility_providers), 'results': results, #'upload_url': upload_url, } return render(request, 'utility_generic.html', context)
def save_json(request, city_tag=None, bldg_tag=None, unit_tag=None): """ very similar functionality to edit() POST processing... TODO: is it possible to combine/abstract any functionality with edit()? """ (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag) if request.is_ajax(): if request.method == 'POST': data = json.loads(request.body) #print data #print building.id, unit.id if data['utility']: other_company = None provider = None if data['company_name'] != "Other": provider_options = ServiceProvider.objects.filter(name=data['company_name']) if len(provider_options): provider = provider_options[0] else: print "error finding utility_provider: %s matches" % len(provider_options) else: other_company = data['other_company'] unit_updated = False for key, value in data['values'].items(): query = UtilitySummary.objects.filter(building=building, unit=unit, type=data['utility'], start_date=key) summary = None updated = False if len(query): summary = query[0] if summary.cost != value['cost']: summary.cost = value['cost'] updated = True if summary.amount != value['amount']: summary.amount = value['amount'] updated = True if provider: if summary.provider != provider: summary.provider = provider updated = True else: if summary.vendor != other_company: summary.vendor = other_company updated = True else: summary = UtilitySummary() summary.building = building summary.unit = unit summary.type = data['utility'] #should set one of these if provider: summary.provider = provider else: summary.vendor = other_company summary.start_date = key summary.cost = value['cost'] summary.amount = value['amount'] updated = True #summary.save() #print "Saving new!!" if updated: #TODO: #consider logging any changes to prevent data loss summary.save() print "Changes saved" unit_updated = True if unit_updated: unit.save_and_update(request) ## #only need to update this unit ## unit.update_averages() ## unit.update_energy_score() ## print "updated unit averages" ## #then update the whole building: ## building.update_utility_averages() ## print "updated building averages" return HttpResponse("OK")