コード例 #1
0
def edit_energystar(request, account_id, space_id):
    account = get_object_or_404(Account, pk=account_id)
    space = get_object_or_404(Space, pk=space_id)
    if check_permission(request, account, space) is False:
        return HttpResponseRedirect("/%s/status/" % (account.id))

    # ---branching for POST vs. GET request
    if request.method == "POST":  # If a form has been submitted...
        if "edit_space_energystar" in request.POST:
            space_energystar_form = SpaceENERGYSTAREditForm(
                request.POST, request.FILES
            )  # A form bound to the POST data
            if space_energystar_form.is_valid():  # All validation rules pass
                # Process the data in building_energystar_form.cleaned_data
                space.__setattr__(
                    "amountOfLaundryProcessedAnnually",
                    space_energystar_form.cleaned_data["amountOfLaundryProcessedAnnually"],
                )
                space.__setattr__(
                    "averageEffluentBiologicalOxygenDemand",
                    space_energystar_form.cleaned_data["averageEffluentBiologicalOxygenDemand"],
                )
                space.__setattr__(
                    "averageInfluentBiologicalOxygenDemand",
                    space_energystar_form.cleaned_data["averageInfluentBiologicalOxygenDemand"],
                )
                space.__setattr__(
                    "averageNumberOfResidents", space_energystar_form.cleaned_data["averageNumberOfResidents"]
                )
                space.__setattr__(
                    "completelyEnclosedFootage", space_energystar_form.cleaned_data["completelyEnclosedFootage"]
                )
                space.__setattr__("cookingFacilities", space_energystar_form.cleaned_data["cookingFacilities"])
                space.__setattr__(
                    "coolingEquipmentRedundancy", space_energystar_form.cleaned_data["coolingEquipmentRedundancy"]
                )
                space.__setattr__("enclosedFloorArea", space_energystar_form.cleaned_data["enclosedFloorArea"])
                space.__setattr__("enrollment", space_energystar_form.cleaned_data["enrollment"])
                space.__setattr__(
                    "exteriorEntranceToThePublic", space_energystar_form.cleaned_data["exteriorEntranceToThePublic"]
                )
                space.__setattr__(
                    "fixedFilmTrickleFiltrationProcess",
                    space_energystar_form.cleaned_data["fixedFilmTrickleFiltrationProcess"],
                )
                space.__setattr__(
                    "fullServiceSpaFloorArea", space_energystar_form.cleaned_data["fullServiceSpaFloorArea"]
                )
                space.__setattr__(
                    "governmentSubsidizedHousing", space_energystar_form.cleaned_data["governmentSubsidizedHousing"]
                )
                space.__setattr__("grantDollars", space_energystar_form.cleaned_data["grantDollars"])
                space.__setattr__("gymCenterFloorArea", space_energystar_form.cleaned_data["gymCenterFloorArea"])
                space.__setattr__("gymnasiumFloorArea", space_energystar_form.cleaned_data["gymnasiumFloorArea"])
                space.__setattr__("hasComputerLab", space_energystar_form.cleaned_data["hasComputerLab"])
                space.__setattr__("hasDiningHall", space_energystar_form.cleaned_data["hasDiningHall"])
                space.__setattr__("hasLaboratory", space_energystar_form.cleaned_data["hasLaboratory"])
                space.__setattr__(
                    "hoursPerDayGuestsOnsite", space_energystar_form.cleaned_data["hoursPerDayGuestsOnsite"]
                )
                space.__setattr__("iceEvents", space_energystar_form.cleaned_data["iceEvents"])
                space.__setattr__("isHighSchool", space_energystar_form.cleaned_data["isHighSchool"])
                space.__setattr__("isTertiaryCare", space_energystar_form.cleaned_data["isTertiaryCare"])
                space.__setattr__(
                    "itEnergyMeterConfiguration", space_energystar_form.cleaned_data["itEnergyMeterConfiguration"]
                )
                space.__setattr__("laundryFacility", space_energystar_form.cleaned_data["laundryFacility"])
                space.__setattr__("licensedBedCapacity", space_energystar_form.cleaned_data["licensedBedCapacity"])
                space.__setattr__("maximumNumberOfFloors", space_energystar_form.cleaned_data["maximumNumberOfFloors"])
                space.__setattr__(
                    "maximumResidentCapacity", space_energystar_form.cleaned_data["maximumResidentCapacity"]
                )
                space.__setattr__("monthsInUse", space_energystar_form.cleaned_data["monthsInUse"])
                space.__setattr__("numberOfBedrooms", space_energystar_form.cleaned_data["numberOfBedrooms"])
                space.__setattr__("numberOfCashRegisters", space_energystar_form.cleaned_data["numberOfCashRegisters"])
                space.__setattr__(
                    "numberOfCommercialRefrigerationUnits",
                    space_energystar_form.cleaned_data["numberOfCommercialRefrigerationUnits"],
                )
                space.__setattr__(
                    "numberOfCommercialWashingMachines",
                    space_energystar_form.cleaned_data["numberOfCommercialWashingMachines"],
                )
                space.__setattr__("numberOfComputers", space_energystar_form.cleaned_data["numberOfComputers"])
                space.__setattr__(
                    "numberOfConcertShowEventsPerYear",
                    space_energystar_form.cleaned_data["numberOfConcertShowEventsPerYear"],
                )
                space.__setattr__("numberOfDishwashers", space_energystar_form.cleaned_data["numberOfDishwashers"])
                space.__setattr__("numberOfFTEWorkers", space_energystar_form.cleaned_data["numberOfFTEWorkers"])
                space.__setattr__(
                    "numberOfGuestMealsServedPerYear",
                    space_energystar_form.cleaned_data["numberOfGuestMealsServedPerYear"],
                )
                space.__setattr__("numberOfHotelRooms", space_energystar_form.cleaned_data["numberOfHotelRooms"])
                space.__setattr__(
                    "numberOfLaundryHookupsInAllUnits",
                    space_energystar_form.cleaned_data["numberOfLaundryHookupsInAllUnits"],
                )
                space.__setattr__(
                    "numberOfLaundryHookupsInCommonArea",
                    space_energystar_form.cleaned_data["numberOfLaundryHookupsInCommonArea"],
                )
                space.__setattr__("numberOfMriMachines", space_energystar_form.cleaned_data["numberOfMriMachines"])
                space.__setattr__(
                    "numberOfOpenClosedRefrigerationUnits",
                    space_energystar_form.cleaned_data["numberOfOpenClosedRefrigerationUnits"],
                )
                space.__setattr__("numberOfPeople", space_energystar_form.cleaned_data["numberOfPeople"])
                space.__setattr__(
                    "numberOfResidentialLiftSystems",
                    space_energystar_form.cleaned_data["numberOfResidentialLiftSystems"],
                )
                space.__setattr__(
                    "numberOfResidentialLivingUnits",
                    space_energystar_form.cleaned_data["numberOfResidentialLivingUnits"],
                )
                space.__setattr__(
                    "numberOfResidentialWashingMachines",
                    space_energystar_form.cleaned_data["numberOfResidentialWashingMachines"],
                )
                space.__setattr__("numberOfRooms", space_energystar_form.cleaned_data["numberOfRooms"])
                space.__setattr__(
                    "numberOfSpecialOtherEventsPerYear",
                    space_energystar_form.cleaned_data["numberOfSpecialOtherEventsPerYear"],
                )
                space.__setattr__(
                    "numberOfSportingEventsPerYear", space_energystar_form.cleaned_data["numberOfSportingEventsPerYear"]
                )
                space.__setattr__("numberOfStaffedBeds", space_energystar_form.cleaned_data["numberOfStaffedBeds"])
                space.__setattr__(
                    "numberOfSurgicalOperatingBeds", space_energystar_form.cleaned_data["numberOfSurgicalOperatingBeds"]
                )
                space.__setattr__(
                    "numberOfWalkInRefrigerationUnits",
                    space_energystar_form.cleaned_data["numberOfWalkInRefrigerationUnits"],
                )
                space.__setattr__("numberOfWeekdaysOpen", space_energystar_form.cleaned_data["numberOfWeekdaysOpen"])
                space.__setattr__("numberOfWorkers", space_energystar_form.cleaned_data["numberOfWorkers"])
                space.__setattr__("nutrientRemoval", space_energystar_form.cleaned_data["nutrientRemoval"])
                space.__setattr__("onSiteLaundryFacility", space_energystar_form.cleaned_data["onSiteLaundryFacility"])
                space.__setattr__("openFootage", space_energystar_form.cleaned_data["openFootage"])
                space.__setattr__("openOnWeekends", space_energystar_form.cleaned_data["openOnWeekends"])
                space.__setattr__("ownedBy", space_energystar_form.cleaned_data["ownedBy"])
                space.__setattr__(
                    "partiallyEnclosedFootage", space_energystar_form.cleaned_data["partiallyEnclosedFootage"]
                )
                space.__setattr__("percentCooled", space_energystar_form.cleaned_data["percentCooled"])
                space.__setattr__("percentHeated", space_energystar_form.cleaned_data["percentHeated"])
                space.__setattr__("percentOfficeCooled", space_energystar_form.cleaned_data["percentOfficeCooled"])
                space.__setattr__("percentOfficeHeated", space_energystar_form.cleaned_data["percentOfficeHeated"])
                space.__setattr__(
                    "percentOfFloorAreaThatIsCommonSpaceOnly",
                    space_energystar_form.cleaned_data["percentOfFloorAreaThatIsCommonSpaceOnly"],
                )
                space.__setattr__("plantDesignFlowRate", space_energystar_form.cleaned_data["plantDesignFlowRate"])
                space.__setattr__("poolLocation", space_energystar_form.cleaned_data["poolLocation"])
                space.__setattr__("poolSize", space_energystar_form.cleaned_data["poolSize"])
                space.__setattr__(
                    "primaryHotWaterFuelType", space_energystar_form.cleaned_data["primaryHotWaterFuelType"]
                )
                space.__setattr__("residentPopulation", space_energystar_form.cleaned_data["residentPopulation"])
                space.__setattr__("schoolDistrict", space_energystar_form.cleaned_data["schoolDistrict"])
                space.__setattr__("seatingCapacity", space_energystar_form.cleaned_data["seatingCapacity"])
                space.__setattr__("singleStore", space_energystar_form.cleaned_data["singleStore"])
                space.__setattr__(
                    "sizeOfElectronicScoreBoards", space_energystar_form.cleaned_data["sizeOfElectronicScoreBoards"]
                )
                space.__setattr__(
                    "studentSeatingCapacity", space_energystar_form.cleaned_data["studentSeatingCapacity"]
                )
                space.__setattr__("supplementalHeating", space_energystar_form.cleaned_data["supplementalHeating"])
                space.__setattr__(
                    "surgeryCenterFloorArea", space_energystar_form.cleaned_data["surgeryCenterFloorArea"]
                )
                space.__setattr__("totalGrossFloorArea", space_energystar_form.cleaned_data["totalGrossFloorArea"])
                space.__setattr__("upsSystemRedundancy", space_energystar_form.cleaned_data["upsSystemRedundancy"])
                space.__setattr__("weeklyOperatingHours", space_energystar_form.cleaned_data["weeklyOperatingHours"])

                space.save()
                messages.success(
                    request, "Space ENERGY STAR info has been updated. Building scores may take 60 seconds to update."
                )

                # assign worker to recalculate ENERGY STAR score
                rc = RESTClient()
                pm = PortfolioManager(rest_client=rc)

                if settings.DJANGO_ENV != "development":
                    q = Queue(connection=conn)
                    result = q.enqueue(pm.set_scores_for_building, space.building)
                else:
                    pm.set_scores_for_building(building=space.building)

                space_view_url = "/%s/spaces/%s/details/" % (account.id, space.id)
                return HttpResponseRedirect(space_view_url)
    elif request.method == "GET":
        space_energystar_form = SpaceENERGYSTAREditForm(
            {
                "amountOfLaundryProcessedAnnually": space.amountOfLaundryProcessedAnnually,
                "averageEffluentBiologicalOxygenDemand": space.averageEffluentBiologicalOxygenDemand,
                "averageInfluentBiologicalOxygenDemand": space.averageInfluentBiologicalOxygenDemand,
                "averageNumberOfResidents": space.averageNumberOfResidents,
                "completelyEnclosedFootage": space.completelyEnclosedFootage,
                "cookingFacilities": space.cookingFacilities,
                "coolingEquipmentRedundancy": space.coolingEquipmentRedundancy,
                "enclosedFloorArea": space.enclosedFloorArea,
                "enrollment": space.enrollment,
                "exteriorEntranceToThePublic": space.exteriorEntranceToThePublic,
                "fixedFilmTrickleFiltrationProcess": space.fixedFilmTrickleFiltrationProcess,
                "fullServiceSpaFloorArea": space.fullServiceSpaFloorArea,
                "governmentSubsidizedHousing": space.governmentSubsidizedHousing,
                "grantDollars": space.grantDollars,
                "gymCenterFloorArea": space.gymCenterFloorArea,
                "gymnasiumFloorArea": space.gymnasiumFloorArea,
                "hasComputerLab": space.hasComputerLab,
                "hasDiningHall": space.hasDiningHall,
                "hasLaboratory": space.hasLaboratory,
                "hoursPerDayGuestsOnsite": space.hoursPerDayGuestsOnsite,
                "iceEvents": space.iceEvents,
                "isHighSchool": space.isHighSchool,
                "isTertiaryCare": space.isTertiaryCare,
                "itEnergyMeterConfiguration": space.itEnergyMeterConfiguration,
                "laundryFacility": space.laundryFacility,
                "licensedBedCapacity": space.licensedBedCapacity,
                "maximumNumberOfFloors": space.maximumNumberOfFloors,
                "maximumResidentCapacity": space.maximumResidentCapacity,
                "monthsInUse": space.monthsInUse,
                "numberOfBedrooms": space.numberOfBedrooms,
                "numberOfCashRegisters": space.numberOfCashRegisters,
                "numberOfCommercialRefrigerationUnits": space.numberOfCommercialRefrigerationUnits,
                "numberOfCommercialWashingMachines": space.numberOfCommercialWashingMachines,
                "numberOfComputers": space.numberOfComputers,
                "numberOfConcertShowEventsPerYear": space.numberOfConcertShowEventsPerYear,
                "numberOfDishwashers": space.numberOfDishwashers,
                "numberOfFTEWorkers": space.numberOfFTEWorkers,
                "numberOfGuestMealsServedPerYear": space.numberOfGuestMealsServedPerYear,
                "numberOfHotelRooms": space.numberOfHotelRooms,
                "numberOfLaundryHookupsInAllUnits": space.numberOfLaundryHookupsInAllUnits,
                "numberOfLaundryHookupsInCommonArea": space.numberOfLaundryHookupsInCommonArea,
                "numberOfMriMachines": space.numberOfMriMachines,
                "numberOfOpenClosedRefrigerationUnits": space.numberOfOpenClosedRefrigerationUnits,
                "numberOfPeople": space.numberOfPeople,
                "numberOfResidentialLiftSystems": space.numberOfResidentialLiftSystems,
                "numberOfResidentialLivingUnits": space.numberOfResidentialLivingUnits,
                "numberOfResidentialWashingMachines": space.numberOfResidentialWashingMachines,
                "numberOfRooms": space.numberOfRooms,
                "numberOfSpecialOtherEventsPerYear": space.numberOfSpecialOtherEventsPerYear,
                "numberOfSportingEventsPerYear": space.numberOfSportingEventsPerYear,
                "numberOfStaffedBeds": space.numberOfStaffedBeds,
                "numberOfSurgicalOperatingBeds": space.numberOfSurgicalOperatingBeds,
                "numberOfWalkInRefrigerationUnits": space.numberOfWalkInRefrigerationUnits,
                "numberOfWeekdaysOpen": space.numberOfWeekdaysOpen,
                "numberOfWorkers": space.numberOfWorkers,
                "nutrientRemoval": space.nutrientRemoval,
                "onSiteLaundryFacility": space.onSiteLaundryFacility,
                "openFootage": space.openFootage,
                "openOnWeekends": space.openOnWeekends,
                "ownedBy": space.ownedBy,
                "partiallyEnclosedFootage": space.partiallyEnclosedFootage,
                "percentCooled": space.percentCooled,
                "percentHeated": space.percentHeated,
                "percentOfficeCooled": space.percentOfficeCooled,
                "percentOfficeHeated": space.percentOfficeHeated,
                "percentOfFloorAreaThatIsCommonSpaceOnly": space.percentOfFloorAreaThatIsCommonSpaceOnly,
                "plantDesignFlowRate": space.plantDesignFlowRate,
                "poolLocation": space.poolLocation,
                "poolSize": space.poolSize,
                "primaryHotWaterFuelType": space.primaryHotWaterFuelType,
                "residentPopulation": space.residentPopulation,
                "schoolDistrict": space.schoolDistrict,
                "seatingCapacity": space.seatingCapacity,
                "singleStore": space.singleStore,
                "sizeOfElectronicScoreBoards": space.sizeOfElectronicScoreBoards,
                "studentSeatingCapacity": space.studentSeatingCapacity,
                "supplementalHeating": space.supplementalHeating,
                "surgeryCenterFloorArea": space.surgeryCenterFloorArea,
                "totalGrossFloorArea": space.totalGrossFloorArea,
                "upsSystemRedundancy": space.upsSystemRedundancy,
                "weeklyOperatingHours": space.weeklyOperatingHours,
            }
        )

    main_page_help_text = "Space ENERGY STAR Info - change any field(s), then click Update to save."
    tab_help_text = "not used"

    context = {
        "sidebar": "buildingspeakapp/shared/account_sidebar.html",
        "tab": "details",
        "main_page_help_text": main_page_help_text,
        "tab_help_text": tab_help_text,
        "user": request.user,
        "account": account,
        "accounts": request.user.account_set.order_by("id"),
        "buildings": account.building_set.order_by("name"),
        "spaces": Space.objects.filter(Q(building__account=account) | Q(meters__account=account))
        .distinct()
        .order_by("name"),
        "meters": account.meter_set.order_by("name"),
        "equipments": Equipment.objects.filter(Q(buildings__account=account) | Q(meters__account=account))
        .distinct()
        .order_by("name"),
        "space_energystar_form": space_energystar_form,
        "space": space,
        "space_ESPM_type": space.get_ESPM_type_display(),
    }

    template_name = "buildingspeakapp/spaces/edit_energystar.html"
    return render(request, template_name, RequestContext(request, context))
