Example #1
0
    def join_program(bot, update):
        """ Add new user to program as referraler

        :param bot: bot
        :type bot: telegram.Bot
        :param update: update event
        :type update: relegram.Update
        """
        _, channel_id, channel_name = update.callback_query.data.split(':')
        username = update.effective_user.username
        user_id = update.effective_user.id

        if not db_session.query(Inviter.inviter_id).filter_by(
                inviter_id=user_id).scalar():
            logger.debug('Adding inviter <{0}> to DB'.format(user_id))
            inviter = Inviter(user_id, username, update.effective_user.first_name, update.effective_user.last_name)
            db_session.add(inviter)

        q = db_session.query(ChannelInviter).filter_by(inviter_id=user_id,
                                                       channel_id=channel_id)
        if not db_session.query(q.exists()).scalar():
            logger.info('Adding assoc SI <{0}:{1}> to DB'
                        .format(user_id, channel_id))
            association = ChannelInviter(user_id, channel_id)
            db_session.add(association)

        db_session.commit()
        update.callback_query.answer()
Example #2
0
 def getJsToken(cls):
     '''
     从数据库中取
        有  直接返回
        没有  调用wxapi接口从微信服务器获取 ,并保存到数据库
     '''
     dt = int(time.time()) * 1000 - 110 * 60 * 1000
     tokenTemp = db_session.query(TokenTemp).filter(
         TokenTemp.name == 'js_token',
         TokenTemp.update_time > str(dt)).first()
     js_token = ''
     if tokenTemp != None:
         js_token = tokenTemp.token
     else:
         access_token = cls.getAccessToken()
         js_token = WeixinHelper.getJsapiTicket(access_token)
         # 更新到数据库
         db_session.query(TokenTemp).filter(
             TokenTemp.name == 'js_token').update({
                 'token':
                 access_token,
                 'update_time':
                 str(int(time.time()) * 1000)
             })
         db_session.commit()
     return js_token
Example #3
0
    def getAccessToken(cls):
        '''
        从数据库中取
           有  直接返回
           没有  调用wxapi接口从微信服务器获取,并保存到数据库
        '''
        # 获取当前时间戳 单位:秒
        dt = int(time.time()) * 1000 - 110 * 60 * 1000
        tokenTemp = db_session.query(TokenTemp).filter(
            TokenTemp.name == 'access_token',
            TokenTemp.update_time > str(dt)).first()
        if tokenTemp != None:
            access_token = tokenTemp.token
        else:
            accessTokenObj = WeixinHelper.getAccessToken()
            access_token = accessTokenObj['access_token']
            # 更新到数据库
            db_session.query(TokenTemp).filter(
                TokenTemp.name == 'access_token').update({
                    'token':
                    access_token,
                    'update_time':
                    str(int(time.time()) * 1000)
                })
            db_session.commit()

        return access_token
Example #4
0
    def list_statistics(bot, update):
        """ Send or edit last message with channels for statistics purpose

        :param bot: bot
        :type bot: telegram.Bot
        :param update: update event
        :type update: relegram.Update
        """
        logger.debug('<user:{0}>: request for statistics'.format(
            update.effective_user.id))
        user_id = update.effective_user.id
        channels = db_session.query(Channel).filter_by(admin_id=user_id)
        if not db_session.query(channels.exists()).scalar():
            logger.debug('<user:{0}> no channels available for stat'.format(
                update.effective_user.id))
            return send_response(bot, update, Messages.NO_REFERRAL_CHANNELS)

        buttons = [
            InlineKeyboardButton(channel.username,
                                 callback_data='{0}:{1}:{2}'.format(
                                     Commands.STATISTICS, channel.channel_id,
                                     channel.username)) for channel in channels
        ]

        return send_response(bot, update, get_user_sattistics_text(channels),
                             create_inline_keyboard(buttons, width=3))
