def create_cheque_schedules(date):
    statement = CHEQUE_SCHEDULE.replace("(date)", str(date))
    total_schedules = execute_select_query(statement)
    output = [item for t in total_schedules for item in t]
    output.sort()
    for i in output:
        statement = CHEQUE_SCHEDULE_DETAILS.replace("(scheduleGroup)",
                                                    f"{i}").replace(
                                                        "(date)", str(date))
        accounts_in_schedule = execute_select_query(statement)
        schedule_transactions = {}
        for schedule in accounts_in_schedule:
            schedule_transactions = create_account_dictionary(
                schedule_transactions, schedule)
        schedule_reference = select_account_and_add_to_schedule(
            schedule_transactions, "cheque", i)
        schedule_reference_dict = {
            "schedule_number": schedule_reference,
            "schedule_date": str(datetime.date.today())
        }
        for schedule in accounts_in_schedule:
            update_query(
                "transaction", schedule_reference_dict,
                f"account_no = '{schedule[0]}' and rd_date = '{str(schedule[3])}' and is_cash = {False} and schedule_group = {i}"
            )
Пример #2
0
def set_deliver_complete_time(connection, cursor, username, oid):
    now = datetime.now()
    update_query(
        connection, cursor, 'update delivers '
        'set completeTime = %s '
        'where oid = %s and uid = ('
        'select uid from users where username = %s);', (now, oid, username))
Пример #3
0
def update_menu(connection, cursor, username, min_spent, avai, day_limit, no_orders, price, fid):
    rid = select_query(cursor,
                       'select rid from manages join users using(uid) '
                       'where username = %s', (username,))[0][0]
    if min_spent is not None:
        update_query(connection, cursor,
                     'update restaurants '
                     'set minSpent = %s '
                     'where rid = %s;', (float(min_spent), rid))
    if avai is not None:
        update_query(connection, cursor,
                     'update menu '
                     'set availability = %s '
                     'where rid = %s and fid = %s;', ((avai,), rid, fid))
    if day_limit is not None:
        update_query(connection, cursor,
                     'update menu '
                     'set dayLimit = %s '
                     'where rid = %s and fid = %s;', (int(day_limit), rid, fid))
    if no_orders is not None:
        update_query(connection, cursor,
                     'update menu '
                     'set noOfOrders = %s '
                     'where rid = %s and fid = %s;', (int(no_orders), rid, fid))
    if price is not None:
        update_query(connection, cursor,
                     'update menu '
                     'set price = %s '
                     'where rid = %s and fid = %s;', (float(price), rid, fid))
Пример #4
0
def review_order(connection, cursor, username, oid, content):
    update_query(connection, cursor,
                 'update orders '
                 'set review = %s '
                 'where oid = %s and cid = ('
                 'select uid from users where username = %s);',
                 (content, oid, username))
def get_and_update_rebate_and_default_fee(account_no, number_of_installments,
                                          rd_date, schedule_type,
                                          schedule_number):
    short_waits = WebDriverWait(driver.Instance, 10, poll_frequency=1)
    no_of_installment_element = driver.Instance.find_element_by_id(
        IDs.schedule_elements['no_of_installment'])
    no_of_installment_element.clear()
    no_of_installment_element.send_keys(number_of_installments)
    driver.Instance.find_element_by_id(
        IDs.schedule_elements['rebate_default_button']).click()
    rebate_element = short_waits.until(
        EC.presence_of_element_located(
            (By.ID, IDs.schedule_elements['rebate'])))
    default_element = short_waits.until(
        EC.presence_of_element_located(
            (By.ID, IDs.schedule_elements['default'])))
    rebate_default_dict = {
        'rebate': rebate_element.text.replace(",", "").strip(),
        'default_fee': default_element.text.replace(",", "").strip()
    }
    is_cash = True if schedule_type.lower() == 'cash' else False
    update_query(
        "transaction", rebate_default_dict,
        f"account_no = '{account_no}' and rd_date = '{str(rd_date)}' and is_cash = {is_cash} and schedule_group = {schedule_number}"
    )
