Ejemplo n.º 1
0
def view_kwh_log():
    """Lists all kwh the user has entered. User can enter and edit data on this
    page."""

    user_id = session.get("user_id")

    if user_id:

        electricity_logs = ElectricityLog.query.filter(
            ElectricityLog.residence.has(
                Residence.user_id == user_id)).order_by(
                    ElectricityLog.start_date.desc()).all()

        residences = Residence.query.filter_by(user_id=user_id).order_by(
            Residence.is_default.desc(), Residence.residence_id.desc()).all()

        if electricity_logs:
            summary = ElectricityLog.get_electricity_summary(user_id)
        else:
            summary = None

        years = reversed(ElectricityLog.get_kwh_years(user_id))

        return render_template("kwh-list.html",
                               electricity_logs=electricity_logs,
                               residences=residences,
                               summary=summary,
                               years=years)

    # return to homepage when not logged in
    else:
        return redirect("/")
Ejemplo n.º 2
0
def get_year_comparison_data():

    user_id = session.get("user_id")

    years = [2017, 2016, 2015, 2014]
    this_year = date.today().year
    days_this_year = days_btw_today_and_jan1()

    trip_co2 = TripLog.get_co2_per_yr(user_id)
    kwh_co2 = ElectricityLog.get_co2_per_yr(user_id)
    ng_co2 = NGLog.get_co2_per_yr(user_id)

    co2_per_yr = []

    for year in years:
        total = 0
        if trip_co2.get(year):
            total += trip_co2[year]["total"]
        if kwh_co2.get(year):
            total += kwh_co2[year]["total"]
        if ng_co2.get(year):
            total += ng_co2[year]["total"]

        if year != this_year:
            co2_per_yr.append(round(total, 2))
        else:
            yr_projected = round(total / days_this_year, 2) * 365
            co2_per_yr.append(yr_projected)

    return jsonify(co2_per_yr)
Ejemplo n.º 3
0
def add_kwh():
    """User kwh data for the user."""

    start_date = request.form.get("start_date")
    end_date = request.form.get("end_date")
    kwh = request.form.get("kwh")
    name_or_address = request.form.get("residence")
    user_id = session.get("user_id")

    try:
        residence = Residence.query.filter_by(
            user_id=user_id, name_or_address=name_or_address).one()
    except NoResultFound:  # .one() error
        residence = Residence.query.filter_by(
            user_id=user_id, name_or_address=name_or_address).first()

    residence_id = residence.residence_id

    new_kwh = ElectricityLog(start_date=start_date,
                             end_date=end_date,
                             kwh=kwh,
                             residence_id=residence_id)

    db.session.add(new_kwh)
    db.session.commit()

    return redirect("/kwh-log")
Ejemplo n.º 4
0
def get_yearly_totals(user_id):

    years = set()
    years.update(TripLog.get_trip_years(user_id),
                 ElectricityLog.get_kwh_years(user_id),
                 NGLog.get_ng_years(user_id))
    this_year = date.today().year
    days_this_year = days_btw_today_and_jan1()

    trip_co2 = TripLog.get_co2_per_yr(user_id)
    kwh_co2 = ElectricityLog.get_co2_per_yr(user_id)
    ng_co2 = NGLog.get_co2_per_yr(user_id)

    co2_per_yr = {}

    for year in years:
        total = 0
        if trip_co2.get(year):
            total += trip_co2[year]["total"]
        if kwh_co2.get(year):
            total += kwh_co2[year]["total"]
        if ng_co2.get(year):
            total += ng_co2[year]["total"]

        if year != this_year:
            daily_avg = round(total / 365, 2)
            co2_per_yr[year] = {
                "total": round(total, 2),
                "daily_avg": daily_avg
            }
        else:
            daily_avg = round(total / days_this_year, 2)
            co2_per_yr[year] = {
                "total": round(total, 2),
                "daily_avg": daily_avg,
                "yr_projected": daily_avg * 365
            }

    return co2_per_yr
Ejemplo n.º 5
0
def get_co2_per_datatype():

    user_id = session.get("user_id")
    year = request.args.get("year")

    start_date = "1/1/1900"
    end_date = "1/1/2036"

    if year != "ALL YEARS":
        start_date = "1/1/%s" % (year)
        end_date = "12/31/%s" % (year)

    trip_co2 = TripLog.sum_trip_co2(user_id, start_date, end_date)
    kwh_co2 = ElectricityLog.sum_kwh_co2(user_id, start_date, end_date)
    ng_co2 = NGLog.sum_ng_co2(user_id, start_date, end_date)

    return jsonify([trip_co2, kwh_co2, ng_co2])
Ejemplo n.º 6
0
def get_co2_trend():
    """Calculate the monthly CO2 for each CO2 source for a given year and
    return as json."""

    user_id = session.get("user_id")
    year = request.args.get("year")

    months = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    months = sorted(months.items())
    trip_co2_per_month = []
    kwh_co2_per_month = []
    ng_co2_per_month = []

    for month in months:
        start_date = "%s/1/%s" % (month[0], year)
        end_date = "%s/%s/%s" % (month[0], month[1], year)
        trip_co2_per_month.append(
            TripLog.sum_trip_co2(user_id, start_date, end_date))
        kwh_co2_per_month.append(
            ElectricityLog.sum_kwh_co2(user_id, start_date, end_date))
        ng_co2_per_month.append(NGLog.sum_ng_co2(user_id, start_date,
                                                 end_date))

    return jsonify({
        "trip": trip_co2_per_month,
        "kwh": kwh_co2_per_month,
        "ng": ng_co2_per_month
    })