コード例 #2
0
    def handle(self, *args, **options):

        # capture content_id which will indicate which piece of functionality we're after
        content_id = args[1]

        # add blocks of code here that can be run by calling the right content_id
        # must include comment line indicating what additional arguments are used

        if content_id == "get_building_energystar_xml":
            # SendEmail   email   get_building_energystar_xml   building_id

            to = args[0]
            subject = "OPS: xml for ENERGY STAR score for Building %s" % args[2]

            rc = RESTClient()
            pm = PortfolioManager(rest_client=rc)
            xml = pm.get_xml(building=Building.objects.get(id=args[2]))

            # create context dict containing variables referenced by template tags in html file
            context = Context({"content_id": content_id, "xml": xml})

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.to = [to]
            email.attach_alternative(html_body, "text/html")

            email.send()

        elif content_id == "get_latest_meter_end_dates":
            # SendEmail   email   get_latest_meter_end_dates

            to = args[0]
            subject = "OPS: latest end dates for all Meters"

            meter_lines = []

            for meter in Meter.objects.all():
                meter_df = meter.get_bill_data_period_dataframe()
                # extract non-forecasted data
                meter_df["Cost (act) is not NaN"] = [not (x) for x in meter_df["Cost (act)"].apply(math.isnan)]
                meter_df["Consumption (act) is not NaN"] = [
                    not (x) for x in meter_df["Consumption (act)"].apply(math.isnan)
                ]
                meter_df["Peak Demand (act) is not NaN"] = [
                    not (x) for x in meter_df["Peak Demand (act)"].apply(math.isnan)
                ]
                temp = [
                    [
                        meter_df["Cost (act) is not NaN"][i],
                        meter_df["Consumption (act) is not NaN"][i],
                        meter_df["Peak Demand (act) is not NaN"][i],
                    ]
                    for i in range(0, len(meter_df))
                ]
                meter_df["IsNotForecasted"] = [i[0] or i[1] or i[2] for i in temp]
                meter_df = meter_df[meter_df["IsNotForecasted"]]
                meter_df = meter_df.sort_index()

                meter_lines.append(
                    [meter.id, meter.account.id, meter.account.name, meter_df["End Date"][-1].strftime("%m/%d/%Y")]
                )

            print_lines = [["Meter ID", "Account ID", "Account Name", "Latest End Date"]]
            print_lines.extend(sorted(meter_lines, key=itemgetter(3), reverse=False))

            # create context dict containing variables referenced by template tags in html file
            context = Context({"content_id": content_id, "meter_end_dates_table": print_lines})

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.to = [to]
            email.attach_alternative(html_body, "text/html")

            email.send()

        elif content_id == "check_meter_forecasts":
            # SendEmail   email   check_meter_forecasts

            to = args[0]
            subject = "OPS: check Meter forecasts"

            meter_lines = []

            for meter in Meter.objects.all():
                meter_df = meter.get_bill_data_period_dataframe()

                meter_lines.append(
                    [meter.id, meter.account.id, meter.account.name, meter_df.index[-1].strftime("%b %Y")]
                )

            print_lines = [["Meter ID", "Account ID", "Account Name", "Latest Forecasted Month"]]
            print_lines.extend(sorted(meter_lines, key=itemgetter(3), reverse=False))

            # create context dict containing variables referenced by template tags in html file
            context = Context({"content_id": content_id, "meter_latest_forecasted_month_table": print_lines})

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.to = [to]
            email.attach_alternative(html_body, "text/html")

            email.send()

        elif content_id == "get_financial_summary":
            # SendEmail   email   get_financial_summary

            to = args[0]
            subject = "FINANCE: summary of all accounts"

            acct_lines = [
                [
                    "Account ID",
                    "Account Name",
                    "Monthly Payment",
                    "User Count",
                    "Meter Count",
                    "Meter Count Over 10",
                    "Stripe ID",
                    "Stripe CC Exp. Mo.",
                    "Stripe CC Exp. Yr.",
                    "Stripe CC Last 4",
                    "Stripe CC Type",
                    "# Failed Attempts",
                    "CC Updated Since Last Attempt?",
                    "Latest Payment Date",
                    "Latest Payment Amount ($)",
                ]
            ]

            for acct in Account.objects.exclude(id=12):
                num_meters = acct.meter_set.count()
                if acct.payments.count() > 0:
                    latest_payment_date = acct.payments.order_by("-created_at")[0].created_at.strftime("%m/%d/%Y")
                    latest_payment_amount = acct.payments.order_by("-created_at")[0].amount_in_cents / 100.0
                else:
                    latest_payment_date = "No payments!"
                    latest_payment_amount = 0.00

                acct_lines.append(
                    [
                        acct.id,
                        acct.name,
                        "%.2f" % acct.monthly_payment,
                        str(acct.users.exclude(is_staff=True).count()),
                        str(num_meters),
                        str(max(num_meters - 10, 0)),
                        acct.stripe_customer_id,
                        acct.stripe_cc_exp_month,
                        acct.stripe_cc_exp_year,
                        acct.stripe_cc_last_4,
                        acct.stripe_cc_type,
                        acct.failed_charge_attempts,
                        acct.payment_details_updated_since_last_attempt,
                        latest_payment_date,
                        latest_payment_amount,
                    ]
                )

            # create context dict containing variables referenced by template tags in html file
            context = Context({"content_id": "account_financials", "acct_data_table": acct_lines})

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.to = [to]
            email.attach_alternative(html_body, "text/html")

            email.send()

        elif content_id == "get_all_stripe_events":
            # SendEmail   email   get_all_stripe_events

            to = args[0]
            subject = "FINANCE: all (recent) Stripe events"

            stripe.api_key = settings.STRIPE_SECRET_KEY
            x = stripe.Event.all()
            if len(x) > 0 and "data" in x:
                list_of_events = x["data"]

                customer_created = [
                    ["Created", "New Customer ID", "New Customer Desc.", "New Customer Email", "Event ID"]
                ]
                customer_card_created = [
                    ["Created", "Customer ID", "New Card ID", "New Card Type", "Last 4 Digits", "Event ID"]
                ]
                charge_succeeded = [
                    [
                        "Created",
                        "Customer ID",
                        "Statement Description",
                        "Charge Amount",
                        "Card ID",
                        "Charge ID",
                        "Event ID",
                    ]
                ]
                charge_failed = [
                    [
                        "Created",
                        "Customer ID",
                        "Statement Description",
                        "Charge Amount",
                        "Card ID",
                        "Charge ID",
                        "Event ID",
                    ]
                ]
                transfer_created = [
                    ["Created", "Date", "Transfer ID", "Charge Count", "Gross", "Fees", "Net", "Event ID"]
                ]
                transfer_paid = [["Created", "Date", "Transfer ID", "Charge Count", "Gross", "Fees", "Net", "Event ID"]]

                temp = [
                    customer_created.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["id"],
                            i["data"]["object"]["description"],
                            i["data"]["object"]["email"],
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "customer.created"
                ]
                temp = [
                    customer_card_created.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["customer"],
                            i["data"]["object"]["id"],
                            i["data"]["object"]["type"],
                            i["data"]["object"]["last4"],
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "customer.card.created"
                ]
                temp = [
                    charge_succeeded.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["customer"],
                            i["data"]["object"]["statement_description"],
                            "${0:,.2f}".format(i["data"]["object"]["amount"] / 100.0),
                            i["data"]["object"]["card"]["id"],
                            i["data"]["object"]["id"],
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "charge.succeeded"
                ]
                temp = [
                    charge_failed.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["customer"],
                            i["data"]["object"]["statement_description"],
                            "${0:,.2f}".format(i["data"]["object"]["amount"] / 100.0),
                            i["data"]["object"]["card"]["id"],
                            i["data"]["object"]["id"],
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "charge.failed"
                ]
                temp = [
                    transfer_created.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            datetime.fromtimestamp(float(i["data"]["object"]["date"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["id"],
                            i["data"]["object"]["summary"]["charge_count"],
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["charge_gross"] / 100.0),
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["charge_fees"] / 100.0),
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["net"] / 100.0),
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "transfer.created"
                ]
                temp = [
                    transfer_paid.append(
                        [
                            datetime.fromtimestamp(float(i["created"])).strftime("%Y-%m-%d %H:%M:%S"),
                            datetime.fromtimestamp(float(i["data"]["object"]["date"])).strftime("%Y-%m-%d %H:%M:%S"),
                            i["data"]["object"]["id"],
                            i["data"]["object"]["summary"]["charge_count"],
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["charge_gross"] / 100.0),
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["charge_fees"] / 100.0),
                            "${0:,.2f}".format(i["data"]["object"]["summary"]["net"] / 100.0),
                            i["id"],
                        ]
                    )
                    for i in list_of_events
                    if i["type"] == "transfer.paid"
                ]
            else:
                customer_created = []
                customer_card_created = []
                charge_succeeded = []
                charge_failed = []
                transfer_created = []
                transfer_paid = []

            # create context dict containing variables referenced by template tags in html file
            context = Context(
                {
                    "content_id": "get_all_stripe_events",
                    "charge_succeeded": charge_succeeded if len(charge_succeeded) > 1 else None,
                    "charge_failed": charge_failed if len(charge_failed) > 1 else None,
                    "customer_card_created": customer_card_created if len(customer_card_created) > 1 else None,
                    "customer_created": customer_created if len(customer_created) > 1 else None,
                    "transfer_created": transfer_created if len(transfer_created) > 1 else None,
                    "transfer_paid": transfer_paid if len(transfer_paid) > 1 else None,
                }
            )

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.to = [to]
            email.attach_alternative(html_body, "text/html")

            email.send()

        elif content_id == "check_ENERGY_STAR_scores":
            # SendEmail   email   check_ENERGY_STAR_scores

            to = args[0]
            subject = "OPS: checking ENERGY STAR scores (unavailable, 0, or 100)"

            bldg_lines = []

            for bldg in Building.objects.all():
                if (
                    bldg.ES_score_past_12_months == "unavailable"
                    or bldg.ES_score_next_12_months == "unavailable"
                    or bldg.ES_score_past_12_months == "0"
                    or bldg.ES_score_next_12_months == "100"
                    or bldg.ES_score_past_12_months == "0"
                    or bldg.ES_score_next_12_months == "100"
                ):
                    bldg_lines.append(
                        [
                            bldg.id,
                            bldg.account.id,
                            bldg.account.name,
                            bldg.ES_score_past_12_months,
                            bldg.ES_score_next_12_months,
                        ]
                    )

            print_lines = [
                ["Building ID", "Account ID", "Account Name", "Past 12 ENERGY STAR Score", "Next 12 ENERGY STAR Score"]
            ]
            if len(bldg_lines) > 0:
                print_lines.extend(sorted(bldg_lines, key=itemgetter(1), reverse=False))
            if len(bldg_lines) == 0:
                subject = "OPS: no ENERGY STAR scores unavailable, 0, or 100!"

            # create context dict containing variables referenced by template tags in html file
            context = Context(
                {
                    "content_id": "check_ENERGY_STAR_scores",
                    "data_table": print_lines
                    if len(print_lines) > 1
                    else [["No ENERGY STAR scores are unavailable or at the boundaries of 0 or 100!"]],
                }
            )

            # turn html file + context variable into string for html body
            html_body = render_to_string("mail/staffinfo_renderer.html", context)

            # construct email and reference Mandrill template name to be used
            email = EmailMultiAlternatives(subject, html_body, headers={"X-MC-Template": "staffinfo"})
            email.attach_alternative(html_body, "text/html")

            # supposed to be able to set equal to list of addresses, but that fails, so we cycle through
            email.to = [to]
            email.send()