Пример #6
0
def update():
    id_ = request.json['id']
    query = request.json['query']

    update_query(id_, query)
    obj = {'msg': '{}でクエリを登録しました。'.format(query)}

    obj = json.dumps(obj)

    return jsonify(obj)
Пример #7
0
def login_save_h():
    width = request.args.get('w')
    height = request.args.get('h')
    user_ip = request.remote_addr
    try:
        # TODO: select -> check -> update; don't remove
        update_query(
            "DELETE FROM `screen_size` WHERE `screen_size`.`user_ip`=%s",
            (user_ip, ))
        update_query(
            "INSERT INTO `screen_size` (`user_ip`, `w`, `h`) VALUES (%s, %s, %s)",
            (user_ip, width, height))
        # redirect to vk auth then, detailed static params below
        url = "https://oauth.vk.com/authorize?client_id={}&scope=groups&response_type=code&v=5.27&redirect_uri=http://vksmm.info{}".format(
            CLIENT_ID, url_for('parse_vk_responce'))
        return redirect(url)
    except Exception:
        log.error("/save_h error:\n{}".format(format_exception()))
        return redirect(url_for('landing_page'))
Пример #8
0
def add_schedule_full_time(connection, cursor, username, startday, endday,
                           shift):
    day = []
    if startday < endday:
        for i in range(startday, endday + 1):
            day.append(i)
    else:
        for i in range(startday, 8):
            day.append(i)
        for i in range(1, endday + 1):
            day.append(i)
    for i in range(len(day)):
        sid_morning = (day[i] - 1) * 8 + shift
        sid_afternoon = (day[i] - 1) * 8 + shift + 4
        update_query(
            connection, cursor, 'insert into MonthlyWorks (uid, sid) '
            'values '
            '((select uid from users where username = %s), %s), '
            '((select uid from users where username = %s), %s);',
            (username, sid_morning, username, sid_afternoon))
Пример #9
0
def delete_promotion(connection, cursor, pid):
    percent_query = select_query(
        cursor,
        'select 1 from Promotions join Percentage using(pid) where pid = %s;',
        (pid, ))
    if len(percent_query) != 0:
        update_query(connection, cursor,
                     'delete from Percentage where pid = %s;', (pid, ))
    flat_query = select_query(
        cursor,
        'select 1 from Promotions join Flat using(pid) where pid = %s;',
        (pid, ))
    if len(flat_query) != 0:
        update_query(connection, cursor, 'delete from Flat where pid = %s;',
                     (pid, ))
    update_query(connection, cursor, 'delete from Promotes where pid = %s;',
                 (pid, ))
    update_query(connection, cursor, 'delete from Promotions where pid = %s;',
                 (pid, ))
Пример #10
0
def update(connection, cursor, username, password=None, phone=None):
    if password is None:
        update_query(connection, cursor,
                     'update users set phone = %s where username = %s;',
                     ((phone, ), username))
    if phone is None:
        update_query(connection, cursor,
                     'update users set password = %s where username = %s;',
                     (password, username))
    else:
        update_query(
            connection, cursor,
            'update users set password = %s, phone = %s where username = %s;',
            (password, (phone, ), username))
Пример #11
0
def customer_update(connection, cursor, username, card_number=None, cvv=None):
    uid = select_query(cursor, 'select uid from users where username = %s',
                       (username, ))[0][0]
    if card_number is None:
        update_query(connection, cursor,
                     'update customers set cvv = %s where uid = %s;',
                     (cvv, uid))
    elif cvv is None:
        update_query(
            connection, cursor,
            'update customers set creditCardNumber = %s where uid = %s;',
            (card_number, uid))
    else:
        update_query(
            connection, cursor,
            'update customers set creditCardNumber = %s, cvv = %s where uid = %s;',
            (card_number, cvv, uid))