Example #5
0
 def getAccessTokenByCode(cls):
     '''
     从数据库中取
        有  直接返回
        没有  调用wxapi接口从微信服务器获取 ,并保存到数据库
     '''
     dt = int(time.time()) * 1000 - 110 * 60 * 1000
     tokenTemp = db_session.query(TokenTemp).filter(
         TokenTemp.name == 'flush_token',
         TokenTemp.update_time > str(dt)).first()
     flush_token = ''
     if tokenTemp != None:
         flush_token = tokenTemp.token
     else:
         access_token = cls.getAccessToken()
         flushTokenObj = WeixinHelper.getAccessTokenByCode(access_token)
         if 'access_token' in flushTokenObj:
             flush_token = flushTokenObj['access_token']
             flushTokenObj = WeixinHelper.refreshAccessToken(flush_token)
             if 'access_token' in flushTokenObj:
                 flush_token = flushTokenObj['access_token']
                 # 更新到数据库
                 db_session.query(TokenTemp).filter(
                     TokenTemp.name == 'flush_token').update({
                         'token':
                         flush_token,
                         'update_time':
                         str(int(time.time()) * 1000)
                     })
                 db_session.commit()
     return flush_token
Example #6
0
def show_items(category_id):
    if 'username' in login_session:
        username = login_session["username"]
    else:
        username = None
    category = db_session.query(Category).filter_by(id=category_id).one()
    items = db_session.query(CategoryItem).filter_by(
        category_id=category_id).all()
    with store_context(local_storage):
        if username is not None and \
                category.user_id == login_session['user_id']:
            return render_template('owner_items.html',
                                   items=items,
                                   category=category,
                                   username=username,
                                   categories=db_session.
                                   query(Category).
                                   order_by(asc(Category.name)))
        else:
            return render_template('items.html',
                                   items=items,
                                   category=category,
                                   username=username,
                                   categories=db_session.
                                   query(Category).
                                   order_by(asc(Category.name)))
Example #7
0
def new_item(category_id):
    if 'username' not in login_session:
        return redirect('/login')
    category = db_session.query(Category).filter_by(id=category_id).one()
    all_categories = db_session.query(Category).order_by(asc(Category.name))
    if request.method == 'POST':
        try:
                photo = request.files.get('photo')
                new_item = CategoryItem(name=request.form['name'],
                                        description=request.
                                        form['description'],
                                        category_id=category_id)
                with store_context(local_storage):
                    new_item.picture.from_file(photo)
                    new_item.picture.generate_thumbnail(width=300)
                    db_session.add(new_item)
                    db_session.commit()
        except:
            flash("Item creation failed")
            return redirect(url_for('show_items',
                                    category_id=category_id,
                                    categories=all_categories))
        flash('New %s Item Successfully Created' % (new_item.name))
        return redirect(url_for('show_items',
                                category_id=category_id,
                                categories=all_categories))
    else:
        return render_template('new_item.html',
                               category_id=category_id,
                               categories=all_categories)
Example #8
0
    def list_managment(bot, update):
        """ Send or edit last message with channels list for managment purpose

        :param bot: bot
        :type bot: telegram.Bot
        :param update: update event
        :type update: relegram.Update
        """
        user_id = update.effective_user.id
        channels = db_session.query(Channel).filter_by(admin_id=user_id)
        if not db_session.query(channels.exists()).scalar():
            logger.info(
                'User <{0}> has no channels for managment'.format(user_id))
            return send_response(bot, update, Messages.NO_REFERRAL_CHANNELS)

        buttons = [
            Buttons.get_button(Commands.MANAGMENT,
                               label=channel.username,
                               channel_id=channel.channel_id,
                               channel_name=channel.username)
            for channel in channels
        ]
        keyboard = create_inline_keyboard(buttons, width=3)
        return send_response(bot, update, Messages.SELECT_CHANNEL_TO_MANAGE,
                             keyboard)
Example #9
0
def get_category_data():
    categories = db_session.query(Category).all()
    json_dict_list = [r.serialize for r in categories]
    for index, data in enumerate(json_dict_list):
        items = db_session.query(CategoryItem) \
            .filter_by(category_id=json_dict_list[index]['id']).all()
        json_dict_list[index]['category_items'] = [i.serialize for i in items]
    return json_dict_list
Example #10
0
def deleteById(object, item_id):
    try:
        db_session.query(type(object)).filter_by(id=item_id).delete()
        db_session.commit()
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Example #11
0
def updatedata(data, model):
    try:
        db_session.query(model).filter(model.id == 1).update(data)
        db_session.commit()
        flash("information updated successfully", "success")
    except exc.SQLAlchemyError as e:
        print(e)
        db_session.rollback()
        flash('there was an error committing your data.', 'danger')
