Exemplo n.º 1
0
def recharge_doit():
    user_id = request.form['user_user']
    helper_id = request.form['helper_user']
    amount = request.form['amount']
    if not user_id or not helper_id or not amount:
        return 'Please enter valid data!'

    if amount == u"0":
        return "Invalid amount"

    if not uid_pattern.match(user_id):
        return "Invalid user id"
    if not uid_pattern.match(helper_id):
        return "Invalid helper id"

    users = Users.get_all(filters=['uidNumber=' + user_id])
    helpers = Users.get_all(filters=['uidNumber=' + helper_id])

    if not users:
        return "user %s not found" % user_id
    if not helpers:
        return "user %s not found" % helper_id
    user = users[0]
    helper = helpers[0]

    session = get_session()
    ev = RechargeEvent(user['id'], helper['id'], amount)

    session.add(ev)
    session.commit()

    return render_template('recharge_success.html', amount=amount, user=user)
Exemplo n.º 2
0
def login(type_user):
    data = request.get_json()
    try:
        schema = LoginSchema()
        schema.load(data=data)
    except ValidationError as error:
        return jsonify(error.messages), HTTPStatus.BAD_REQUEST
    user = Users(email=data['email'],
                 password=data['password'],
                 table=type_user)
    message, status = user.login()
    return jsonify({'message': message}), status
def send_low_balances(with_summary=True):
    session = get_session()

    if config.FORCE_MAIL_TO:
        send_low_balance(session, Users.get_by_id(config.FORCE_MAIL_TO), with_summary, force=True)
        return

    for user in Users.get_all():
        try:
            send_low_balance(session, user, with_summary)
        except Exception:
            logger.exception("while sending lowbalances:")
            continue
Exemplo n.º 4
0
def send_summaries():
    session = get_session()

    if config.FORCE_MAIL_TO:
        send_summary(session, Users.get_by_id(config.FORCE_MAIL_TO), "Getränkeübersicht", force=True)
        return

    for user in Users.get_all():
        try:
            send_summary(session, user, "Getränkeübersicht")
        except Exception:
            logging.exception("While sending summary for %s", user)
            continue
def send_summaries():
    session = get_session()

    if config.FORCE_MAIL_TO:
        send_summary(session, Users.get_by_id(config.FORCE_MAIL_TO), "Getränkeübersicht", force=True)
        return

    for user in Users.get_all():
        try:
            send_summary(session, user, "Getränkeübersicht")
        except Exception:
            logger.exception("While sending summary for %s", user)
            continue
Exemplo n.º 6
0
def send_low_balances(with_summary=True):
    session = get_session()

    if config.FORCE_MAIL_TO:
        send_low_balance(session, Users.get_by_id(config.FORCE_MAIL_TO), with_summary, force=True)
        return

    for user in Users.get_all():
        try:
            send_low_balance(session, user, with_summary)
        except Exception:
            logging.exception("while sending lowbalances:")
            continue
def send_low_balance(session, user, with_summary=False, force=False):
    if "email" not in user:
        return

    balance = Users.get_balance(user['id'])

    if not force and balance >= MINIMUM_BALANCE:
        # reset time
        user['meta']['last_emailed'] = time.time()
        Users.save(user)
        return

    last_emailed = user['meta'].get('last_emailed', 0)
    diff = time.time() - last_emailed
    diff_hours = diff / 60 / 60
    diff_days = diff_hours / 24

    if not force and diff_hours <= REMIND_MAIL_EVERY_X_HOURS:
        return

    logger.info("%s's low balance last emailed %.2f days (%.2f hours) ago. Mailing now.",
                user['name'], diff_days, diff_hours)
    content_text = (u"Du hast seit mehr als {diff_days} Tagen "
                    u"ein Guthaben von unter {minimum_balance}€!\n"
                    u"Aktueller Kontostand: {balance:.2f}€.\n"
                    u"Zum Aufladen im Space-Netz http://drinks-touch.fd/ besuchen.").format(
        diff_days=int(REMIND_MAIL_EVERY_X_HOURS / 24),
        minimum_balance=MINIMUM_BALANCE,
        balance=balance)
    content_html = render_jinja_html('low_balance.html',
                                     diff_days=REMIND_MAIL_EVERY_X_HOURS / 24,
                                     minimum_balance=MINIMUM_BALANCE,
                                     balance=balance,
                                     uid=user['id'])

    if not with_summary:
        content_text += FOOTER.format(uid=user['id'])
        content_html = render_jinja_html('main.html', prepend_html=content_html)

        send_notification(user['email'], "Negatives Guthaben", content_text, content_html, user['id'])
        return

    send_summary(session, user,
                 subject="Negatives Guthaben",
                 prepend_text=content_text,
                 prepend_html=content_html,
                 force=True)
    user['meta']['last_emailed'] = time.time()
    Users.save(user)