Пример #12
0
def create_promotion(connection, cursor, restaurant, foodItem, endDate,
                     startDate, promotionType, percent, maxAmount, flatAmount,
                     minAmount):
    update_query(
        connection, cursor,
        'insert into Promotions (pid, startDate, endDate) values '
        '((select count(*) from Promotions) + 1, %s, %s);',
        (startDate, endDate))
    if len(restaurant) == 0 and len(foodItem) == 0:
        update_query(
            connection, cursor, 'insert into Promotes (pid, rid, fid) '
            'values ((select count(*) from Promotions), NULL, NULL);')
    elif len(restaurant) != 0 and len(foodItem) == 0:
        rid = select_query(cursor,
                           'select rid from Restaurants where rName = %s',
                           (restaurant, ))[0][0]
        update_query(
            connection, cursor, 'insert into Promotes (pid, rid, fid) '
            'values ((select count(*) from Promotions), %s, NULL);', (rid, ))
    elif len(restaurant) == 0 and len(foodItem) != 0:
        fid = select_query(cursor,
                           'select fid from FoodItems where fName = %s',
                           (foodItem, ))[0][0]
        update_query(
            connection, cursor, 'insert into Promotes (pid, rid, fid) '
            'values ((select count(*) from Promotions), NULL, %s);', (fid, ))
    else:
        rid = select_query(cursor,
                           'select rid from Restaurants where rName = %s',
                           (restaurant, ))[0][0]
        fid = select_query(cursor,
                           'select fid from FoodItems where fName = %s',
                           (foodItem, ))[0][0]
        update_query(
            connection, cursor, 'insert into Promotes (pid, rid, fid) '
            'values ((select count(*) from Promotions), %s, %s);', (rid, fid))
    if promotionType == 'percent':
        update_query(
            connection, cursor,
            'insert into Percentage (pid, percent, maxAmount) '
            'values ((select count(*) from Promotions), %s, %s);',
            (percent, maxAmount))
    else:
        update_query(
            connection, cursor,
            'insert into Flat (pid, flatAmount, minAmount) '
            'values ((select count(*) from Promotions), %s, %s);',
            (flatAmount, minAmount))