Example #12
0
def databaseOperations(subject):
    targetsearch = Pynionquery.query.filter_by(searchword = subject).first()
    if (targetsearch):
        print("found and updating")
        db_session.query(Pynionquery).filter(Pynionquery.searchword == subject).update({Pynionquery.count: Pynionquery.count+1})
    else:
        print("db file initialised....")
        pynionquery = Pynionquery(subject)
        db_session.add(pynionquery)
    db_session.commit()
Example #13
0
def show_categories():
    categories = db_session.query(Category).order_by(asc(Category.name))
    items = db_session.query(CategoryItem).order_by(desc(CategoryItem.added))
    if 'username' in login_session:
        username = login_session["username"]
    else:
        username = None
    return render_template('categories.html', categories=categories,
                           items=items,
                           username=username)
Example #14
0
def query(model_column, model_filter=None, filter_by=None):
    """
    model_column: model.column column you want to query
    model_filter: model.filter coulumn you want to filter, defaults to None
    filter_by: value you want to filter by, defaults to None
    """
    if model_filter:
        return db_session.query(model_column).filter(
            model_filter == filter_by).one()[0]
    else:
        return db_session.query(model_column).one()[0]
Example #15
0
def update_social_media(data):
    try:
        for i, k in enumerate(data, start=1):
            db_session.query(SocialMedia).filter(SocialMedia.site_id == i). \
                update({'site_link': data[k]})
        db_session.commit()
        flash('Restaurant social media accounts committed successfully .',
              'success')
    except exc.SQLAlchemyError:
        db_session.rollback()
        flash('there was an error committing your data.', 'danger')
Example #16
0
def get_account_balance(account_number):
    credit = db_session.query(func.sum(Transaction.amount)) \
        .filter(and_(Transaction.account_number == account_number,
                     Transaction.transaction_type == Transaction.get_credit_type())) \
        .one()[0]

    debit = db_session.query(func.sum(Transaction.amount)) \
        .filter(and_(Transaction.account_number == account_number,
                     Transaction.transaction_type == Transaction.get_debit_type())) \
        .one()[0]

    return (0 if credit is None else credit) - (0 if debit is None else debit)
Example #17
0
 def scrape_disclosures(self, target_id=None):
     """ """
     pool = Pool(processes=10)
     iterator = db_session.query(Filer.filer_id)
     if target_id is not None:
         iterator = db_session.query(
             Filer.filer_id).filter(Filer.filer_id == target_id)
     for row in iterator:
         filer_id = row[0]
         for f_year in range(FIRST_YEAR, LAST_YEAR + 1):
             pool.apply_async(self.scrape_disclosure,
                              args=(filer_id, f_year))
     self.logger.info('Scraped %d new records.', self.record_counter)
Example #18
0
def single_item(category_id, item_id):
    # confirm item exists
    item = db_session.query(CategoryItem).filter_by(id=item_id).one()
    category = db_session.query(Category).filter_by(id=category_id).one()
    if 'username' in login_session:
        username = login_session["username"]
    else:
        username = None
    with store_context(local_storage):
        return render_template('single_item.html',
                               category_id=category_id,
                               item=item,
                               categories=db_session.
                               query(Category).order_by(asc(Category.name)),
                               username=username)
Example #19
0
def delete_item(category_id, item_id):
    if 'username' not in login_session:
        return redirect('/login')
    db_session.query(Category).filter_by(id=category_id).one()
    delete_me = db_session.query(CategoryItem).filter_by(id=item_id).one()
    all_categories = db_session.query(Category).order_by(asc(Category.name))
    if request.method == 'POST':
        with store_context(local_storage):
            db_session.delete(delete_me)
            db_session.commit()
            flash('item Item Successfully Deleted')
            return redirect(url_for('show_items',
                                    category_id=category_id,
                                    categories=all_categories))
    else:
        return render_template('delete_item.html', item=delete_me)
Example #20
0
def get_payment(payment_id):
    """ Get payment information
    """
    payment = db_session.query(Payment).get(payment_id)
    if payment:
        return payment, 200
    abort(404)