Exemplo n.º 8
0
    def __init__(self, screen, user, drink, text, session, **kwargs):
        super(SuccessScreen, self).__init__(screen)

        self.user = user

        self.objects.append(
            Label(self.screen, text='Danke,', pos=(30, 120), size=70))
        self.objects.append(
            Label(self.screen, text=user['name'] + "!", pos=(30, 170),
                  size=70))
        self.objects.append(
            Label(self.screen, text=text, size=45, pos=(30, 250)))

        self.objects.append(
            Label(self.screen, text='Verbleibendes Guthaben: ', pos=(30, 350)))
        self.objects.append(
            Label(
                self.screen,
                text=str(Users.get_balance(self.user['id'], session=session)) +
                ' EUR',
                pos=(50, 400)))

        self.objects.append(
            Button(self.screen,
                   text='OK',
                   pos=(50, 600),
                   size=50,
                   click=self.btn_home))

        self.progress = Progress(self.screen,
                                 pos=(400, 500),
                                 size=80,
                                 on_elapsed=self.home)
        self.objects.append(self.progress)
        self.progress.start()
        balance = Users.get_balance(user['id'])
        if balance >= 0:
            sound = "smb_coin.wav"
        elif balance < -10:
            sound = "alarm.wav"
        else:
            sound = "smb_bowserfalls.wav"
        os.system(
            "ssh -o StrictHostKeyChecking=no pi@pixelfun aplay sounds/%s >/dev/null 2>&1 &"
            % sound)

        if drink:
            send_drink(user, drink, True)
    def btn_euro(self, euro, param, pos):
        try:
            self.message.text = "Konto wird erzeugt..."
            self.progress.speed = 1 / 20.0
            self.progress.start()
            self.progress.on_elapsed = None
            self.progress.value = 0
            user = Users.create_temp_user()
            print "Created temp %s with EUR %d" % (user['id_card'], euro)
            self.progress.value = 0.2
            self.message.text = "Guthaben wird gespeichert..."
            self.aufladen(user, euro)

            barcode = user['id_card']

            self.message.text = "ID-Card wird generiert..."
            code_img = self.generate_barcode(euro, barcode)
            self.progress.value = 0.4
            self.message.text = "reticulating splines..."
            receipt_img = self.generate_receipt(euro, code_img)
            self.progress.value = 0.6
            self.message.text = "reloading fobblewobbles..."
            png = self.to_png(receipt_img)
            self.progress.value = 0.8
            self.message.text = "ID-Card wird gedruckt..."
            self.print_png(png)
            self.progress.on_elapsed = self.time_elapsed
            self.progress.stop()
            ScreenManager.get_instance().set_active(
                ProfileScreen(self.screen, user))
        except Exception as e:
            self.message.text = "Fehler: " + str(e)
            self.progress.value = 0
            self.progress.speed = 1 / 5.0
Exemplo n.º 10
0
    def btn_euro(self, euro):
        try:
            self.message.text = "Konto wird erzeugt..."
            self.progress.speed = 1 / 20.0
            self.progress.start()
            self.progress.on_elapsed = None
            self.progress.value = 0
            user = Users.create_temp_user()
            print("Created temp %s with EUR %d" % (user['id_card'], euro))
            self.progress.value = 0.2
            self.message.text = "Guthaben wird gespeichert..."
            self.aufladen(user, euro)

            barcode = user['id_card']

            self.message.text = "ID-Card wird generiert..."
            code_img = self.generate_barcode(barcode)
            self.progress.value = 0.4
            self.message.text = "reticulating splines..."
            receipt_img = self.generate_receipt(euro, code_img)
            self.progress.value = 0.6
            self.message.text = "reloading fobblewobbles..."
            png = self.to_png(receipt_img)
            self.progress.value = 0.8
            self.message.text = "ID-Card wird gedruckt..."
            self.print_png(png)
            self.progress.on_elapsed = self.time_elapsed
            self.progress.stop()
            ScreenManager.get_instance().set_active(
                ProfileScreen(self.screen, user)
            )
        except Exception as e:
            self.message.text = "Fehler: " + str(e)
            self.progress.value = 0
            self.progress.speed = 1 / 5.0