Пример #13
0
def full_cycle_v2(processed_groups, all_):
    """Actually scans only 1 group, save parsed groups"""
    buf_all_groups = list(all_)
    i = 0
    chosen_id = -1
    while i < len(buf_all_groups):
        try:
            group_id = buf_all_groups[i]
            if group_id not in processed_groups:
                break
            else:
                buf_all_groups.pop(i)
        except Exception as e:
            log.error("Alert! Data error: {}. Raw: {}".format(
                e, buf_all_groups))
    try:
        if chosen_id == -1:
            group_id = buf_all_groups[0]  # -- first group of leftover
        else:
            group_id = chosen_id
    except Exception as e:
        log.error("choose_id exception: {}, buf_all_groups: {}".format(
            e, buf_all_groups))
        return None

    auth_token = None
    ret = getA(group_id, auth_token, 0, 1)

    # determine here if token is required
    ret_keys = ret.keys()
    if "count" in ret_keys:
        count = ret["count"]
    elif "code" in ret_keys:
        log.info("refreshing access_token...")
        user_id = select_query(
            "select g.`user_id` from `groups` g where g.`group_id`=%s order by g.`added` desc",
            (group_id, ))[0][0]
        auth_token = select_query(
            "select u.`auth_token` from `userinfo` u where u.`user_id`=%s",
            (user_id, ))[0][0]
        ret = getA(group_id, auth_token, 0, 1)
        if "count" in ret.keys():
            count = int(ret["count"])
        else:
            log.error("sorry... error_code={0}, message: {1}".format(
                ret["code"], ret["message"]))
            log.info(ret)
            return group_id
    else:
        return group_id
    log.info("--OK")
    update_query("update groups set is_old=1 where group_id=%s", (group_id, ))
    update_query("delete from postinfo where group_id=%s", (group_id, ))
    screen_name = select_query(
        "SELECT g.`screen_name` FROM `groups` g WHERE g.`group_id`=%s",
        (group_id, ))[0][0]
    log.info("screen_name: {}, group_id: {}, nums to parse: {}".format(
        screen_name, group_id, str(count)))
    if count > 30000 or count == 0:
        update_query("delete from groups where group_id=%s", (group_id, ))
        log.info("removing this group from queue")
        return group_id
    try:
        req = "https://api.vk.com/method/groups.getById?group_id={0}".format(
            group_id)
        written_name = short_value(
            requests.get(req).json()["response"][0]["name"].replace(
                "&amp;", "&"), 35)
    except Exception as ex:
        log.error("no written_name: {0}".format(ex))
        written_name = short_value(screen_name, 35)
    print "name: {}".format(written_name)

    # UPDATE GROUP-INFO IN THE STATS
    try:
        with open(os.path.join(os.getcwd(), "statistics.txt"), "r") as f:
            data = json.loads(f.read())
    except:
        data = {}
    data["name"] = written_name
    data["count"] = count
    data["group_id"] = group_id
    data["totalgroups"] = len(all_)
    with open(os.path.join(os.getcwd(), "statistics.txt"), "w") as f:
        f.write(json.dumps(data))

    # LOAD AND PROCESS VK-POSTS
    offset = count // 100 + 1
    for i in range(0, offset):
        posts = getA(group_id, auth_token, i * 100, 100)
        for post in posts["items"]:
            try:
                link = "http://vk.com/{0}?w=wall-{1}_{2}".format(
                    screen_name, group_id, post["id"])
                try:
                    comm = post["comments"]["count"]
                except:
                    comm = 0
                try:
                    like = post["likes"]["count"]
                except:
                    like = 0
                try:
                    repo = post["reposts"]["count"]
                except:
                    repo = 0
                try:
                    picture = None
                    if "attachments" in post.keys():
                        a_type = post["attachments"][0]["type"]
                        if a_type in ["photo", "video"]:
                            picture = post["attachments"][0][a_type][
                                "photo_130"]
                except Exception as ex:
                    picture = None
                update_query(
                    "insert into `postinfo` (`group_id`, `link`, `like`, `comm`, `repo`, `picture`) values (%s, %s, %s, %s, %s, %s)",
                    (group_id, link, like, comm, repo, picture))
            except BaseException as ex:
                log.error(
                    "link error: {}, full post: {}, full response: {}".format(
                        ex, post, posts))
        # UPDATE POSTs-INFO IN THE STATS
        with open(os.path.join(os.getcwd(), "statistics.txt"), "r") as f:
            data = json.loads(f.read())
        data["count"] -= len(posts["items"])
        if data["count"] < 0:
            data["count"] = 0
        with open(os.path.join(os.getcwd(), "statistics.txt"), "w") as f:
            f.write(json.dumps(data))
        time.sleep(0.05)

    # now load datas back and save only best 300
    limit = 100  # x3 = 300
    if count > limit * 3.05:
        ts = time.time()
        bestlikes = select_query(
            "select p.`group_id`, p.`link`, p.`like`, p.`comm`, p.`repo`, p.`picture` from `postinfo` p where p.`group_id`=%s order by p.`like` desc limit %s",
            (group_id, limit))
        bestrepos = select_query(
            "select p.`group_id`, p.`link`, p.`like`, p.`comm`, p.`repo`, p.`picture` from `postinfo` p where p.`group_id`=%s order by p.`repo` desc limit %s",
            (group_id, limit))
        bestcomms = select_query(
            "select p.`group_id`, p.`link`, p.`like`, p.`comm`, p.`repo`, p.`picture` from `postinfo` p where p.`group_id`=%s order by p.`comm` desc limit %s",
            (group_id, limit))
        update_query("delete from postinfo where group_id=%s", (group_id, ))

        toti = 0
        bestdatas = []
        append = bestdatas.append
        for post in bestlikes + bestrepos + bestcomms:
            if post not in bestdatas:
                toti += 1
                append(post)
                update_query(
                    "INSERT INTO `postinfo` (`group_id`, `link`, `like`, `comm`, `repo`, `picture`) VALUES (%s, %s, %s, %s, %s, %s)",
                    (post[0], post[1], post[2], post[3], post[4], post[5]))
                time.sleep(0.03)
        log.info("{} seconds to re save {} posts".format(
            int(time.time() - ts), toti))
    else:
        log.info("no re-save needed")
    return group_id