Example #21
0
def delete_category(category_id):
    if 'username' not in login_session:
        return redirect('/login')
    delete_me = db_session.query(
        Category).filter_by(id=category_id).one()
    if delete_me.user_id != login_session['user_id']:
        return """<script>function myFunction() {
            alert('You are not authorized to edit this category.
            Please create your own category in order to edit.');
            } </script><body onload='myFunction()''>"""
    if request.method == 'POST':
        with store_context(local_storage):
            db_session.delete(delete_me)
            flash('%s Successfully Deleted' % delete_me.name)
            db_session.commit()
            return redirect(url_for('show_categories',
                            category_id=category_id,
                            username=login_session["username"],
                            categories=db_session.
                            query(Category).order_by(asc(Category.name))))
    else:
        return render_template('delete_category.html',
                               category=delete_me,
                               username=login_session["username"],
                               categories=db_session.
                               query(Category).order_by(asc(Category.name)))
Example #22
0
def calendar_washing():
    wperson = models.Person.query.filter_by(id=current_user.person_id).first()
    if wperson:
        hostel = db_session.query(
            models.Hostel).filter(models.Room.id == wperson.room).filter(
                models.Hostel.id == models.Room.hostel_id).first().id
        washing = models.Washing.query.filter_by(hostel=hostel).all()
    else:
        hostel = None
        washing = models.Washing.query.all()

    data = []

    if washing:
        for wash in washing:
            data.append({
                'id': wash.id,
                'name': wash.person,
                'location': wash.hostel,
                'startDate': wash.start.strftime('%m/%d/%Y'),
                'endDate': wash.end.strftime('%m/%d/%Y')
            })

    return render_template('calendar_washing.html',
                           data=data,
                           wperson=wperson,
                           hostel=hostel)
Example #23
0
def create_notification(payment_id):
    """ Notify about payment status
    """
    payment = db_session.query(Payment).get(payment_id)
    if not payment:
        abort(404)

    if not request.json or 'notification_url' not in request.json:
        logger.debug(
            'Not enough data to create notification! Request data: {0}'.format(
                request.json))
        abort(400)

    if payment.status in [
            PaymentStatus.timeout, PaymentStatus.success, PaymentStatus.refused
    ]:
        logger.debug('Payment has already finished')
        return jsonify({'error': 'Payment has already finished'}), 400

    user_data = request.json.get('user_data', {})
    notification = Notification(payment.payment_id,
                                request.json.get('notification_url'),
                                user_data)
    payment.notifications.append(notification)
    db_session.add(payment)
    db_session.commit()
    return jsonify({'id': notification.notification_id}), 201
Example #24
0
def getById(type, id):
    try:
        o = db_session.query(type).filter_by(id=object.id)
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Example #25
0
def createUser(login_session):
    newUser = User(name=login_session['username'], email=login_session[
                   'email'], picture=login_session['picture'])
    db_session.add(newUser)
    db_session.commit()
    user = db_session.query(User).filter_by(email=login_session['email']).one()
    return user.id
Example #26
0
def login():
    form = LogInForm()
    if request.method == 'POST' and form.validate():
        user_name = form.user_name.data
        password = form.password.data

        # user name exist in db and its password is valid
        user = db_session.query(Employee).filter_by(employee_username=user_name).first()
        if user is not None and user.is_correct_password(password) and user.employee_status == 'active':
            # user is owner -> transmit to owner panel
            if user.employee_id == 1:
                session['owner_logged_in'] = True
                session['owner_username'] = user.employee_username
                return render_template('owner_restaurant.html',
                                       base_form=RestaurantBaseForm(),
                                       opening_form=RestaurantOpeningHoursForm(),
                                       media_form=RestaurantSocialMediaForm(),
                                       owner_username=session['owner_username'])
            # user is employee -> transmit to progressive panel
            else:
                session['employee_logged_in'] = True
                session['employee_username'] = user.employee_username
                return redirect(url_for('staff.all_orders'))
    elif session.get('owner_logged_in'):
        return render_template('owner_restaurant.html',
                               base_form=RestaurantBaseForm(),
                               opening_form=RestaurantOpeningHoursForm(),
                               media_form=RestaurantSocialMediaForm(),
                               owner_username=session['owner_username'])
    elif session.get('employee_logged_in'):
        return redirect(url_for('staff.all_orders'))
    return render_template('log_in.html',
                           form=form)