Exemplo n.º 11
0
 def on_barcode(self, barcode):
     if not barcode:
         return
     user = Users.get_by_id_card(barcode)
     if user:
         ScreenManager.get_instance().set_active(
             ProfileScreen(self.screen, user))
Exemplo n.º 12
0
def register(type_user):
    data = request.get_json()
    try:
        if type_user == 'provider':
            schema = ProvideRegisterSchema()
            schema.load(data=data)
        else:
            schema = ClientRegisterSchema()
            schema.load(data=data)
    except ValidationError as error:
        return jsonify(error.messages), HTTPStatus.BAD_REQUEST
    user = Users(email=data['email'],
                 password=data['password'],
                 table=type_user,
                 register_data=data['forms'])
    message, status = user.register()
    return jsonify({"message": message}), status
Exemplo n.º 13
0
def send_low_balance(session, user, with_summary=False, force=False):
    balance = Users.get_balance(user['id'])

    if not force and balance >= MINIMUM_BALANCE:
        # reset time
        user['meta']['last_emailed'] = time.time()
        Users.save(user)
        return

    last_emailed = user['meta'].get('last_emailed', 0)
    diff = time.time() - last_emailed
    diff_hours = diff / 60 / 60
    diff_days = diff_hours / 24

    if not force and diff_hours <= REMIND_MAIL_EVERY_X_HOURS:
        return

    logging.info("%s's low balance last emailed %.2f days (%.2f hours) ago. Mailing now.",
                 user['name'], diff_days, diff_hours)
    content_text = (u"Du hast seit mehr als {diff_days} Tagen "
                    u"ein Guthaben von unter {minimum_balance}€!\n"
                    u"Aktueller Kontostand: {balance:.2f}€.\n"
                    u"Zum Aufladen im Space-Netz http://drinks-touch.fd/ besuchen.").format(
        diff_days=REMIND_MAIL_EVERY_X_HOURS / 24,
        minimum_balance=MINIMUM_BALANCE,
        balance=balance)
    content_html = render_jinja_html('low_balance.html',
                                     diff_days=REMIND_MAIL_EVERY_X_HOURS / 24,
                                     minimum_balance=MINIMUM_BALANCE,
                                     balance=balance,
                                     uid=user['id'])

    if not with_summary:
        content_text += FOOTER.format(uid=user['id'])
        content_html = render_jinja_html('main.html', prepend_html=content_html)

        send_notification(user['email'], "Negatives Guthaben", content_text, content_html, user['id'])
        return

    send_summary(session, user,
                 subject="Negatives Guthaben",
                 prepend_text=content_text,
                 prepend_html=content_html,
                 force=True)
    user['meta']['last_emailed'] = time.time()
    Users.save(user)
Exemplo n.º 14
0
 def on_barcode(self, barcode):
     from .screen_manager import ScreenManager
     from .profile import ProfileScreen
     if not barcode:
         return
     user = Users.get_by_id_card(barcode)
     if user:
         ScreenManager.get_instance().set_active(
             ProfileScreen(self.screen, user))
Exemplo n.º 15
0
    def save_drink(self, args, pos):
        session = get_session()
        drink = DrinksManager.get_instance().get_selected_drink()
        if not drink:
            return
        ev = ScanEvent(
            drink['ean'],
            self.user['id'],
            datetime.datetime.now()
        )
        session.add(ev)
        session.commit()
        DrinksManager.get_instance().set_selected_drink(None)
        Users.delete_if_nomoney(self.user)

        screen_manager = ScreenManager.get_instance()
        screen_manager.set_active(SuccessScreen(self.screen, self.user, drink,
            "getrunken: %s" % drink['name'], session))
Exemplo n.º 16
0
 def setUpClass(cls) -> None:
     company_email = '*****@*****.**'
     email = '*****@*****.**'
     password = '******'
     data = {
         "response_name": "Name Test",
         "company_name": "Company Test LTDA",
         "phone": "11951236634",
         "cnpj": "1234567897897845"
     }
     cls.register_provider = Users(email=company_email,
                                   password=password,
                                   register_data=data,
                                   table='provider')
     cls.register_client = Users(email=email,
                                 password=password,
                                 register_data=data,
                                 table='client')