Пример #14
0
def rate_deliver(connection, cursor, oid, rating):
    update_query(connection, cursor,
                 'update delivers '
                 'set rating = %s '
                 'where oid = %s;', (rating, oid))
Пример #15
0
def delete_schedule_part_time(connection, cursor, username, sid):
    sid = tuple([int(item) for item in sid])
    update_query(
        connection, cursor, 'delete from WeeklyWorks '
        'where uid = (select uid from users where username = %s) and sid in %s;',
        (username, sid))
Пример #16
0
def add_food(connection, cursor, username, fName, fCategory):
    update_query(connection, cursor,
                 'insert into FoodItems (fid, fName, fCategory) '
                 'values ((select count(*) from FoodItems) + 1, %s, %s);', ((fName,), (fCategory,)))
Пример #17
0
def checkout(connection, cursor, username, rid, fid, quantity, ptype, pid, location):
    availability = select_query(cursor,
                                'select availability '
                                'from menu '
                                'where rid = %s and fid in %s;',
                                (rid, fid))[0][0]
    if not availability:
        raise Exception('This item is not available')
    now = datetime.now()
    oid = select_query(cursor,
                       'select count(*) + 1 from orders;')[0][0]
    update_query(connection, cursor,
                 'insert into orders (oid, orderTime, rid, cid) '
                 'values '
                 '('
                 '%s, %s, %s, '
                 '(select uid from users where username = %s)'
                 ');',
                 (oid, now, rid, username))
    for i in range(len(fid)):
        update_query(connection, cursor,
                     'insert into contains (oid, fid, quantity) '
                     'values '
                     '(%s, %s, %s);', (oid, fid[i], quantity[i]))
        update_query(connection, cursor,
                     'update menu m '
                     'set noOfOrders = noOfOrders + '
                     '(select quantity '
                     'from contains c '
                     'where c.fid = %s and oid = %s'
                     ') '
                     'where rid = %s and fid = %s;',
                     (fid[i], oid, rid, fid[i]))
    total_price = select_query(cursor,
                               'select sum(price*quantity) as totalPrice '
                               'from contains join orders using(oid) '
                               'join menu using(rid, fid) '
                               'where oid = %s', (oid,))[0][0]
    min_spent = select_query(cursor,
                             'select minSpent '
                             'from restaurants join orders using(rid) '
                             'where oid = %s;', (oid,))[0][0]
    if total_price < min_spent:
        raise Exception('Minimum spent is not met')
    discount = 0
    if ptype == 'flat':
        flat_promo = select_query(cursor,
                                  'select distinct flatAmount '
                                  'from flat join promotes using(pid) '
                                  'where pid = %s '
                                  'and (fid is null or fid in %s) '
                                  'and (rid is null or rid = %s) '
                                  'and minAmount <= %s;', (pid, fid, rid, total_price))
        if len(flat_promo) > 0:
            discount = flat_promo[0][0]
    elif ptype == 'percentage':
        percent_promo = select_query(cursor,
                                     'select percent, quantity, price, maxAmount '
                                     'from percentage join promotes pr using(pid) '
                                     'join contains c on('
                                     'pr.fid is null or c.fid = pr.fid) '
                                     'join menu m on('
                                     'pr.rid is null or m.rid = pr.rid) '
                                     'where pid = %s '
                                     'and c.fid in %s '
                                     'and m.rid = %s;', (pid, fid, rid))
        if len(percent_promo) > 0:
            discount = sum(item[0] * item[1] * item[2] for item in percent_promo)
            discount = min(discount, percent_promo[0][3])
    update_query(connection, cursor,
                 'update customers '
                 'set rewardPoints = rewardPoints + round(%s) '
                 'where uid = ('
                 'select uid '
                 'from customers join users using(uid) '
                 'where username = %s);',
                 (total_price - discount, username))
    part_time = select_query(cursor,
                             'select w.uid '
                             'from weeklyworks w join schedules using(sid) '
                             'where startTime <= %s and endTime >= %s '
                             'and dayOfWeek = %s '
                             'and not exists ('
                             'select 1 '
                             'from delivers d '
                             'where (completeTime is null or completeTime > %s) and d.uid = w.uid'
                             ');',
                             (now.strftime('%H:%M'), now.strftime('%H:%M'), convert_date(now.strftime("%A")), now))
    full_time = select_query(cursor,
                             'select uid '
                             'from monthlyworks w join schedules using(sid) '
                             'where startTime <= %s and endTime >= %s '
                             'and dayOfWeek = %s '
                             'and not exists ('
                             'select 1 '
                             'from delivers d '
                             'where (completeTime is null or completeTime > %s) and d.uid = w.uid'
                             ');',
                             (now.strftime('%H:%M'), now.strftime('%H:%M'), convert_date(now.strftime("%A")), now))
    rider = (part_time + full_time)[0][0]
    update_query(connection, cursor,
                 'insert into delivers (uid, oid, startTime, deliverCost, location) '
                 'values (%s, %s, %s, 10, %s);',
                 (rider, oid, now, location))
    return {
        'oid': oid,
        'food price': total_price,
        'discount': discount,
        'deliver cost': 10,
        'total price': total_price - discount + 10,
        'rider': rider
    }