Example #27
0
def get_last_emp_id():
    try:
        emp_id_row = db_session.query(func.max(Employee.emp_id).label("max_emp_id")) \
            .one()[0]
    except NoResultFound:
        emp_id_row = None
    return emp_id_row
Example #28
0
 def get(self, id):
     #obj = self.main_model.query.get(id)
     obj = db_session.query(self.main_model).get(id)
     db_session.delete(obj)
     db_session.commit()
     flash(u'%s deleted' % self.main_model.__name__)
     return redirect(url_for(self.default_route))
Example #29
0
 def decorated_function(*args, **kwargs):
     g.user = None
     if 'user_id' in session:
         g.user = db_session.query(User).get(session['user_id'])
     if g.user is None:
         flash(u'You must login to proceed')
         return redirect(url_for('user.login'))
     return f(*args, **kwargs)
Example #30
0
 def __call__(self, form, field):
     check = db_session.query(self.model).filter(self.field == field.data).first()
     if 'id' in form:
         id = form.id.data
     else:
         id = None
     if check and (id is None or id != check.id):
         raise ValidationError(self.message)
Example #31
0
def query_email(email):
    try:
        r = db_session.query(User).filter_by(email =email).all()
    except:
        db_session.rollback()
        r = None
    db_session.close()
    return r
Example #32
0
def modify_menu_item(order_id, status):
    on_success = jsonify({'success': True}), 200, {
        'ContentType': 'application/json'
    }

    # the commented code below is used for sending confirmation and rejection/missed emails to the customers,
    # I commented them because they were taking a whole lot of time to perform, according to that the database was
    # missing/rejecting/confirming order on its own
    # customer = db_session.query(Customers).filter(Customers.customer_id == Orders.customer_id).first()
    # restaurant_name = query(model_column=RestaurantBaseInformation.restaurant_name)
    # preparing_time = query(model_column=OrdersTiming.preparing_time)
    if status == 'missed':
        db_session.query(Orders).filter(
            Orders.order_id == int(order_id)).update({
                "status":
                status,
                "datetime_confirmed":
                datetime.datetime.now()
            })
        db_session.commit()
        # confirm_customer(customer.customer_name, customer.customer_email, order_id, restaurant_name, 'missed',preparing_time)
        return on_success
    elif status == 'in_progress':
        db_session.query(Orders).filter(
            Orders.order_id == int(order_id)).update({
                "status":
                status,
                "datetime_confirmed":
                datetime.datetime.now()
            })
        db_session.commit()
        # confirm_customer(customer.customer_name, customer.customer_email, order_id, restaurant_name, 'confirmed',preparing_time)
        return on_success
    elif status == 'rejected':
        db_session.query(Orders).filter(
            Orders.order_id == int(order_id)).update({
                "status":
                status,
                "datetime_confirmed":
                datetime.datetime.now()
            })
        db_session.commit()
        # confirm_customer(customer.customer_name, customer.customer_email, order_id, restaurant_name, 'rejected',preparing_time)
        return on_success
    elif status == 'finished':
        db_session.query(Orders).filter(
            Orders.order_id == int(order_id)).update({
                "status":
                status,
                "datetime_confirmed":
                datetime.datetime.now()
            })
        db_session.commit()
        # confirm_customer(customer.customer_name, customer.customer_email, order_id, restaurant_name, 'finished',preparing_time)
        return on_success
Example #33
0
def update(object):
    try:
        objToUpdate = db_session.query(type(object)).filter_by(id=object.id)
        objToUpdate.update(object.toMappedValues())
        db_session.commit()
    except:
        db_session.rollback()
    finally:
        closeDbSession()
Example #34
0
def get_menu_items():
    categories_set = set()
    menu_items = db_session.query(MenuItems).filter(
        MenuItems.item_status == 'active').all()
    for i in menu_items:
        print(i.item_status)
    # get categories out
    for item in menu_items:
        categories_set.add(item.item_category)
    # CMS
    categorized_menu_items = {}
    for category in categories_set:
        category_items = db_session.query(MenuItems).filter(
            and_(MenuItems.item_category == category,
                 MenuItems.item_status == 'active')).all()
        serialized_category_items = [item.serialize for item in category_items]
        categorized_menu_items[category] = serialized_category_items
    return jsonify(categorized_menu_items)