Exemplo n.º 17
0
 def render_aufladungen(self):
     aufladungen = Users.get_recharges(self.user['id'], limit=12)
     y = 210
     prev_date = None
     for i, aufladung in enumerate(aufladungen):
         x = 30
         if y + 45 * 2 >= self.btn_drinks.pos[1]:
             self.elements_aufladungen.append(Label(self.screen,
                 text="...",
                 pos=(x, y)
             ))
             break
         date = aufladung.timestamp.strftime("%a, %-d.%-m.%Y")
         time = aufladung.timestamp.strftime("%H:%M")
         text = time
         helper = aufladung.helper_user_id
         if helper:
             user = Users.get_by_id(aufladung.helper_user_id)
             if user:
                 helper = user['name']
             text += " mit " + helper
         if date != prev_date:
             prev_date = date
             self.elements_aufladungen.append(Label(self.screen,
                 text=date, size=35,
                 pos=(x, y + 15)
             ))
             y += 45
         count_width = 120
         margin_right = 10
         self.elements_aufladungen.append(Label(self.screen,
             text=text,
             pos=(x + 10, y), size=45,
             max_width=480 - x - margin_right - count_width
         ))
         self.elements_aufladungen.append(Label(
             self.screen,
             text=str(aufladung.amount),
             align_right=True,
             pos=(480 - margin_right, y - 5),
             max_width=count_width
         ))
         y += 35
Exemplo n.º 18
0
    def __init__(self, screen, char, **kwargs):
        super(NamesScreen, self).__init__(screen)

        self.char = char

        self.objects.append(
            Button(self.screen,
                   text="BACK",
                   pos=(30, 30),
                   click=self.back,
                   font=monospace,
                   size=30))

        self.timeout = Progress(
            self.screen,
            pos=(200, 50),
            speed=1 / 15.0,
            on_elapsed=self.time_elapsed,
        )
        self.objects.append(self.timeout)
        self.timeout.start()

        self.objects.append(
            Label(
                self.screen,
                text='Wer bist du?',
                pos=(20, 110),
            ))

        users = Users.get_all(self.char)

        btns_y = 7
        num_cols = int(math.ceil(len(users) / float(btns_y)))
        for i, user in enumerate(users):
            padding = 20
            xoff, yoff = 30, 190
            btn_ypos = 90
            i_y = i % btns_y
            i_x = i // btns_y
            x = i_x * (screen.get_width() / num_cols)
            y = i_y * btn_ypos
            self.objects.append(
                Button(self.screen,
                       text=user["name"],
                       pos=(xoff + x, y + yoff),
                       click=self.switch_to_screen,
                       click_param=user,
                       padding=padding))
            i += 1
Exemplo n.º 19
0
def recharge_doit():
    user_id = request.form['user_user']
    helper_id = request.form['helper_user']
    amount = request.form['amount']
    if not user_id or not helper_id or not amount:
        return 'Please enter valid data!'

    if amount == u"0":
        return "Invalid amount"

    if not uid_pattern.match(user_id):
        return "Invalid user id"
    if not uid_pattern.match(helper_id):
        return "Invalid helper id"

    users = Users.get_all(filters=['uidNumber=' + user_id])
    helpers = Users.get_all(filters=['uidNumber=' + helper_id])

    if not users:
        return "user %s not found" % user_id
    if not helpers:
        return "user %s not found" % helper_id
    user = users[0]
    helper = helpers[0]

    session = get_session()
    ev = RechargeEvent(
        user['id'],
        helper['id'],
        amount
    )

    session.add(ev)
    session.commit()

    return render_template('recharge_success.html', amount=amount, user=user)
Exemplo n.º 20
0
    def __init__(self, screen, **kwargs):
        super(MainScreen, self).__init__(screen)

        self.objects.append(Image(self.screen, pos=(30, 20)))

        self.objects.append(
            Label(self.screen,
                  text=u'member auswählen',
                  pos=(65, 250),
                  size=50))

        all_users = Users.get_all()
        i = 0
        for c in range(97, 97 + 26):
            text = str(chr(c))
            users = filter(lambda u: u["name"].lower().startswith(text),
                           all_users)
            if len(users) == 0:
                continue
            self.objects.append(
                Button(
                    self.screen,
                    text=text,
                    pos=self.__get_pos(i),
                    click=self.switch_to_screen,
                    click_param=text,
                    force_width=440 / 6,
                    force_height=440 / 6,
                ))

            i += 1

        self.objects.append(
            Button(
                self.screen,
                text='Abbrechen',
                pos=(150, 700),
                size=30,
                click=self.home,
            ))
        self.timeout = Progress(
            self.screen,
            pos=(380, 715),
            speed=1 / 15.0,
            on_elapsed=self.time_elapsed,
        )
        self.objects.append(self.timeout)
        self.timeout.start()