Пример #18
0
def parse_vk_responce():
    code = request.args.get('code')
    if code:
        try:
            # render link and get auth_token, user_id
            url = "https://oauth.vk.com/access_token?client_id={}&client_secret={}&code={}&redirect_uri=http://vksmm.info{}".format(
                CLIENT_ID, CLIENT_SECRET, code, url_for('parse_vk_responce'))
            res = requests.get(url).json()
            user_id = res["user_id"]
            access_token = res["access_token"]

            # LOAD OLD SORTING
            res = select_query(
                "SELECT u.`sort_type` FROM `userinfo` u WHERE u.`user_id`=%s",
                (user_id, ))
            try:
                sort_type = res[0][0]
                if sort_type not in ['like', 'repo', 'comm']:
                    sort_type = 'like'
            except:
                sort_type = 'like'

            # LOAD USER-DATA
            try:
                url = "https://api.vk.com/method/execute.name_pic?access_token={0}&id={1}".format(
                    access_token, user_id)
                response = requests.get(url).json()["response"]
                username = response["name"]
                picture = response["picture"]  # avatar 100px
            except Exception as e:
                log.error("load user-datas: {}".format(e))
                username = "******"
                picture = None
            log.info("+ {} online".format(username))

            # delete old personal data, save new
            # WTF???
            update_query(
                "DELETE FROM `userinfo` WHERE `userinfo`.`user_id`=%s",
                (user_id, ))
            update_query("DELETE FROM `groups` where `groups`.`user_id`=%s",
                         (user_id, ))
            update_query(
                "INSERT INTO `userinfo` (`user_id`, `auth_token`, `sort_type`, `last_seen`, `username`, `picture`) VALUES (%s, %s, %s, %s, %s, %s)",
                (user_id, access_token, sort_type, datetime.now(), username,
                 picture))
            try:
                # load fresh groups from account;
                req = "https://api.vk.com/method/execute.get_all_groups?access_token={}".format(
                    access_token)
                buf = requests.get(req).json()["response"]

                len_buf = len(buf)
                limit = 100
                steps = len_buf // limit + 1
                for st in range(steps):
                    offset = st * limit
                    i = offset
                    group_ids = ""
                    while i < offset + limit and i < len_buf:
                        group_ids += "{},".format(buf[i])
                        i += 1
                    req = "https://api.vk.com/method/groups.getById?group_ids={0}".format(
                        group_ids[:-1])
                    groups = requests.get(req)
                    groups_json = groups.json()["response"]

                    for item in groups_json:
                        group_name = wrap_value(item["name"])
                        try:
                            update_query(
                                "INSERT INTO `groups` (`user_id`, `group_id`, `screen_name`, `picture`, `added`, `is_old`, `groupname`) VALUES (%s, %s, %s, %s, %s, 0, %s)",
                                (int(user_id), int(item["gid"]),
                                 item["screen_name"], item["photo_medium"],
                                 int(time.time()), group_name))
                        except Exception as e:
                            log.error(repr(e))
            except Exception:
                log.error(format_exception())
            return redirect(
                url_for('index_page',
                        user_id=user_id,
                        access_token=access_token))
        except Exception:
            log.error("/vk_login err:\n{}".format(format_exception()))
    return redirect(url_for('landing_page'))  # add an error-message here ?