Example #35
0
def db():
    from openpyxl import load_workbook
    wb = load_workbook('krp.xlsx')
    ws = wb['4']
    for row in range(1, ws.max_row + 1):
        room = db_session.query(models.Room).filter(
            models.Room.hostel_id == 3,
            models.Room.room_number == ws['A%s' % row].value).update(
                {'note': 'ktp'})
        db_session.commit()
Example #36
0
 def post(self, id):
     obj = db_session.query(self.main_model).get(id)
     form = self.get_form(obj)
     if form.validate():
         form.populate_obj(obj)
         db_session.add(obj)
         db_session.commit()
         flash(u'%s updated' % self.main_model.__name__)
         return redirect(url_for(self.default_route))
     return render_template(self.template_name, obj=obj, form=form)
Example #37
0
def new_category():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        new = Category(name=request.form['name'],
                       user_id=login_session['user_id'])
        db_session.add(new)
        user = getUserInfo(login_session['user_id'])
        flash('New Category %s Successfully Created by %s' %
              (new.name, user.name))
        db_session.commit()
        categories = db_session.query(Category).order_by(asc(Category.name))
        return redirect(url_for('show_categories',
                                username=login_session["username"],
                                categories=categories))
    else:
        categories = db_session.query(Category).order_by(asc(Category.name))
        return render_template('new_category.html',
                               username=login_session["username"],
                               categories=categories)
Example #38
0
def new_get_person():
    query = db_session.query(models.Hostel, models.Person, models.Room).filter(
        models.Hostel.id == request.form['location']).filter(
            models.Person.id == request.form['id']).filter(
                models.Room.id == models.Person.room).first()

    return json.dumps({
        'status': 'ok',
        'person': query[1].first_name + ' ' + query[1].last_name,
        'room': query[2].room_number,
        'hostel': query[0].number
    })
Example #39
0
def get_last_account_num(branch_code):
    # account_num_row = AccountHolder.query\
    #    .with_entities(func.max(AccountHolder.account_number).label("max_account"))\
    #    .filter(AccountHolder.branch_code == branch_code)\
    #    .first()

    try:
        account_num_row = db_session.query(func.max(AccountHolder.account_number).label("max_account")) \
            .filter(AccountHolder.branch_code == branch_code) \
            .one()[0]
    except NoResultFound:
        account_num_row = None
    return account_num_row
Example #40
0
def create_user(jdic):
    
    group_user = db_session.query(Group).filter_by(name='user').one()
    time_expire = datetime.timedelta(10)+datetime.datetime.now()
    s = Session(time_expire, jdic['username'],jdic['password'])
    db_session.add(s)
    db_session.commit()
    u = User(jdic['username'],jdic['email'],jdic['password'],group_user)
    u.session = s
    db_session.add(u)
    db_session.commit()
    db_session.close()
    return s.token
Example #41
0
def edit_category(category_id):
    if 'username' not in login_session:
        return redirect('/login')

    edited = db_session.query(
        Category).filter_by(id=category_id).one()

    if request.method == 'POST':
        if request.form['name']:
            edited.name = request.form['name']
            flash('%s Category Successfully Edited ' % edited.name)
            categories = db_session.query(Category)\
                .order_by(asc(Category.name))
            return redirect(url_for('show_categories',
                                    username=login_session["username"],
                                    categories=categories))
    else:
        categories = db_session.query(Category).order_by(asc(Category.name))
        return render_template('edit_category.html',
                               category=edited,
                               username=login_session["username"],
                               categories=categories)
