Beispiel #1
0
    def show(self):
        municipality = self.request.context
        site_reports = None
        trend_data = None
        # generate a trend view of saved municipality reports
        # get all site reports belonging to the municipality
        period = date_from_string_or_default(self.request.GET, 'period', None,
                                             '%Y-%m')

        if period:
            try:
                site_report = SiteReport.get(
                    SiteReport.municipality == municipality,
                    extract("year", SiteReport.report_date) == period.year,
                    extract("month", SiteReport.report_date) == period.month)
                site_reports = [site_report]
            except NoResultFound:
                self.request.session.flash(
                    u"Cannot find site report for {}.".format(
                        period.strftime("%b %Y")), "error")

        if site_reports is None:
            site_reports = SiteReport.all(
                SiteReport.municipality == municipality)

            trend_data = json.dumps(get_trend_data(site_reports))

        end = (period or datetime.date.today())

        return {
            'municipality': municipality,
            'trend_data': trend_data,
            'site_reports': site_reports,
            'date': end
        }
Beispiel #2
0
 def _add_site_report(self):
     site_report = SiteReport(report_date=datetime.datetime(YEAR,
                                                            MONTH,
                                                            DAY),
                              municipality=self.municipality,
                              report_json={'vehicle_count': 0})
     with transaction.manager:
         site_report.save()
Beispiel #3
0
    def site_reports(self):
        municipality = self.request.context
        # default to start and end of current month
        today = datetime.date.today()
        default_start, default_end = get_month_start_end(today)

        start, end = get_start_end_date(self.request.GET, default_start,
                                        default_end, today)

        # not necessary but pretty format the date range when we can
        if start == default_start and end == default_end:
            label = "This Month"
        elif (today - start).days == 1:
            label = "Yesterday"
        elif end == today:
            time_labels = [
                # if start and end are the same, the label is today
                (lambda dt: dt.days == 0, "Today"),
                # if timedelta between start and end is less than 31 days,
                # last # days
                (lambda dt: 1 < dt.days < 30, "Last {} days")
            ]
            time_delta = today - start
            labels = [l for f, l in time_labels if f(time_delta)]
            label = labels[0].format(time_delta.days + 1)\
                if len(labels) == 1 else None
        else:
            label = None

        # confirm if site report for selected month period is available
        show_save_report = False
        update_report = False

        if (end - start).days <= 31:
            # show save button if the time period selected is a month
            show_save_report = True
            try:
                # try to retrieve month report
                SiteReport.get_report_by_date(end, municipality)
                update_report = True
            except NoResultFound:
                pass

        return {
            'municipality': municipality,
            'start': start,
            'end': end,
            'label': label,
            'show_save_report': show_save_report,
            'update_report': update_report
        }
Beispiel #4
0
    def test_save_site_report(self):
        initial_count = SiteReport.count()

        self.request.context = self.municipality
        self.request.method = 'POST'
        self.request.POST = MultiDict([
            ('start', '2014-06-1'),
            ('end', '2014-06-30')])

        response = self.views.save_site_report()
        self.assertIsInstance(response, HTTPFound)
        self.assertEqual(SiteReport.count(), initial_count + 1)

        site_report = SiteReport.get_report_by_date(
            datetime.datetime(2014, 6, 1), self.municipality)
        self.assertEqual(site_report.report_date.day, 1)
Beispiel #5
0
    def test_get_trend_data(self):
        site_report_1 = SiteReport(report_date=date.today(),
                                   report_json={
                                       'volume_of_mature_compost': 10,
                                       'electricity_consumption': 150
                                   })
        site_report_2 = SiteReport(report_date=date.today(),
                                   report_json={
                                       'volume_of_mature_compost': 10,
                                       'electricity_consumption': 200
                                   })

        site_reports = [site_report_1, site_report_2]
        trend_data_map = helpers.get_trend_data(site_reports)
        self.assertIsInstance(trend_data_map, dict)
        self.assertIsNotNone(trend_data_map['volume_of_mature_compost'])
        self.assertIsNotNone(trend_data_map['electricity_consumption'])
Beispiel #6
0
    def test_update_report(self):
        self._add_site_report()
        report_date = datetime.datetime(YEAR, MONTH, DAY)
        initial_count = SiteReport.count()
        # use existing municipality instance state
        municipality = self.municipality
        municipality.vehicle_count = MagicMock(return_value=15)

        self.request.context = municipality
        self.request.method = 'POST'
        self.request.POST = MultiDict([
            ('start', '{}-{}-{}'.format(YEAR, MONTH, 1)),
            ('end', '{}-{}-{}'.format(YEAR, MONTH, 31))])
        response = self.views.save_site_report()
        self.assertIsInstance(response, HTTPFound)
        self.assertEqual(SiteReport.count(), initial_count)

        site_report = SiteReport.get_report_by_date(
            report_date, self.municipality)
        self.assertEqual(site_report.report_json['vehicle_count'], 15)