Ejemplo n.º 7
0
def get_co2_by_day_of_week():
    """Get the total CO2 for each day of the week from each source given a date
    range."""

    user_id = session.get("user_id")
    year = request.args.get("year")

    start_date = "1/1/%s" % (year)
    end_date = "12/31/%s" % (year)

    trip_co2_by_day_of_week = TripLog.calculate_total_co2_per_day_of_week(
        user_id, start_date, end_date)

    kwh_co2_by_day_of_week = ElectricityLog.calculate_total_co2_per_day_of_week(
        user_id, start_date, end_date)

    return jsonify({
        "trip": trip_co2_by_day_of_week.values(),
        "kwh": kwh_co2_by_day_of_week.values()
    })
Ejemplo n.º 8
0
def load_daily_kwh(residence_id, csv_file):
    """Load kwh into database."""

    print "\n Load kwh \n"

    with open(csv_file) as csvfile:
        reader = csv.DictReader(csvfile)
        kwh_data = {}
        for row_dict in reader:
            date = row_dict["DATE"]
            usage = float(row_dict["USAGE"])

            kwh_data[date] = kwh_data.get(date, 0) + usage

        for date in kwh_data:
            elect_log = ElectricityLog(residence_id=residence_id,
                                       kwh=kwh_data[date],
                                       start_date=date,
                                       end_date=date)
            db.session.add(elect_log)
    db.session.commit()
Ejemplo n.º 9
0
def homepage():
    """Renders login template if the user is not signed in and the homepage if
    the user is logged in."""

    user_id = session.get("user_id")

    if user_id:
        name = User.query.get(user_id).name
        years = set()
        years.update(TripLog.get_trip_years(user_id),
                     ElectricityLog.get_kwh_years(user_id),
                     NGLog.get_ng_years(user_id))
        this_year = date.today().year

        makes = Car.get_unique_makes()
        usercars = UserCar.query.filter_by(user_id=user_id).order_by(
            UserCar.is_default.desc(), UserCar.usercar_id.desc()).all()

        co2_per_yr = get_yearly_totals(user_id)

        if co2_per_yr.get(this_year):
            trees_to_offset = int(
                round(co2_per_yr[this_year]["yr_projected"] /
                      TREE_POUNDS_CO2_PER_YEAR))
        else:
            trees_to_offset = 0

        return render_template("homepage.html",
                               years=sorted(years, reverse=True),
                               makes=makes,
                               usercars=usercars,
                               co2_per_yr=co2_per_yr,
                               this_year=this_year,
                               trees=trees_to_offset,
                               name=name)

    else:
        return render_template("login-register.html")
Ejemplo n.º 10
0
def get_co2_other_location():
    """Calculate the kwh CO2 for the user's current residence and as well as the
    potential CO2 at a different location and return as JSON."""

    user_id = session.get("user_id")
    year = request.args.get("year")
    zipcode = request.args.get("zipcode")

    months = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    months = sorted(months.items())

    kwh_co2_per_month = []
    kwh_co2_per_month_other_location = []

    if datetime.now().year == int(year):
        days = days_btw_today_and_jan1()
    else:
        days = 365

    for month in months:
        start_date = "%s/1/%s" % (month[0], year)
        end_date = "%s/%s/%s" % (month[0], month[1], year)

        # CO2 per month
        kwh_co2_per_month.append(
            ElectricityLog.sum_kwh_co2(user_id, start_date, end_date))
        kwh_co2_per_month_other_location.append(
            ElectricityLog.sum_kwh_co2_other_location(user_id, zipcode,
                                                      start_date, end_date))

        # CO2 per day (rate)
        co2_daily_rate = round(sum(kwh_co2_per_month) / days, 2)
        co2_daily_rate_other_location = round(
            sum(kwh_co2_per_month_other_location) / days, 2)

        # Total CO2 for the year
        kwh_co2_per_year = round(sum(kwh_co2_per_month), 2)
        kwh_co2_per_year_other_location = round(
            sum(kwh_co2_per_month_other_location), 2)

        # percent change = (current - new) / current * 100
        try:
            percent_change = int(
                abs(kwh_co2_per_year - kwh_co2_per_year_other_location) /
                kwh_co2_per_year * 100)
        except ZeroDivisionError:
            percent_change = None

        if percent_change is None:
            statement = "There is no data for that year to compare."
        elif kwh_co2_per_year > kwh_co2_per_year_other_location:
            statement = "This location {} your carbon footprint by {}%".format(
                "decreases", percent_change)
        elif kwh_co2_per_year < kwh_co2_per_year_other_location:
            statement = "This location {} your carbon footprint by {}%".format(
                "increases", percent_change)
        elif kwh_co2_per_year == kwh_co2_per_year_other_location:
            statement = "This location doesn't change the carbon footprint"

    return jsonify({
        "current_monthly_co2": kwh_co2_per_month,
        "new_monthly_co2": kwh_co2_per_month_other_location,
        "current_yearly_co2": kwh_co2_per_year,
        "new_yearly_co2": kwh_co2_per_year_other_location,
        "current_daily_rate": co2_daily_rate,
        "new_daily_rate": co2_daily_rate_other_location,
        "comparison_statement": statement
    })