Example #42
0
def order_received():
    reload(app.utilities)
    if session.get('verified'):
        customer_info = db_session.query(Customers).filter(
            Customers.customer_id == session['customer_id']).one()
        customer_order_info = db_session.query(Orders).filter(
            Orders.customer_id == session['customer_id']).one()
        customer_order_items = db_session.query(OrderItems).filter(
            OrderItems.order_id == customer_order_info.order_id).all()
        total = 0
        for item in customer_order_items:
            total += (float(item.item_price) * item.item_quantity)
        if customer_order_info.order_method == 'delivery':
            a = float(total) + app.utilities.delivery_charges
            b = a * (float(app.utilities.delivery_tax) / 100)
            total = a + b

        session.pop('customer_id', None)
        session.pop('customer_phone', None)
        session.pop('verification_code', None)
        session.pop('verified', None)

        return render_template(
            'order_received.html',
            customer_info=customer_info,
            customer_order_info=customer_order_info,
            customer_order_items=customer_order_items,
            total=total,
            delivery_taxes=app.utilities.delivery_tax,
            delivery_charges=app.utilities.delivery_charges,
            pending_time=app.utilities.pending_time,
            delivery_time=datetime.timedelta(
                minutes=app.utilities.delivery_time),
            preparing_time=datetime.timedelta(
                minutes=app.utilities.preparing_time),
        )
    else:
        return redirect(url_for('.index'))
Example #43
0
    def show_link(bot, update):
        """ Callback function, that added link to the CHANNEL for inline message.
        Function recieve code from update.callback_query.data and uses it for
        determinate channel.

        :param bot: bot
        :type bot: telegram.Bot
        :param update: update event
        :type update: relegram.Update
        """
        code = update.callback_query.data
        inviter_id = db_session.query(ChannelInviter.inviter_id).filter_by(
            code=code).first()[0]
        # If another user pressed the button (not sender)
        # open the link to the channel
        if inviter_id != update.callback_query.from_user.id:
            channel = db_session.query(ChannelInviter).filter_by(
                code=code).first().channel

            # If user not in referrals
            # (not applyed the refferal link yet) add it to DB
            if db_session.query(Referral).filter_by(
                    receiver_id=update.callback_query.from_user.id,
                    channel_id=channel.channel_id).count() == 0:
                db_session.add(Referral(
                    inviter_id, channel.channel_id,
                    receiver_id=update.callback_query.from_user.id))
                db_session.commit()

            button = InlineKeyboardButton(
                ButtonsLabels.GO_TO, url=Links.BASE.format(channel.username))
            keyboard = create_inline_keyboard([button])
            text = Messages.INLINE_LINK_APPERED.format(channel.username)
            update.callback_query.edit_message_text(text=text,
                                                    parse_mode=ParseMode.HTML,
                                                    reply_markup=keyboard)

        return update.callback_query.answer()
Example #44
0
def edit_item(category_id, item_id):
    if 'username' not in login_session:
        return redirect('/login')
    edited_item = db_session.query(CategoryItem).filter_by(id=item_id).one()
    # confirm category exists
    db_session.query(Category).filter_by(id=category_id).one()
    print edited_item.category.name
    if request.method == 'POST':
        if request.form['name']:
            edited_item.name = request.form['name']
        if request.form['description']:
            edited_item.description = request.form['description']
        if request.form['category']:
            edited_item.category = db_session.query(Category).filter_by(
                id=request.form['category']).one()
            print edited_item.category.name
        photo = request.files.get('photo')
        if photo:
            with store_context(local_storage):
                    edited_item.picture.from_file(photo)
                    edited_item.picture.generate_thumbnail(width=300)
                    db_session.add(edited_item)
                    db_session.commit()
        else:
            db_session.add(edited_item)
            db_session.commit()
        flash('Item Successfully Edited')
        return redirect(url_for('show_items',
                                category_id=category_id))
    else:
        all_categories = db_session.query(Category).\
                                        order_by(asc(Category.name))
        return render_template('edit_item.html',
                               category_id=category_id,
                               item_id=item_id,
                               item=edited_item,
                               categories=all_categories)
Example #45
0
    def get(self):
        objs_json = []
        if 'query' in request.args:
            objs_json = search_drivers.search(self.main_model.__name__, request.args['query'])
        else:
            query = filter_query(request.args.iteritems(), self.filter_get(db_session.query(self.main_model)), self.main_model)
            objs = []
            if 'limit' in request.args:
                objs = query.order_by(self.default_sort)[0:int(request.args['limit'])]
            else:
                objs = query.order_by(self.default_sort).all()
            for obj in objs:
                objs_json.append(obj.to_dict(self.relations))

        return make_response(json.dumps(objs_json, cls = datetime_json_encoder), 200)
