Пример #1
0
def cartridge(request, cartridge_id):
    title = 'Расходные материалы'
    options = _query(f"SELECT * FROM all_options_for_cartridges WHERE id = {cartridge_id}")
    prices = _query(f"SELECT v.name, cartridge_price.price FROM cartridge_price "
                    f"LEFT JOIN vendors v ON v.id = cartridge_price.vendor_id WHERE cartridge_id = {cartridge_id}")
    cartridge = _query(f"SELECT * FROM all_cartridge WHERE id = {cartridge_id}")
    if cartridge:
        carts = list(cartridge[0])
        tids = set()
        tmodels = set()
        tamodels = set()
        # ids = list(set(carts[5]))
        ids = [x for x in carts[5] if not (x in tids or tids.add(x))]
        # models = list(set(carts[4]))
        models = [x for x in carts[4] if not (x in tmodels or tmodels.add(x))]
        brand_id = carts[6]
        if carts[7]:
            brand = carts[7]
        else:
            brand = ''
        arr = []
        for idx, v in enumerate(models):
            arr.append([ids[idx], v])
        carts[4] = arr
        amodels = [x for x in carts[8] if not (x in tamodels or tamodels.add(x))]
        cartridge = tuple(carts)
        return render(request, 'cartridge/cartridge.html', {'title': title, 'cartridge': cartridge, 'options': options,
                                                            'brand': brand, 'brand_id': brand_id, 'amodels': amodels,
                                                            'prices': prices, 'cartridge_id': cartridge_id})
    else:
        raise Http404('Страница отсутствует, с id: ' + str(cartridge_id))
Пример #2
0
def get_from_models(model_id):
    # print(datetime.datetime.now() - start_time, 'сбор остального')
    mq = _query(
        f'SELECT brand_id, name, main_image, image FROM models WHERE id = {model_id}'
    )
    try:
        brand_id = mq[0][0]
    except:
        brand_id = None
    try:
        model = mq[0][1]
    except:
        model = None
    try:
        model_main_image = mq[0][2]
    except:
        model_main_image = None
    try:
        model_images = mq[0][3].split(';')
    except:
        model_images = None
    try:
        brand_name = models.Brands.objects.filter(
            id=brand_id).values('name')[0]['name']
    except:
        brand_name = None
    # print(datetime.datetime.now() - start_time, 'сбор остального завершен')
    return model, model_main_image, model_images, brand_id, brand_name
Пример #3
0
def get_all_models(brand_id, limit, offset):
    # print(datetime.datetime.now() - start_time, 'получение всех моделей')
    brand_models = _query(
        f'SELECT * FROM model_for_filter mopt WHERE brand_id = {brand_id} ORDER BY main_image LIMIT {limit} OFFSET {offset};'
    )
    # print(datetime.datetime.now() - start_time, 'получение всех моделей завершено')
    return brand_models
Пример #4
0
def get_from_spr_details(spr_detail_id):
    dq = _query(
        f'SELECT name, name_ru FROM spr_details WHERE id = {spr_detail_id}')
    try:
        if dq[0][1]:
            detail_name = dq[0][1]
        else:
            detail_name = dq[0][0]
    except:
        detail_name = None
    return detail_name
Пример #5
0
def get_errors(model_id):
    # print(datetime.datetime.now() - start_time, 'получение ошибок')
    verrors = _query(
        f"SELECT * FROM all_errors WHERE mid = {model_id}  ORDER BY code;")
    # print(datetime.datetime.now() - start_time, 'получение ошибок завершено')

    # print(datetime.datetime.now() - start_time, 'сортировка ошибок')
    if len(verrors) > 0:
        if verrors[0][2] is None and verrors[0][3] is None and verrors[0][
                4] is None and verrors[0][5] is None:
            verrors = None
    # print(datetime.datetime.now() - start_time, 'сортировка ошибок завершена')
    return verrors