Пример #19
0
def register(connection, cursor, username, password, phone, user_type,
             rider_type):
    uid = select_query(cursor, 'select count(*) from users;')[0][0] + 1
    update_query(
        connection, cursor,
        'insert into Users (uid, username, password, phone) values '
        '(%s, %s, %s, %s);', (uid, username, password, (phone, )))
    if user_type == 'customer':
        today = date.today()
        update_query(
            connection, cursor,
            'insert into Customers (uid, rewardPoints, registerDate) values '
            '(%s, 0, %s);', (uid, today))
    if user_type == 'rider':
        update_query(connection, cursor,
                     'insert into Riders (uid) values (%s);', (uid, ))
        if rider_type == 'partTime':
            update_query(
                connection, cursor,
                'insert into PartTimeRiders (uid, psalary) values (%s, 12);',
                (uid, ))
        if rider_type == 'fullTime':
            update_query(
                connection, cursor,
                'insert into FullTimeRiders (uid, fsalary) values (%s, 40);',
                (uid, ))
    if user_type == 'staff':
        update_query(
            connection, cursor,
            'insert into Staffs (uid) values ((select count(*) from Users));')
    if username == 'manager':
        update_query(
            connection, cursor,
            'insert into Managers (uid) values ((select count(*) from Users));'
        )