Exemplo n.º 21
0
 def on_barcode(self, barcode):
     if not barcode:
         return
     self.processing.is_visible = True
     user = Users.get_by_id_card(barcode)
     if user:
         ScreenManager.get_instance().set_active(
             ProfileScreen(self.screen, user))
         self.processing.is_visible = False
         return
     drink = get_by_ean(barcode)
     DrinksManager.get_instance().set_selected_drink(drink)
     self.barcode_label.text = drink['name']
     self.show_scanned_info(True)
     self.processing.is_visible = False
     self.timeout.start()
Exemplo n.º 22
0
def main():
    users = Users.get_all(include_temp=True)

    init_db()
    session = get_session()

    for user in users:
        ldapName = user["name"]
        ldapUser = LdapUser(ldapId=user["id"],
                            name=ldapName,
                            id_card=user["id_card"],
                            path=user["path"],
                            is_card=ldapName.startswith("geld"))

        session.add(ldapUser)

    session.commit()
Exemplo n.º 23
0
 def on_barcode(self, barcode):
     if not barcode:
         return
     self.processing.is_visible = True
     user = Users.get_by_id_card(barcode)
     if user:
         ScreenManager.get_instance().set_active(
             ProfileScreen(self.screen, user)
         )
         self.processing.is_visible = False
         return
     drink = get_by_ean(barcode)
     DrinksManager.get_instance().set_selected_drink(drink)
     self.barcode_label.text = drink['name']
     self.show_scanned_info(True)
     self.processing.is_visible = False
     self.timeout.start()
def main():
    users = list(Users.get_all(include_temp=True))

    init_db()
    session = get_session()

    for user in users:
        ldap_name = user["name"]
        ldap_user = LdapUser(
            ldap_id=user["id"],
            name=ldap_name,
            id_card=user["id_card"],
            path=user["path"],
            is_card=ldap_name.startswith("geld")
        )

        session.add(ldap_user)

    session.commit()
Exemplo n.º 25
0
def format_recharges(recharges):
    """

    :type recharges: list[RechargeEvent]
    """
    recharges_fmt = "\nAufladungen:\n" \
                    "    #                 datum     mit aufgeladen\n"

    for i, event in enumerate(recharges):
        date = event.timestamp.strftime("%F %T Z")
        mit = event.helper_user_id

        try:
            mit = Users.get_by_id(mit)['name']
        except Exception:
            pass

        amount = event.amount
        recharges_fmt += "  % 3d % 15s %7s %10s\n" % (i, date, mit, amount)

    return recharges_fmt
Exemplo n.º 26
0
def format_recharges(recharges):
    """

    :type recharges: list[RechargeEvent]
    """
    recharges_fmt = "\nAufladungen:\n" \
                    "    #                 datum     mit aufgeladen\n"

    for i, event in enumerate(recharges):
        date = event.timestamp.strftime("%F %T Z")
        mit = event.helper_user_id

        try:
            mit = Users.get_by_id(mit)['name']
        except Exception:
            pass

        amount = event.amount
        recharges_fmt += "  % 3d % 15s %7s %10s\n" % (i, date, mit, amount)

    return recharges_fmt
Exemplo n.º 27
0
 def on_barcode(self, barcode):
     if not barcode:
         return
     self.processing.is_visible = True
     user = Users.get_by_id_card(barcode)
     if user:
         ScreenManager.get_instance().set_active(
             ProfileScreen(self.screen, user)
         )
         self.processing.is_visible = False
         return
     drink = get_by_ean(barcode)
     DrinksManager.get_instance().set_selected_drink(drink)
     self.drink_info.text = drink['name']
     if self.zuordnen not in self.objects:
         self.objects.extend([self.zuordnen, self.drink_info])
     if self.btn_aufladungen in self.objects:
         self.objects.remove(self.btn_aufladungen)
     if self.btn_drinks in self.objects:
         self.objects.remove(self.btn_drinks)
     self.processing.is_visible = False
     self.timeout.start()