Example #46
0
def all_repair():
    if request.method == "GET":
        repairs = db_session.query(
            models.Repair, models.Person, models.Room,
            models.Hostel).filter(models.Repair.fix == False).filter(
                models.Repair.person == models.Person.id).filter(
                    models.Person.room == models.Room.id).filter(
                        models.Room.hostel_id == models.Hostel.id).order_by(
                            desc(models.Repair.open_date)).all()
        return render_template('all_repair.html', repairs=repairs)
    else:
        query = models.Repair.query.filter_by(id=request.form['id']).first()
        query.fix = True
        db_session.commit()
        return json.dumps({'status': 'OK'})
Example #47
0
 def reset_password(token, new_password):
     """Verify the new password for this user."""
     data = deserialize_data(token)
     if data is None:
         logging.warning(f"Error reseting password: BadSignature or "
                         f"SignatureExpired")
         return None
     user_id = data.get('id')
     user = db_session.query(User).filter_by(id=user_id).first()
     if user is None:
         logging.warning(f"User with id {user_id} does not exist.")
         return None
     user.password = new_password
     db_session.add(user)
     db_session.commit()
     return user
Example #48
0
def block_view(hostel, block):
    hostel_number = hostel
    block_number = block
    hostel_id = models.Hostel.query.filter_by(number=hostel).first().id
    block_id = models.Block.query.filter_by(number=block_number).first().id
    rooms = models.Room.query.filter_by(hostel_id=hostel_id,
                                        block_id=block_id).all()
    query = [x.id for x in rooms]
    places = {}
    for free in db_session.query(models.Room_free).filter(
            models.Room_free.room_id.in_(query)).all():
        places.update({str(free.room_id): free.places})

    return render_template('block_view.html',
                           hostel_number=hostel_number,
                           rooms=rooms,
                           room_free=places)
Example #49
0
def getUserID(email):
    try:
        user = db_session.query(User).filter_by(email=email).one()
        return user.id
    except:
        return None
Example #50
0
 def get(self, id):
     obj = filter_query(request.args.iteritems(), self.filter_get(db_session.query(self.main_model).filter(getattr(self.main_model, self.id_field) == id)), self.main_model).one()
     if obj is None:
         abort(404)
     obj_json = obj.to_dict(self.relations)
     return make_response(json.dumps(obj_json, cls = datetime_json_encoder), 200)
Example #51
0
def item_json(category_id, item_id):
    # confirm item exists
    item = db_session.query(CategoryItem).filter_by(id=item_id).one()
    return jsonify(item=item.serialize)
Example #52
0
 def get(self, id):
     obj = db_session.query(self.main_model).get(id)
     form = self.get_form(obj)
     return render_template(self.template_name, obj=obj, form=form)
Example #53
0
 def get(self):
     query = db_session.query(self.main_model)
     if(self.order_by is not None):
         query = query.order_by(self.order_by)
     objs = query.all()
     return render_template(self.template_name, objs=objs)
Example #54
0
def getUserInfo(user_id):
    user = db_session.query(User).filter_by(id=user_id).one()
    return user
Example #55
0
def show_items_json(category_id):
    # check that category exists
    db_session.query(Category).filter_by(id=category_id).one()
    items = db_session.query(CategoryItem).filter_by(
        category_id=category_id).all()
    return jsonify(items=[i.serialize for i in items])
Example #56
0
class LoginAPI(MethodView):
    def post(self):
        try:
                r = json.loads(request.data)
        except ValueError, err:
                return 'error during prasing json:%s'% err
        try:
                if not vemail.match(r['email']):
                    return 'email not correct %s'% r['email']
                if not vpassword.match(r['password']):
                    return 'password not correct'
        except KeyError, err:
                return 'leaking key %s' % err
        try:
                user = db_session.query(User).filter_by(email=r['email']).one()
        except Exception,e:
                db_session.rollback()
                db_session.close()
                logger.error(str(e))
                return 'unknown error'
        
        if user.password == r['password']:
            token = user.session.token
            db_session.close()
            return jmsg(3,extra={'token':token})
        else:
            return 'password not correct'


register_view = RegisterAPI.as_view('register')