Exemplo n.º 1
0
def details(request, city_tag, bldg_tag, unit_tag=''):
    (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag='')

    #print unit.full_address()
    context = { 'building': building,
                'units': [unit],
                'unit': unit,
                'user': request.user,
                #'redirect_field': REDIRECT_FIELD_NAME,
                }
    return render(request, 'unit_details.html', context)
Exemplo n.º 2
0
def handle_json(request, city_tag=None, bldg_tag=None, unit_tag=None):
    (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag)

    matches = {}
    if request.is_ajax():
        if request.method == 'POST':
            ## print 'Raw Data: "%s"' % request.body
            ## print dir(request.POST)
            ## print request.POST.get('data')
            data = json.loads(request.body)
            #print data
            #print building.id, unit.id
            if data['utility']:
                end = datetime.strptime(data['end'], '%Y-%m-%d')
                end = timezone.make_aware(end, timezone.UTC())
                start = datetime.strptime(data['start'], '%Y-%m-%d')
                start = timezone.make_aware(start, timezone.UTC())
                #print type(start)
                #print start
                
                #can do lookup once we have the utility type
                #everything else is needed for storing
                main_query = UtilitySummary.objects.filter(building=building, unit=unit, type=data['utility'], start_date__lte=end, start_date__gte=start)
                #main_query = UtilitySummary.objects.filter(building=building, unit=unit, type=data['utility'])
                
                #print "Matches: %s" % len(main_query)
                for option in main_query.all():
                    #print dir(option.start_date)
                    #print type(option.start_date)
                    #print option.start_date
                    #print option.start_date.strftime('%Y-%m-01')
                    date_key = option.start_date.strftime('%Y-%m-01')
                    #date_key = option.start_date.strftime('%m/01/%Y')
                    matches[date_key] = {  }
                    if option.amount:
                        matches[date_key]['amount'] = option.amount
                    else:
                        matches[date_key]['amount'] = ''

                    if option.cost:
                        matches[date_key]['cost'] = option.cost
                    else:
                        matches[date_key]['cost'] = ''

                    #print option
                #filter by dates
                
                #convert all results to json response

    #http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python
    result = json.dumps(matches)
    #print result
    return HttpResponse(result, content_type="application/json")
Exemplo n.º 3
0
def new(request, city_tag, bldg_tag, unit_tag=None):
    (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag=unit_tag)

    #TODO:
    #find any active listing for current unit

    if request.method == 'POST':
        listingform = ListingForm(request.POST, instance=building,
                                    prefix='listing')

        if listingform.is_valid(): # All validation rules pass
            #https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
            #by passing commit=False, we get a copy of the model before it
            #has been saved. This allows diff to work below
            updated = listingform.save(commit=False)

            updated.set_booleans()
            #print json.dumps(updated.diff)
            
            #print updated.diff
            changes = ChangeDetails()
            changes.ip_address = get_client_ip(request)
            changes.user = request.user
            changes.diffs = json.dumps(updated.diff)
            changes.building = updated
            #not required
            #changes.unit =
            changes.save()
            
            #now it's ok to save the building details:
            updated.save()

            unit_ok = False
            if building.units.count() == 1:
                unitform = UnitForm(request.POST, instance=unit, prefix='unit')
                if unitform.is_valid(): # All validation rules pass
                    updated_unit = unitform.save(commit=False)
                    updated_unit.save_and_update(request)
                    unit_ok = True
            else:
                unit_ok = True

            if unit_ok:
                #redirect to listing details with an edit message
                messages.add_message(request, messages.INFO, 'Saved changes to listing.')
                finished_url = reverse('listing.views.details', args=(updated.tag, updated.city.tag))
                
                return redirect(finished_url)

    else:
        #listingform = ListingForm(instance=listing, prefix='listing')
        listingform = ListingForm(prefix='listing')
        #listingform.fields['name'].label = "Building Name"
        #if building.units.count() == 1:
        #    unitform = UnitForm(instance=unit, prefix='unit')

    context = { 'building': building,
                'user': request.user,
                'listingform': listingform,
                }
    return render(request, 'listing-edit.html', context)
Exemplo n.º 4
0
def upload_simple(request, city_tag=None, bldg_tag=None, unit_tag=None):
    (city, building, unit) = find_by_tags(city_tag, bldg_tag, unit_tag)

    (provider_names, utility_providers) = make_provider_names(city)
    
    if request.method == 'POST':
        #print "form posted"
        form = UploadShortForm(request.POST, request.FILES)
        form.fields['utility_provider'].choices = provider_names

        #print form.fields['file'].data
        #print form.fields['file'].cleaned_data
        #print form.fields['file'].cleaned_data

        #if meta.is_valid() and form.is_valid(): 
        if form.is_valid(): 

            errors = False

            if request.FILES.has_key("file"):
                #blob_key = request.FILES["blobkey"].blobstore_info._BlobInfo__key
                blob_key = request.FILES['file'].blobstore_info.key()

                #print "BLOBKEY: ", blob_key
                #obj.blobstore_key = blob_key
                statement = Statement()
                statement.blob_key = blob_key

                statement.original_filename = request.FILES['file'].name
                
                statement.unit = unit

                statement.ip_address = get_client_ip(request)

                #print request.user
                #print dir(request.user)
                if request.user and not request.user.is_anonymous():
                    statement.user = request.user
                
                (provider, company_name) = parse_form_providers(form)
                #if form.cleaned_data.has_key('vendor'):
                #statement.vendor = form.cleaned_data['vendor']

                #should set one of these
                if provider:
                    statement.provider = provider
                else:
                    statement.vendor = company_name

                #if form.cleaned_data.has_key('utility_type'):
                #if meta.cleaned_data['utility_type'] == 'other':
                #if form.cleaned_data['utility_type'] == 'other':
                    #if form.cleaned_data.has_key('alt_type'):
                    #statement.type = form.cleaned_data['alt_type']
                #else:
                statement.type = form.cleaned_data['utility_type']
                                
                statement.save()
                #print statement
                #form.save()
                #return HttpResponseRedirect(view_url)
                #return redirect(view_url, permanent=True)
                #in chrome, the original post url stays in the address bar...
                finished_url = reverse('utility.views.thank_you')
                return redirect(finished_url)

            else:
                print "NO BLOBKEY!!!", str(request)
                print dir(request)
                print request.FILES
                if request.FILES.has_key('file'):
                    print request.FILES['file']
                    print dir(request.FILES['file'])
                    print request.FILES['file'].blobstore_info.key()
                print 

        else:
            #print dir(form)
            #print form.errors
            #print "form did not validate"
            pass

    else:
        #form = UploadShortForm()
        #meta = MetaUtilityForm(prefix='meta')

        form = UploadShortForm()
        form.fields['utility_provider'].choices = provider_names
        
    #view_url = reverse('utility.views.upload_handler')
    view_url = request.path
    #upload_url, upload_data = prepare_upload(request, view_url)
    upload_url = create_upload_url(view_url)
    upload_data = {}
    
    context = {
        'city': city.name,
        'bldg': building,
        'unit': unit,
        #'form': form,
        'meta': form,
        'upload_url': upload_url,
        'providers': json.dumps(utility_providers),        
        }

    return render(request, 'upload_simple.html', context )
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
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")