Exemplo n.º 28
0
    def __init__(self, screen, user, drink, text, session):
        super(SuccessScreen, self).__init__(screen)

        self.user = user

        self.objects.append(Label(
            self.screen,
            text='Danke,',
            pos=(30, 120),
            size=70
        ))
        self.objects.append(Label(
            self.screen,
            text=user['name'] + "!",
            pos=(30, 170),
            size=70
        ))
        self.objects.append(Label(
            self.screen,
            text=text,
            size=45,
            pos=(30, 250)
        ))

        self.objects.append(Label(
            self.screen,
            text='Verbleibendes Guthaben: ',
            pos=(30, 350)
        ))
        self.objects.append(Label(
            self.screen,
            text=str(Users.get_balance(self.user['id'], session=session)) + ' EUR',
            pos=(50, 400)
        ))

        self.objects.append(Button(
            self.screen,
            text='OK',
            pos=(50, 600),
            size=50,
            click_func=self.btn_home
        ))

        self.progress = Progress(
            self.screen,
            pos=(400, 500),
            size=80,
            on_elapsed=self.home
        )
        self.objects.append(self.progress)
        self.progress.start()
        balance = Users.get_balance(user['id'])
        if balance >= 0:
            sound = "smb_coin.wav"
        elif balance < -10:
            sound = "alarm.wav"
        else:
            sound = "smb_bowserfalls.wav"
        os.system("ssh -o StrictHostKeyChecking=no pi@pixelfun aplay sounds/%s >/dev/null 2>&1 &" % sound)

        if drink:
            send_drink(user, drink, True)
 def set_id(self, ean):
     ean = ean.upper() if ean else ean
     self.user['id_card'] = ean
     Users.save(self.user)
     self.id_label.text = self.user['id_card']
Exemplo n.º 30
0
def send_summary(session, user, subject, prepend_text=None, prepend_html=None, force=False):
    if 'email' not in user:
        return

    frequency_str = user['meta']['drink_notification']
    balance = Users.get_balance(user['id'])

    if not force and frequency_str not in FREQUENCIES.keys():
        return
    elif force:
        freq_secs = 0
    else:
        freq_secs = FREQUENCIES[frequency_str]

    last_emailed = user['meta']['last_drink_notification']
    if type(last_emailed) not in [int, float]:
        last_emailed = 0

    last_emailed_str = datetime.fromtimestamp(last_emailed).strftime("%d.%m.%Y %H:%M:%S")
    diff = time.time() - last_emailed
    diff_hours = diff / 60 / 60
    diff_days = diff_hours / 24

    if force:
        logger.info("Forcing mail.")
    else:
        if diff <= freq_secs:
            return

    logger.info("%s's summary last emailed %.2f days (%.2f hours) ago. Mailing now.",
                user['name'], diff_days, diff_hours)

    content_text = u""

    if prepend_text:
        content_text += prepend_text + u"\n==========\n"

    content_text += u"Hier ist deine Getränkeübersicht seit {since}.\n" \
                    u"Dein aktuelles Guthaben beträgt EUR {balance:.2f}.\n" \
        .format(since=last_emailed_str, balance=balance)

    drinks_consumed = get_drinks_consumed(session, user, last_emailed)
    recharges = get_recharges(session, user, last_emailed)

    if drinks_consumed:
        content_text += format_drinks(drinks_consumed)

    if recharges:
        content_text += format_recharges(recharges)

    content_text += FOOTER.format(uid=user['id'])
    content_html = render_jinja_html('main.html',
                                     with_report=True,
                                     balance=balance,
                                     since_text=last_emailed_str,
                                     drinks=drinks_consumed,
                                     recharges=recharges,
                                     prepend_html=prepend_html,
                                     limit_days=REMIND_MAIL_EVERY_X_HOURS / 24,
                                     minimum_balance=MINIMUM_BALANCE,
                                     uid=user['id'])

    email = user['email']

    if not email:
        logger.warning("User %s has no email. skipping.", user)
        return

    if len(drinks_consumed) == 0 and len(recharges) == 0 and not force:
        logger.debug("got no rows. skipping.")
        return

    logger.info("Got %d drinks and %d recharges. Mailing.", len(drinks_consumed), len(recharges))
    send_notification(email, subject, content_text, content_html, user['id'])
    user['meta']['last_drink_notification'] = time.time()
    Users.save(user)
Exemplo n.º 31
0
 def users(self):
     if not self._users:
         self._users = Users()
     return self._users
def main():
    for user in Users.get_all():
        user['meta']['last_emailed'] = 0
        user['meta']['last_drink_notification'] = 0
        Users.save(user)