Пример #20
0
def index_page():
    try:
        user_id = int(request.args.get('user_id'))
    except:
        return redirect(
            url_for('landing_page')
        )  # add an error-message here ? "'user_id' error: int expected"
    try:
        offset = int(request.args.get('offset'))
    except:
        offset = 0
    sort_type = request.args.get('sort_type')
    access_token = request.args.get('access_token')
    if user_id and access_token:
        try:
            groups = select_query(
                "SELECT g.`group_id`, g.`groupname`, g.`picture` FROM `groups` g WHERE g.`user_id`=%s",
                (user_id, ))
            try:
                group_id = int(request.args.get('group_id'))
            except:
                group_id = groups[0][0]

            current_group_name = None
            current_group_picture = None
            group_list = []
            append = group_list.append
            for item in groups:
                buf_group_name = short_value(unwrap_value(item[1]), 30)
                append([item[0], buf_group_name, item[2]])
                if int(item[0]) == int(group_id):
                    current_group_name = unwrap_value(item[1])
                    current_group_picture = item[2]
            if not current_group_name and not current_group_picture:
                # then load from vk
                req = "https://api.vk.com/method/groups.getById?group_ids={0}".format(
                    group_id)
                other_group_data = requests.get(req).json()["response"][0]
                current_group_name = unwrap_value(other_group_data["name"])
                current_group_picture = other_group_data["photo_medium"]

            # UPDATE SORTING
            if sort_type in ('like', 'repo', 'comm'):
                update_query(
                    "UPDATE `userinfo` SET last_seen = %s, sort_type = %s WHERE user_id = %s",
                    (datetime.now(), sort_type, user_id))
            else:
                update_query(
                    "UPDATE `userinfo` SET last_seen = %s WHERE user_id=%s",
                    (datetime.now(), user_id))
                res = select_query(
                    "SELECT u.`sort_type` FROM `userinfo` u WHERE u.`user_id`=%s",
                    (user_id, ))
                sort_type = res[0][0]

            try:
                w = int(request.args.get('w'))
                h = int(request.args.get('h'))
            except:
                user_ip = request.remote_addr
                sizes = select_query(
                    "SELECT s.`w`, s.`h` FROM `screen_size` s WHERE s.`user_ip`=%s",
                    (user_ip, ))
                w, h = sizes[0]
                log.debug("width = {0}, height = {1}; user_ip = {2}".format(
                    w, h, user_ip))
            try:
                cols = int((w * 0.8 - 235) / 125)  # x
                rows = int((h - 120.0) / 120)  # y
                count = rows * cols
            except:
                count = 35
            posts = select_query(
                "SELECT p.`like`, p.`repo`, p.`comm`, p.`link`, p.`picture` FROM `postinfo` p WHERE p.`group_id`=%s ORDER BY %s DESC LIMIT %s OFFSET %s",
                (group_id, sort_type, count, offset * count))
            if posts:
                recommendation = None
            else:
                max_range = select_query(
                    "SELECT COUNT(g.*) FROM `groups` g WHERE g.`is_old`=1"
                )[0][0]
                try:
                    rlimit = int((h - 300) / 36.0)
                    if rlimit > max_range:
                        log.debug("big screen :)")
                        rlimit = max_range - 1
                except Exception as e:
                    log.error("rlimit e:", e)
                    rlimit = 13
                roffset = int((max_range - rlimit) * random()) + 1
                groups = select_query(
                    "SELECT g.`group_id`, g.`groupname`, g.`picture` FROM `groups` g WHERE g.`is_old`=1 ORDER BY g.`group_id` ASC LIMIT %s OFFSER %s",
                    (rlimit, roffset))
                recommendation = []
                append = recommendation.append
                for item in groups:
                    try:
                        buf_group_name = short_value(unwrap_value(item[1]), 50)
                        if [item[0], buf_group_name,
                                item[2]] not in recommendation:
                            append([item[0], buf_group_name, item[2]])
                    except Exception:
                        log.error(traceback.print_exc())

            # PAGE-NAVIGATION LINKS
            offset_prev = None
            if offset > 0:
                offset_prev = url_for(
                    'index_page'
                ) + "?user_id={0}&access_token={1}&group_id={2}&offset={3}".format(
                    user_id, access_token, group_id, offset - 1)

            offset_next = None
            count_postinfo = select_query(
                "SELECT COUNT(p.*) FROM `postinfo` p WHERE p.`group_id`=%s",
                (group_id, ))[0][0]
            if count * (offset + 1) < count_postinfo:
                offset_next = url_for(
                    'index_page'
                ) + "?user_id={0}&access_token={1}&group_id={2}&offset={3}".format(
                    user_id, access_token, group_id, offset + 1)

            base_link = url_for(
                'index_page'
            ) + "?user_id={0}&access_token={1}&group_id={2}&offset={3}&sort_type=".format(
                user_id, access_token, group_id, offset)

            # LOAD USER DATA
            user_name, avatar = select_query(
                "SELECT u.`username`, u.`picture` FROM `userinfo` u WHERE u.`user_id`=%s",
                (user_id, ))[0]

            # LOAD STATS
            try:
                with open("statistics.txt", "r") as f:
                    stats = json.loads(f.read())
            except:
                stats = None
            return render_template("index.html",
                                   group_list=group_list,
                                   posts=posts,
                                   user_id=user_id,
                                   user_name=user_name,
                                   avatar=avatar,
                                   access_token=access_token,
                                   current_group_name=current_group_name,
                                   current_group_picture=current_group_picture,
                                   offset_prev=offset_prev,
                                   offset_next=offset_next,
                                   offset=offset,
                                   base_link=base_link,
                                   stats=stats,
                                   group_id=group_id,
                                   count_postinfo=count_postinfo,
                                   sort_type=sort_type,
                                   recomendation=recommendation)
        except Exception:
            log.error("Exception at index_page:\n{}".format(
                format_exception()))
    return redirect(url_for('landing_page'))