Пример #6
0
def get_cartridge(model_id):
    # print(datetime.datetime.now() - start_time, 'получение картриджей')
    cartridges = _query(
        f"SELECT * FROM all_cartridge WHERE {model_id} = ANY(model_id)")
    for idx in range(len(cartridges)):
        cartridge = list(cartridges[idx])
        cartridge[4] = list(set(cartridge[4]))
        cartridges[idx] = tuple(cartridge)
        cartridge_alt = list(cartridges[idx])
        cartridge_alt[8] = list(set(cartridge[8]))
        cartridges[idx] = tuple(cartridge_alt)
    # print(datetime.datetime.now() - start_time, 'получение картриджей завершено')
    return cartridges
Пример #7
0
def get_ids(model_id):
    # print(datetime.datetime.now() - start_time, 'сбор id')
    qd = _query(
        f'SELECT * FROM details WHERE model_id = {model_id} and partcode_id is null'
    )
    try:
        detail_id = qd[0][0]
        spr_detail_id = qd[0][4]
    except:
        detail_id = None
        spr_detail_id = None
    # print(datetime.datetime.now() - start_time, 'сбор id завершен')
    return detail_id, spr_detail_id
Пример #8
0
def cartridges(request, brand_id):
    title = 'Расходные материалы'
    cartridges = _query(f"SELECT * FROM all_cartridge WHERE brand_id = {brand_id} ORDER BY id")
    brand = ''
    for idx in range(len(cartridges)):
        cartridge = list(cartridges[idx])
        cartridge[4] = list(set(cartridge[4]))
        cartridges[idx] = tuple(cartridge)
        cartridge_alt = list(cartridges[idx])
        cartridge_alt[8] = list(set(cartridge[8]))
        cartridges[idx] = tuple(cartridge_alt)
        if cartridge[7]:
            brand = cartridge[7]
        else:
            brand = ''

    return render(request, 'cartridge/cartridges.html', {'title': title, 'cartridges': cartridges, 'brand': brand})
Пример #9
0
def sql_get_range(cid, rmin, rmax):
    if rmin:
        pass
    else:
        rmin = 0
    if rmax:
        pass
    else:
        rmax = 1000000
    q = f'SELECT * FROM select_id_for_range({cid}, {rmin}, {rmax})'
    rids = _query(q)
    sq = ''
    for i, rid in enumerate(rids):
        if i == 0:
            sq = f' mopt.ids && ARRAY[{rid[0]}]'
        else:
            sq += f' OR mopt.ids && ARRAY[{rid[0]}]'
    return sq
Пример #10
0
def get_options(detail_id):
    captions = [
        'Общие характеристики',
        'Принтер',
        'Копир',
        'Сканер',
        'Расходные материалы',
        'Факс',
        'Телефон',
        'Шрифты и языки управления',
        'Лотки',
        'Финишер',
        'Интерфейсы',
        'Память/Процессор',
        'Дополнительная информация',
        'Фото',
        'Общая информация',
        'Габариты',
        'Снят с производства',
        'Актуальный',
    ]
    subcaptions = []
    values = []
    # print(datetime.datetime.now() - start_time, 'получение опций')
    option_vals = _query(
        f"SELECT * FROM all_options_model WHERE detail_id = {detail_id};")
    # print(datetime.datetime.now() - start_time, 'получение опций завершено')

    # print(datetime.datetime.now() - start_time, 'сортировка опций')
    for opts in option_vals:
        if opts[0] is None and opts[1] is not None:
            for opt in opts[3]:
                if 'SubCaption' in opt:
                    opts[3].remove(opt)
            subcaptions.append(opts)
        else:
            values.append(opts)
    options = option_vals
    # print(datetime.datetime.now() - start_time, 'сортировка опций завершена')
    return options, captions, subcaptions, values