Exemplo n.º 33
0
def send_summary(session, user, subject, prepend_text=None, prepend_html=None, force=False):
    frequency_str = user['meta']['drink_notification']
    balance = Users.get_balance(user['id'])

    if not force and frequency_str not in FREQUENCIES.keys():
        return
    elif force:
        freq_secs = 0
    else:
        freq_secs = FREQUENCIES[frequency_str]

    last_emailed = user['meta']['last_drink_notification']
    if type(last_emailed) not in [int, float]:
        last_emailed = 0

    last_emailed_str = datetime.fromtimestamp(last_emailed).strftime("%d.%m.%Y %H:%M:%S")
    diff = time.time() - last_emailed
    diff_hours = diff / 60 / 60
    diff_days = diff_hours / 24

    if force:
        logging.info("Forcing mail.")
    else:
        if diff <= freq_secs:
            return

    logging.info("%s's summary last emailed %.2f days (%.2f hours) ago. Mailing now.",
                 user['name'], diff_days, diff_hours)

    content_text = u""

    if prepend_text:
        content_text += prepend_text + u"\n==========\n"

    content_text += u"Hier ist deine Getränkeübersicht seit {since}.\n" \
                    u"Dein aktuelles Guthaben beträgt EUR {balance:.2f}.\n" \
        .format(since=last_emailed_str, balance=balance)

    drinks_consumed = get_drinks_consumed(session, user, last_emailed)
    recharges = get_recharges(session, user, last_emailed)

    if drinks_consumed:
        content_text += format_drinks(drinks_consumed)

    if recharges:
        content_text += format_recharges(recharges)

    content_text += FOOTER.format(uid=user['id'])
    content_html = render_jinja_html('main.html',
                                     with_report=True,
                                     balance=balance,
                                     since_text=last_emailed_str,
                                     drinks=drinks_consumed,
                                     recharges=recharges,
                                     prepend_html=prepend_html,
                                     limit_days=REMIND_MAIL_EVERY_X_HOURS / 24,
                                     minimum_balance=MINIMUM_BALANCE,
                                     uid=user['id'])

    email = user['email']

    if not email:
        logging.warn("User %s has no email. skipping.", user)
        return

    if len(drinks_consumed) == 0 and len(recharges) == 0 and not force:
        logging.debug("got no rows. skipping.")
        return

    logging.info("Got %d drinks and %d recharges. Mailing.", len(drinks_consumed), len(recharges))
    send_notification(email, subject, content_text, content_html, user['id'])
    user['meta']['last_drink_notification'] = time.time()
    Users.save(user)
Exemplo n.º 34
0
    def __init__(self, screen, user, **kwargs):
        super(ProfileScreen, self).__init__(screen)

        self.user = user

        self.objects.append(Button(
            self.screen,
            text = "BACK",
            pos=(30,30),
            font = monospace,
            click=self.back
        ))

        self.objects.append(Button(
            self.screen,
            text = "ID card",
            pos=(340,30),
            font = monospace,
            click=self.id_card
        ))

        self.objects.append(Label(
            self.screen,
            text =self.user["name"],
            pos=(30, 120),
            size=70,
            max_width=335 - 30 - 10,  # balance.x - self.x - margin
        ))

        self.objects.append(Label(
            self.screen,
            text = 'Guthaben',
            pos=(330, 120),
            size=30
        ))

        self.label_verbrauch = Label(
            self.screen,
            text='Bisheriger Verbrauch:',
            pos=(30, 180),
            size=30
        )
        self.label_aufladungen = Label(
            self.screen,
            text='Aufladungen:',
            pos=(30, 180),
            size=30
        )

        self.processing = Label(
            self.screen,
            text="Moment bitte...",
            size=40,
            pos=(150, 750)
        )
        self.processing.is_visible = False
        self.objects.append(self.processing)

        self.timeout = Progress(
            self.screen,
            pos=(200, 50),
            speed=1/30.0,
            on_elapsed=self.time_elapsed,
            click=self.btn_home,
        )
        self.objects.append(self.timeout)
        self.timeout.start()

        drink = DrinksManager.get_instance().get_selected_drink()
        self.drink_info = Label(
            self.screen,
            text=drink['name'] if drink else "",
            size=60,
            pos=(30, 630)
        )

        self.zuordnen = Button(
            self.screen,
            text='Trinken',
            pos=(30, 690),
            size=50,
            click=self.save_drink
        )
        self.btn_aufladungen = Button(
            self.screen,
            text='Aufladungen',
            pos=(30, 700),
            click=self.show_aufladungen
        )
        self.btn_drinks = Button(
            self.screen,
            text='Buchungen',
            pos=(20, 700),
            click=self.show_drinks
        )
        self.btn_abbrechen = Button(
            self.screen,
            text='Abbrechen',
            pos=(290, 700),
            size=30,
            click=self.btn_home,
        )
        self.btn_aufladen = Button(
            self.screen,
            text='Jetzt Aufladen',
            pos=(210, 700),
            size=30,
            click=self.recharge,
        )

        self.elements_aufladungen = [self.btn_drinks, self.label_aufladungen,
            self.btn_aufladen]
        self.elements_drinks = [self.label_verbrauch, self.btn_abbrechen]
        if drink:
            self.elements_drinks.extend([self.zuordnen, self.drink_info])
        else:
            self.elements_drinks.append(self.btn_aufladungen)


        balance = Users.get_balance(self.user['id'])
        self.objects.append(Label(
            self.screen,
            text = str(balance),
            pos=(335, 145),
            size=40
        ))

        drinks = self.get_stats()
        for i, drinks in enumerate(drinks):
            x = 30
            if i == 11:
                self.elements_drinks.append(Label(
                    self.screen,
                    text = "...",
                    pos=(x, 210 + (i * 35))
                ))
                continue
            if i > 11:
                continue
            text = get_by_ean(drinks["name"])['name']
            count_width = 80
            margin_right = 10
            self.elements_drinks.append(Label(
                self.screen,
                text = text,
                pos=(x, 210 + (i * 35)),
                max_width=480-x-margin_right-count_width
            ))
            self.elements_drinks.append(Label(
                self.screen,
                text = str(drinks["count"]),
                align_right=True,
                pos=(480-margin_right, 210 + (i * 35)),
                max_width=count_width
            ))

        self.objects.extend(self.elements_drinks)

        self.render_aufladungen()