Beispiel #7
0
    def save_site_report(self):
        # get the selected month to create a report for
        # if another report already exists, update it with the report_data
        # contained in the municipality
        today = datetime.date.today()
        default_start, default_end = get_month_start_end(today)
        start, end = get_start_end_date(self.request.POST, default_start,
                                        default_end, today)

        municipality = self.request.context

        # Populate report_data json
        report_json = municipality.get_data_map(start, end)

        # Get start and end date for the month being reported on
        month_start, month_end = get_month_start_end(start)
        try:
            site_report = SiteReport.get_report_by_date(
                month_start, municipality)
            site_report.report_json = report_json
            self.request.session.flash(u"The site report has been updated.",
                                       "success")
        except NoResultFound:
            site_report = SiteReport(report_date=month_start,
                                     municipality=municipality,
                                     report_json=report_json)
            self.request.session.flash(u"The site report has been saved.",
                                       "success")

        site_report.save()

        return HTTPFound(
            self.request.route_url('municipalities',
                                   traverse=(municipality.id, 'reports'),
                                   _query={
                                       'start': start,
                                       'end': end
                                   }))
Beispiel #8
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)

    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    Base.metadata.create_all(engine)

    setup_logging(config_uri)

    pwd_context.load_path(config_uri)

    # create models here
    admin = User(username='******', password='******', active=True,
                 group='nema')
    municipality = Municipality(name="Mukono")
    manager = User(username='******', password='******',
                   active=True, group='sm', municipality=municipality)
    skip_a = Skip(municipality=municipality, skip_type='A', small_length=20,
                  large_length=30, small_breadth=10, large_breadth=16)

    # add dummy site reports
    site_report_1 = SiteReport(
        report_date=datetime.date(2014, 6, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 400,
            'density_of_msw': 0.5,
            'quantity_of_msw_processed': 550,
            'num_trucks_delivered_msw': 20,
            'volume_of_mature_compost': 500,
            'density_of_mature_compost': 3.5,
            'conversion_factor_mature_to_sieved': 0.145,
            'quantity_of_compost_produced': 351,
            'quantity_of_compost_sold': 405,
            'vehicle_count': 15,
            'average_distance': 20,
            'volume_of_rejects_from_sieving': 500,
            'density_of_rejects_from_sieving': 450,
            'quantity_of_rejects_from_sieving_landfilled': 2.4,
            'total_windrow_samples': 14,
            'low_windrow_sample_count': 5,
            'fuel_consumption': 40,
            'electricity_consumption': 150,
            'leachete_volume_accumulated': 200})

    site_report_2 = SiteReport(
        report_date=datetime.date(2014, 4, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 300,
            'density_of_msw': 0.7,
            'quantity_of_msw_processed': 500,
            'num_trucks_delivered_msw': 15,
            'volume_of_mature_compost': 470,
            'density_of_mature_compost': 2.5,
            'conversion_factor_mature_to_sieved': 0.13,
            'quantity_of_compost_produced': 300,
            'quantity_of_compost_sold': 285,
            'vehicle_count': 12,
            'average_distance': 17,
            'volume_of_rejects_from_sieving': 130,
            'density_of_rejects_from_sieving': 150,
            'quantity_of_rejects_from_sieving_landfilled': 1.4,
            'total_windrow_samples': 14,
            'low_windrow_sample_count': 3,
            'fuel_consumption': 28,
            'electricity_consumption': 140,
            'leachete_volume_accumulated': 170})

    site_report_3 = SiteReport(
        report_date=datetime.date(2014, 5, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 200,
            'density_of_msw': 3,
            'quantity_of_msw_processed': 250,
            'num_trucks_delivered_msw': 10,
            'volume_of_mature_compost': 300,
            'density_of_mature_compost': 1.5,
            'conversion_factor_mature_to_sieved': 0.125,
            'quantity_of_compost_produced': 251,
            'quantity_of_compost_sold': 200,
            'vehicle_count': 9,
            'average_distance': 17,
            'volume_of_rejects_from_sieving': 300,
            'density_of_rejects_from_sieving': 175,
            'quantity_of_rejects_from_sieving_landfilled': 2,
            'total_windrow_samples': 10,
            'low_windrow_sample_count': 3,
            'fuel_consumption': 18,
            'electricity_consumption': 110,
            'leachete_volume_accumulated': 140})

    submission_handler_manager.clear()
    hook_submission_handlers()

    with transaction.manager:
        admin.save()
        municipality.save()
        manager.save()
        skip_a.save()
        site_report_1.save()
        site_report_2.save()
        site_report_3.save()

        for status, raw_json in TestBase.submissions:
            json_payload = json.loads(raw_json)
            handler_class = submission_handler_manager.find_handler(
                json_payload)
            handler_class().__call__(json_payload, status=status)