Пример #11
0
def get_options(detail_id):
    # print(datetime.datetime.now() - start_time, 'Запрос на получение опций')
    q_options = f"SELECT * FROM all_options_for_details WHERE detail_id = {detail_id}"
    option_vals = _query(q_options)
    # print(datetime.datetime.now() - start_time, 'Запрос на получение опций завершен')
    # print(datetime.datetime.now() - start_time, 'Сортировка опций')
    captions = []
    subcaptions = []
    values = []
    for opts in option_vals:
        if opts[0] is None and opts[1] is None:
            for i in range(len(opts[3])):
                opts[3][i] = opts[3][i].replace('Caption: ', '')
            captions.append(opts)
        if opts[0] is None and opts[1] is not None:
            for opt in opts[3]:
                if 'SubCaption' in opt:
                    opts[3].remove(opt)
            subcaptions.append(opts)
        else:
            values.append(opts)
    options = option_vals
    # print(datetime.datetime.now() - start_time, 'Сортировка опций завершена')
    return options, captions, subcaptions, values
Пример #12
0
def qet_partcatalog(request, model_id):
    # 'Получение id парткодов, моделей, модулей, названий детали для модулей и парткаталога', q_code_module)
    modules = []
    # print(datetime.datetime.now() - start_time, 'получение парткодов и модулей')
    partcatalog = _query(
        f'SELECT * FROM all_partcatalog WHERE model_id = {model_id}')
    # print(datetime.datetime.now() - start_time, 'получение парткодов и модулей завершено')

    # print(datetime.datetime.now() - start_time, 'Сортировка парткаталога')
    if partcatalog and len(partcatalog) > 0:
        for parts in partcatalog:
            # print(parts)
            if parts[4]:
                modules.append(parts[4])
            elif parts[3]:
                modules.append(parts[3])
        modules = list(dict.fromkeys(modules))
    if request.GET.get('module'):
        cur_module = request.GET.get('module')
    else:
        cur_module = None
    # print(datetime.datetime.now() - start_time, 'Сортировка парткаталога завершена')

    return modules, cur_module, partcatalog
Пример #13
0
def get_filtered_model(brand_id, checkboxs, ranges, radios):
    checkboxs = json.loads(str(checkboxs))
    ranges = json.loads(str(ranges))
    radios = json.loads(str(radios))
    f_sql = f'SELECT * FROM model_for_filter mopt WHERE ('
    ops = 0
    for key, value in ranges.items():
        if len(value) > 0:
            if ops == 0:
                f_sql += sql_get_range(key.replace('range', ''), value[0],
                                       value[1])
                ops += 1
            else:
                f_sql += ' AND '
                f_sql += sql_get_range(key.replace('range', ''), value[0],
                                       value[1])
    for key, value in radios.items():
        if len(value) > 0:
            if ops == 0:
                f_sql += (f'mopt.ids && ARRAY[{value}]')
                ops += 1
            else:
                f_sql += ' AND '
                f_sql += (f'mopt.ids && ARRAY[{value}]')
    for key, value in checkboxs.items():
        if len(value) > 0:
            if ops == 0:
                f_sql += sql_gen_checks(value)
                ops += 1
            else:
                f_sql += ' AND '
                f_sql += sql_gen_checks(value)
    f_sql += f' ) AND brand_id = {brand_id} ORDER BY main_image;'
    print(f_sql)
    brand_models = _query(f_sql)
    return brand_models
Пример #14
0
def get_partcodes(model_id):
    # print(datetime.datetime.now() - start_time, 'Запрос на получение парткаталога')
    partcatalog = _query(f"SELECT * FROM all_partcatalog WHERE model_id = {model_id}")
    # print(datetime.datetime.now() - start_time, 'Запрос на получение парткаталога завершен')
    return partcatalog
Пример #15
0
def get_cartridge_options(partcode):
    # print(datetime.datetime.now() - start_time, 'Запрос на получение картриджей')
    cartridge_options = _query(f"SELECT * FROM all_options_for_cartridges WHERE code = '{partcode}'")
    # print(datetime.datetime.now() - start_time, 'Запрос на получение картриджей завершен')
    return cartridge_options
Пример #16
0
def set_weight(detail_id):
    # print(datetime.datetime.now() - start_time, 'обновление веса')
    _query(
        f"UPDATE details SET weight = (w.weight+1) FROM (SELECT weight FROM details WHERE id = {detail_id}) w "
        f"WHERE id = {detail_id}")