Exemplo n.º 1
0
 def kwh(self, meter, start_date, finish_date):
     sum_kwh = 0
     code = 'complete-data'
     first_read = Read.gql("""where meter = :1 and read_date <= :2 order by
             read_date desc""", meter, start_date).get()
     if first_read is None:
         code = 'partial-data'
     last_read = Read.gql("""where meter = :1 and read_date >= :2 order by
             read_date""", meter, finish_date).get()
     if last_read is None:
         code = 'partial-data'
         q_finish = finish_date
     else:
         q_finish = last_read.read_date
     for read in Read.gql(
             "where meter = :1 and read_date > :2 and read_date <= :3 "
             "order by read_date", meter, start_date, q_finish):
         if first_read is not None:
             rate = (read.value - first_read.value) / \
                 self.total_seconds(read.read_date - first_read.read_date)
             sum_kwh += rate * max(
                 self.total_seconds(
                     min(read.read_date, finish_date) -
                     max(first_read.read_date, start_date)), 0)
         first_read = read
     return {'kwh': sum_kwh, 'code': code, 'start_date': start_date,
             'finish_date': finish_date}
Exemplo n.º 2
0
 def get_unread_items_for_user(self, user):
     q = Item.select(
         Item.id).join(Feed).join(Subscription).join(User).where(
             (User.id == user.id),
             ~(Item.id << Read.select(Read.item).where(User.id == user.id))
         ).order_by(Item.id).distinct().naive()
     return [r.id for r in q]
Exemplo n.º 3
0
 def get(self):
     current_reader = self.require_current_reader()
     read_key = self.get_str('read_key')
     read = Read.get_read(read_key)
     if current_reader.key() != read.meter.reader.key():
         self.return_forbidden()
     self.return_ok(self.page_fields(current_reader, read))
Exemplo n.º 4
0
    def page_fields(self, meter, current_reader, message=None):
        reads = Read.gql(
            "where meter = :1 order by read_date desc", meter).fetch(30)
        now = meter.get_tzinfo().localize(datetime.datetime.now())

        return {'meter': meter, 'reads': reads, 'now': now,
                'candidate_customer_read': meter.candidate_customer_read(),
                'message': message}
Exemplo n.º 5
0
    def post(self):
        current_reader = self.require_current_reader()
        meter_key = self.post_str("meter_key")
        meter = Meter.get_meter(meter_key)
        if current_reader.key() != meter.reader.key():
            self.return_forbidden()

        try:
            read_date = self.post_datetime("read", meter.get_tzinfo())
            value = self.post_float("value")
            read = Read(meter=meter, read_date=read_date, value=value)
            read.put()
            fields = self.page_fields(meter, current_reader)
            fields['read'] = read
            self.return_ok(fields)
        except HTTPBadRequest as e:
            self.return_bad_request(self.page_fields(meter, current_reader, e))
Exemplo n.º 6
0
    def post(self):
        current_reader = self.require_current_reader()
        read_key = self.post_str('read_key')
        read = Read.get_read(read_key)
        try:
            meter = read.meter
            if current_reader.key() != meter.reader.key():
                self.return_forbidden()
            if 'update' in self.request.POST:
                meter.send_read_to = self.post_str('send_read_to').strip()
                meter.send_read_name = self.post_str('send_read_name').strip()
                meter.send_read_reader_email = self.post_str(
                    'send_read_reader_email').strip()
                meter.send_read_address = self.post_str(
                    'send_read_address').strip()
                meter.send_read_postcode = self.post_str(
                    'send_read_postcode').strip()
                meter.send_read_account = self.post_str(
                    'send_read_account').strip()
                meter.send_read_msn = self.post_str('send_read_msn').strip()
                meter.put()
                fields = self.page_fields(current_reader, read)
                fields['message'] = "Info updated successfully."
                self.return_ok(fields)
            else:
                if meter.send_read_to is None or len(meter.send_read_to) == 0:
                    raise HTTPBadRequest(
                        """The supplier's email address must be filled in.""")
                body = jinja2.Template("""Hi, I'd like to submit a \
reading for my {{ read.meter.utility_id }} meter. Details below:

My Name: {{ read.meter.send_read_name }}
My Email Address: {{ read.meter.send_read_reader_email }}
First Line Of Postal Address Of Meter: {{ read.meter.send_read_address }}
Postcode Of Meter: {{ read.meter.send_read_postcode }}
Account Number: {{ read.meter.send_read_account }}
Meter Serial Number: {{ read.meter.send_read_msn }}
Read Date: {{ read.local_read_date().strftime("%Y-%m-%d %H:%M") }}
Reading: {{ read.value }} {{ read.meter.units }}""").render(read=read)

                mail.send_mail(
                    sender="MtrHub <*****@*****.**>",
                    to=meter.send_read_to, cc=meter.send_read_reader_email,
                    reply_to=meter.send_read_reader_email,
                    subject="My " + meter.utility_id + " meter reading",
                    body=body)

                meter.latest_customer_read_date = read.read_date
                meter.put()

                fields = self.page_fields(current_reader, read)
                fields['message'] = "Reading sent successfully."
                self.return_ok(fields)
        except HTTPBadRequest as e:
            self.return_bad_request(self.page_fields(current_reader, read, e))