Exemplo n.º 35
0
import pickle

import pandas as pd
from tqdm import tqdm
from gensim import corpora
from gensim.models import TfidfModel
import gensim
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import csv

from constants import ROOT_PATH
from users.users import Users

users = Users()

dictionary_path = ROOT_PATH + 'bag_of_words/dictionary.dict'
dictionary = gensim.corpora.Dictionary.load(dictionary_path)

comment_id_to_position_corpus = pickle.load(
    open(
        ROOT_PATH +
        f'training_data/comment_id_to_position_{len(dictionary)}_words_dict.p',
        "rb"))

corpus_path = ROOT_PATH + 'bag_of_words/corpus.mm'
corpus = corpora.MmCorpus(corpus_path)

tfidf_model = TfidfModel.load(ROOT_PATH + 'bag_of_words/tfidf.model')

n_items = len(dictionary)
Exemplo n.º 36
0
 def set_id(self, ean):
     ean = ean.upper() if ean else ean
     self.user['id_card'] = ean
     Users.save(self.user)
     self.id_label.text = self.user['id_card']
Exemplo n.º 37
0
def index():
    users = sorted(Users.get_all(), key=lambda u: u['name'].lower())
    users.insert(0, {})
    print(users)
    return render_template('index.html', users=users)
Exemplo n.º 38
0
                                  backend=True))
elif os.path.exists(config_file):
    with open(config_file) as f:
        config = yaml.load(f, Loader=yaml.SafeLoader)
        config['schema'] = yamale.make_schema(content=config['schema'],
                                              validators=get_validators(
                                                  config['config'],
                                                  config['approvedApis']))

api.add_namespace(Info.get_namespace(config), path='/api/v1/info')
api.add_namespace(Environments.get_namespace(config),
                  path='/api/v1/environments')
api.add_namespace(Teams.get_namespace(config), path='/api/v1/teams')
api.add_namespace(Folders.get_namespace(config), path='/api/v1/folders')
api.add_namespace(Apis.get_namespace(config), path='/api/v1/apis')
api.add_namespace(Users.get_namespace(config), path='/api/v1/users')
api.add_namespace(Groups.get_namespace(config), path='/api/v1/groups')
api.add_namespace(Projects.get_namespace(config), path='/api/v1/projects')
api.add_namespace(Repositories.get_namespace(config),
                  path='/api/v1/repositories')
api.add_namespace(ChargingCodes.get_namespace(config),
                  path='/api/v1/chargingcodes')
api.add_namespace(Cms.get_namespace(config), path='/api/v1/cms')

api.init_app(app)


def handle_frontend():
    requested_path = request.path[1:len(request.path)]
    if requested_path == '':
        requested_path = 'index.html'
Exemplo n.º 39
0
def index():
    users = sorted(Users.get_all(), key=lambda u: u['name'].lower())
    users.insert(0, {})
    print(users)
    return render_template('index.html', users=users)
Exemplo n.º 40
0
def main(args):
    for user in Users.get_all():
        user['meta']['last_emailed'] = 0
        user['meta']['last_drink_notification'] = 0
        Users.save(user)