Exemplo n.º 7
0
 def get(self):
     current_reader = self.find_current_reader()
     read_key = self.get_str("read_key")
     read = Read.get_read(read_key)
     meter = read.meter
     if meter.is_public:
         self.return_ok(self.page_fields(current_reader, read))
     elif current_reader is None:
         self.return_unauthorized()
     elif current_reader.key() == meter.reader.key():
         self.return_ok(self.page_fields(current_reader, read))
     else:
         self.return_forbidden()
Exemplo n.º 8
0
    def post(self):
        try:
            current_reader = self.require_current_reader()
            meter_key = self.post_str("meter_key")
            meter = Meter.get_meter(meter_key)
            if current_reader.key() != meter.reader.key():
                self.return_forbidden()

            file_item = self.post_file("spreadsheet")
            if file_item.filename.endswith(".csv"):
                rdr = csv.reader(file_item.file)
                for row in rdr:
                    if len(row) < 2:
                        raise HTTPBadRequest("""Expecting 2 fields per row, the
                                date in the format yyyy-MM-dd HH:mm followed by
                                the reading.""")
                    try:
                        read_date = datetime.datetime.strptime(
                            row[0].strip(), '%Y-%m-%d %H:%M')
                    except ValueError as e:
                        raise HTTPBadRequest(
                            "Problem at line number " + str(rdr.line_num) +
                            " of the file. The first field (the read date "
                            "field) isn't formatted correctly, it should be "
                            "of the form 2010-02-23T21:46. " + str(e))
                    value = float(row[1].strip())
                    read = Read(meter=meter, read_date=read_date, value=value)
                    read.put()
                fields = self.page_fields(meter, current_reader)
                fields['message'] = 'File imported successfully.'
                self.return_ok(fields)
            else:
                raise HTTPBadRequest("The file name must end with '.csv.'")
        except HTTPBadRequest as e:
            e.values = self.page_fields(meter, current_reader)
            raise e
Exemplo n.º 9
0
    def get(self):
        meter_key = self.get_str("meter_key")
        meter = Meter.get_meter(meter_key)
        if meter.is_public:
            current_reader = self.find_current_reader()
        else:
            current_reader = self.require_current_reader()
            if current_reader.key() != meter.reader.key():
                self.return_forbidden()

        reads = Read.gql(
            "where meter = :1 order by read_date desc", meter).fetch(1000)
        self.return_ok(
            {
                'reads': reads,
                'template_name': 'export_reads.csv',
                'content_disposition': 'attachment; filename=reads.csv;'})
Exemplo n.º 10
0
    def post(self):
        current_reader = self.require_current_reader()
        read_key = self.post_str("read_key")
        read = Read.get_read(read_key)
        try:
            meter = read.meter
            if current_reader.key() != meter.reader.key():
                self.return_forbidden()

            if 'delete' in self.request.POST:
                read.delete()
                self.return_see_other(
                    "/view_meter?meter_key=" + str(meter.key()))
            else:
                read_date = self.post_datetime("read")
                value = self.post_float("value")
                read.update(read_date, value)
                self.add_flash("Read edited successfully.")
                self.return_see_other("/view_read?read_key=" + str(read.key()))
        except HTTPBadRequest as e:
            self.return_bad_request(self.page_fields(current_reader, read, e))
Exemplo n.º 11
0
    def get(self):
        meters = {}
        public_reads = []

        for read in Read.gql("order by read_date desc limit 50"):
            meter = read.meter
            if not meter.is_public or str(meter.key()) in meters:
                continue
            meters[str(meter.key())] = meter
            public_reads.append(read)
            if len(public_reads) > 20:
                break

        fields = {'public_reads': public_reads}
        current_reader = self.find_current_reader()
        if current_reader is not None:
            reader_meters = Meter.gql(
                "where reader = :1", current_reader).fetch(10)
            fields['meters'] = reader_meters
            fields['candidate_customer_reads'] = [
                cand for cand in [
                    mtr.candidate_customer_read() for mtr in reader_meters]
                if cand is not None]
        self.return_ok(fields)
Exemplo n.º 12
0
 def get_unread_items_for_user(self, user):
     q = Item.select(Item.id).join(Feed).join(Subscription).join(User).where(
         (User.id == user.id), 
         ~(Item.id << Read.select(Read.item).where(User.id == user.id))).order_by(Item.id).distinct().naive()
     return [r.id for r in q]
Exemplo n.º 13
0
 def get_retry_read():
     """
     解析 JSON, 送去评分
     :return:
     """
     read_m = _r.rpop(MQ_READ_RETRY)
     if read_m:
         logging.debug("Get redis[%s] message:%s" % (MQ_READ_RETRY, read_m,))
         message = json.loads(read_m)
         wt = Read()
         wt.message = read_m
         wt.lesson_id = message.get('lessonId')
         wt.times = message.get('times')
         wt.read_id = message.get('readId')
         wt.user_id = message.get('userId')
         wt.homework_id = message.get('homeworkId')
         wt.lesson_report_guid = message.get('lessonReportGuid')
         wt.submission_time = message.get('submissionTime')
         wt.lesson_report_path = message.get('lessonReportPath')
         wt.sentences = message.get('sentences')
         wt.wav_path = message.get('audioPath')
         wt.language = message.get('language')
         return wt
     return None
Exemplo n.º 14
0
 def get(self):
     current_reader = self.require_current_reader()
     read_key = self.get_str("read_key")
     read = Read.get_read(read_key)
     self.return_ok(self.page_fields(current_reader, read))