Ejemplo n.º 1
0
def show_certifications(request, *args, **kwargs):
    """Вывод удостоверений"""
    mh_vars = certifications_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP)
    context = mh.context
    context['insert_breadcrumbs'] = insert_breadcrumbs
    context['welding_types'] = WELDING_TYPES
    context['group_choices'] = CertSections.group_choices
    special_model_vars(mh, mh_vars, context)
    # -----------------------------
    # Вся выборка только через аякс
    # -----------------------------
    if request.is_ajax():
        rows = mh.standard_show()
        result = []
        ids_certs = {row.id: [] for row in rows}
        # Вытаскиваем группы для удостоверений
        cert_sections = CertSections.objects.filter(
            certification__in=ids_certs.keys()).values('certification',
                                                       'group', 'points')
        for cert_section in cert_sections:
            ids_certs[cert_section['certification']].append(cert_section)

        for row in rows:
            item = object_fields(row)
            item['sections'] = ids_certs.get(row.id, [])

            welding_view = 'ТТ'
            with_tt = False
            with_mk = False
            for section in item['sections']:
                if section['group'] == 12:
                    with_mk = True
                else:
                    with_tt = True
            if with_mk:
                welding_view = 'МК'
            if with_mk and with_tt:
                welding_view = 'ТТ/МК'
            item['certsections__group'] = welding_view
            item['actions'] = row.id
            result.append(item)
        if request.GET.get('page'):
            result = {
                'data': result,
                'last_page': mh.raw_paginator['total_pages'],
                'total_records': mh.raw_paginator['total_records'],
                'cur_page': mh.raw_paginator['cur_page'],
                'by': mh.raw_paginator['by'],
            }
        return JsonResponse(result, safe=False)
    template = '%stable.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 2
0
def edit_holding_kss(request,
                     action: str,
                     row_id: int = None,
                     *args,
                     **kwargs):
    """Создание/редактирование проведений КСС"""
    mh_vars = holding_kss_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.select_related_add('welder')
    mh.select_related_add('welder__subject')
    mh.select_related_add('certification')
    context = mh.context
    context['extra_vars'] = insert_breadcrumbs
    context['welding_types'] = WELDING_TYPES
    context['materials'] = MATERIALS
    special_model_vars(mh, mh_vars, context)
    row = mh.get_row(row_id)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        if action in ('create', 'edit'):
            context['group_choices'] = CertSections.group_choices
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удален' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if not check_cert_for_welder(mh.row):
                context[
                    'error'] = 'Сварщик и удостоверение должны быть заполнены и удостоверение должно принадлежать выбранному сварщику'
        elif not mh.error and action == 'img' and request.FILES:
            mh.uploads()
    if not mh.error and mh.row:
        if not 'row' in context:
            context['row'] = object_fields(mh.row)
        context['row']['folder'] = mh.row.get_folder()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action == 'img':
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 3
0
def edit_certification(request,
                       action: str,
                       row_id: int = None,
                       *args,
                       **kwargs):
    """Создание/редактирование удостоверений"""
    mh_vars = certifications_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    context = mh.context
    context['extra_vars'] = insert_breadcrumbs
    context['welding_types'] = WELDING_TYPES
    special_model_vars(mh, mh_vars, context)
    row = mh.get_row(row_id)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        if action in ('create', 'edit'):
            context['group_choices'] = CertSections.group_choices
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
            context['cert_sections'] = row.certsections_set.select_related(
                'certification').all().order_by('position')
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удален' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        fill_cert_sections(request, mh.row)
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        fill_cert_sections(request, row)
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'

        elif not mh.error and action == 'img' and request.FILES:
            mh.uploads()
    if not mh.error and mh.row:
        if not 'row' in context:
            context['row'] = object_fields(mh.row)
        context['row']['folder'] = mh.row.get_folder()
        context['row']['thumb'] = mh.row.thumb()
        context['row']['imagine'] = mh.row.imagine()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action == 'img':
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 4
0
def show_phones(request, *args, **kwargs):
    """Вывод телефонов 8800
       :param request: HttpRequest
    """
    mh_vars = phones_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, disable_fas=True)

    filters_and_sorters = tabulator_filters_and_sorters(request)
    for rsorter in filters_and_sorters['sorters']:
        if not rsorter in ('cat', '-cat'):
            mh.order_by_add(rsorter)
    for rfilter in filters_and_sorters['filters']:
        mh.filter_add(rfilter)

    mh.context['fas'] = filters_and_sorters['params']
    # Чтобы получить возможность модифицировать фильтры и сортировщики
    mh.filters_and_sorters = filters_and_sorters

    context = mh.context

    # Условие под выборку определенной категории
    menu_filter = filters_and_sorters['params'].get('filters', {})
    if 'cat' in menu_filter:
        ids_phones = Phones.objects.filter(
            menu=menu_filter['cat']).values_list('id', flat=True)
        ids_phones = list(ids_phones)
        mh.filter_add(Q(pk__in=ids_phones))

    special_model_vars(mh, mh_vars, context)
    # -----------------------------
    # Вся выборка только через аякс
    # -----------------------------
    if request.is_ajax():
        only_fields = (
            'id',
            'name',
            'phone',
            'img',
            'is_active',
            'position',
        )
        rows = mh.standard_show()

        ids_phones = {row.id: None for row in rows}
        get_phones_menus(ids_phones)

        result = []
        for row in rows:
            item = object_fields(row, only_fields=only_fields)
            item['actions'] = row.id
            item['folder'] = row.get_folder()
            item['thumb'] = row.thumb()
            item['imagine'] = row.imagine()
            if ids_phones[row.id]:
                item['cat'] = ids_phones[row.id]
            result.append(item)
        if request.GET.get('page'):
            result = {
                'data': result,
                'last_page': mh.raw_paginator['total_pages'],
                'total_records': mh.raw_paginator['total_records'],
                'cur_page': mh.raw_paginator['cur_page'],
                'by': mh.raw_paginator['by'],
            }
        return JsonResponse(result, safe=False)
    template = '%stable.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 5
0
def show_joints(request, *args, **kwargs):
    """Вывод стыков"""
    mh_vars = joints_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP)
    context = mh.context
    context['state_choices'] = WELDING_JOINT_STATES
    context['welding_type_choices'] = WELDING_TYPES
    context['material_choices'] = MATERIALS
    context['join_types'] = JOIN_TYPES
    context['welding_conn_view_choices'] = Joint.welding_conn_view_choices
    special_model_vars(mh, mh_vars, context)

    # -----------------------------
    # Вся выборка только через аякс
    # -----------------------------
    if request.is_ajax():
        only_fields = (
            'id',
            'name',
            'img',
            'diameter',
            'side_thickness',
            'welding_type',
            'material',
            'join_type_from',
            'join_type_to',
            'welding_conn_view',
            'dinc',
            'welding_date',
            'welding_joint__state',
            'line__name',
            'line__titul__name',
            #'line__titul__subject__name',
            #'line__titul__subject__company__name',
        )
        rows = mh.standard_show(
            only_fields=only_fields,
            related_fields=('welding_joint', ),
        )
        result = []
        fk_keys = {
            'line': ('name', ),
            'titul': ('name', ),
            #'subject': ('name', ),
            #'company': ('name', ),
            'welding_joint': ('state', ),
        }
        ids_stigmas = {row.id: [] for row in rows}
        stigmas = JointWelder.objects.select_related('welder').filter(
            joint__in=ids_stigmas.keys()).values('joint', 'welder__stigma')
        for stigma in stigmas:
            ids_stigmas[stigma['joint']].append(stigma['welder__stigma'])
        for row in rows:
            item = object_fields(
                row,
                only_fields=only_fields,
                fk_only_keys=fk_keys,
                related_fields=('welding_joint', ),
            )
            item['stigma'] = []
            if row.id in ids_stigmas:
                item['stigma'] = ids_stigmas[row.id]
            item['actions'] = row.id
            item['folder'] = row.get_folder()
            item['thumb'] = row.thumb()
            item['imagine'] = row.imagine()
            result.append(item)

        if request.GET.get('page'):
            dinc = mh.query.aggregate(Sum('dinc'))
            result = {
                'data': result,
                'last_page': mh.raw_paginator['total_pages'],
                'total_records': mh.raw_paginator['total_records'],
                'cur_page': mh.raw_paginator['cur_page'],
                'by': mh.raw_paginator['by'],
                'dinc': dinc['dinc__sum'],
            }

        return JsonResponse(result, safe=False)
    template = '%stable.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 6
0
def edit_joint(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование стыков"""
    mh_vars = joints_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    context = mh.context
    context['state_choices'] = WELDING_JOINT_STATES
    context['welding_type_choices'] = WELDING_TYPES
    context['material_choices'] = MATERIALS
    context['diameters'] = DIAMETERS
    context['join_types'] = JOIN_TYPES
    context['welding_conn_view_choices'] = Joint.welding_conn_view_choices
    special_model_vars(mh, mh_vars, context)
    row = mh.get_row(row_id)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))

    if request.method == 'GET':
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
            context['welders'] = row.get_welders()
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удален' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        can_edit = True

        if row and hasattr(row, 'welding_joint') and row.welding_joint.state:
            state = row.welding_joint.state
            if state > 1:
                can_edit = False
                context[
                    'error'] = 'Нельзя отредактировать стык со статусом %s' % row.welding_joint.get_state_display(
                    )
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        update_welding_join_welders(request, mh)
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit' and can_edit:
                if mh.permissions['edit']:
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        update_welding_join_welders(request, mh)
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'

        elif not mh.error and action == 'img' and request.FILES:
            mh.uploads()
    if not mh.error and mh.row:
        if not 'row' in context:
            context['row'] = object_fields(mh.row)
        context['row']['folder'] = mh.row.get_folder()
        context['row']['thumb'] = mh.row.thumb()
        context['row']['imagine'] = mh.row.imagine()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action == 'img':
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 7
0
def edit_line(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование линий"""
    mh_vars = lines_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    context = mh.context
    # Права на файлы к линии
    context['files_permissions'] = get_user_permissions(request.user, LineFile)
    special_model_vars(mh, mh_vars, context)
    row = mh.get_row(row_id)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
            context['files'] = row.get_files()
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удален' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        pass_fields = (
            'new_joints',
            'in_progress_joints',
            'repair_joints',
            'complete_joints',
            'complete_dinc',
        )
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'

        elif action == 'file' and request.FILES:
            # Загрузка файла в LineFile
            mh.files_add('path')
            new_file = Files.objects.create(
                desc=mh.row.name,
                name=request.FILES['path'].name,
            )
            mh.uploads(row=new_file)
            if new_file.path:
                line_file = LineFile.objects.create(
                    line=mh.row,
                    file=new_file,
                )
                new_file.update_mimetype()
                context['success'] = 'Файл загружен'
                context['file'] = {
                    'id': line_file.id,
                    'path': new_file.path,
                    'name': new_file.name,
                    'mime': new_file.mime,
                    'folder': new_file.get_folder(),
                }
            else:
                new_file.delete()
                context['error'] = 'Не удалось загрузить файл'

        elif not mh.error and action == 'img' and request.FILES:
            mh.uploads()
    if not mh.error and mh.row:
        if not 'row' in context:
            context['row'] = object_fields(mh.row)
        context['row']['folder'] = mh.row.get_folder()
        context['row']['thumb'] = mh.row.thumb()
        context['row']['imagine'] = mh.row.imagine()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action in ('img', 'file'):
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 8
0
def edit_product_pvalue(request,
                        action: str,
                        row_id: int = None,
                        *args,
                        **kwargs):
    """Добавление/удаление свойства к товару
       Аяксовый метод
       :param request: HttpRequest
       :param action: действие
       :param row_id: ид ProductsProperties
    """
    result = {}
    mh_vars = products_pvalues_vars.copy()
    mh_vars['select_related_list'] = ['prop', 'prop__prop']
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.get_permissions(Products)  # Права от товаров/услуг
    context = mh.context
    row = mh.get_row(row_id)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))

    special_model_vars(mh, mh_vars, context)

    if request.method == 'GET':
        if action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удалено' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        # Обновляем линковку
        prop = None
        prop_id = request.POST.get('prop_id')
        if prop_id:
            prop = Property.objects.filter(pk=prop_id).first()

        pvalue = None
        pvalue_id = request.POST.get('pvalue_id')
        if pvalue_id:
            pvalue = PropertiesValues.objects.filter(pk=pvalue_id).first()

        product = None
        product_id = request.POST.get('product')
        if product_id:
            product = Products.objects.filter(pk=product_id).first()

        new_tag = request.POST.get('new_tag', '')
        new_tag = new_tag.strip()
        if prop and new_tag and not pvalue:
            pvalue = PropertiesValues.objects.filter(
                prop=prop, str_value=new_tag).first()
            if not pvalue and mh.permissions['create']:
                pvalue = PropertiesValues()
                pvalue.prop = prop
                pvalue.str_value = new_tag
                pvalue.save()

        if action == 'create' or (action == 'edit' and row):

            analog = ProductsProperties.objects.filter(
                product=product,
                prop=pvalue,
            )
            if row:
                analog = analog.exclude(pk=row.id)
            if analog:
                if analog:
                    context[
                        'error'] = 'Такое свойство уже присвоено этому товару'
            elif action == 'create' and product and pvalue:
                if mh.permissions['create'] and prop:
                    row = ProductsProperties.objects.create(
                        product=product,
                        prop=pvalue,
                    )
                    context['success'] = 'Данные успешно записаны'
                    context['row'] = {'id': row.id}
                else:
                    context['error'] = 'Недостаточно прав'
            elif action == 'edit' and row and product and product.id == row.product_id:
                if mh.permissions['edit']:
                    if pvalue:
                        row.prop = pvalue
                    row.save()
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            else:
                context['error'] = 'Произошла ошибка'
        if row:
            context['row'] = {
                'id': row.id,
                'prop_id': row.prop.prop.id,
                'pvalue_id': row.prop.id,
                'name': row.prop.prop.name,
                'is_active': row.prop.prop.is_active,
                'position': row.prop.prop.position,
                'value': row.prop.str_value,
            }
    return JsonResponse(context, safe=False)
Ejemplo n.º 9
0
def edit_prop(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование свойства для товара"""
    mh_vars = props_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.get_permissions(Products)  # Права от товаров/услуг
    row = mh.get_row(row_id)
    context = mh.context
    special_model_vars(mh, mh_vars, context)

    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        if action in ('create', 'edit'):
            context['ptypes'] = Property.ptype_choices
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
            # Значения свойства
            context['pvalues'] = [
                object_fields(prop, pass_fields=('prop', ))
                for prop in mh.row.propertiesvalues_set.all()
            ]
            context['pvalues_ends'] = analyze_digit(len(context['pvalues']),
                                                    end=('запись', 'записей',
                                                         'записи'))

        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удалено' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
        elif action == 'pvalue' and row:
            result = {}
            if mh.permissions['drop']:
                drop_pvalue = request.GET.get('drop_pvalue')
                if drop_pvalue:
                    result['drop_pvalue'] = drop_pvalue
                    pvalue = PropertiesValues.objects.filter(
                        prop=row, pk=drop_pvalue).first()
                    if pvalue:
                        pvalue.delete()
                result['success'] = 'Значение свойства удалено'
            else:
                result['error'] = 'Недостаточно прав'
            return JsonResponse(result, safe=False)

    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    mh.save_row()
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
        elif action == 'img' and request.FILES:
            mh.uploads()
        elif action == 'pvalue' and row:
            result = {}
            pk = request.POST.get('id')
            value = request.POST.get('value')
            if value:
                value = value.strip()
            is_active = request.POST.get('is_active')
            prop = PropertiesValues(prop=row)
            if pk:
                analog = PropertiesValues.objects.filter(pk=pk,
                                                         prop=row).first()
                if analog:
                    prop = analog
            else:
                # Дубли нам не нужны
                analog = PropertiesValues.objects.filter(prop=row,
                                                         str_value=value)
                if analog:
                    result['error'] = 'Вы создаете дубликат'
                    return JsonResponse(result, safe=False)
            prop.str_value = value
            prop.is_active = True if is_active else False

            if mh.permissions['edit']:
                result['success'] = 'Данные успешно записаны'
                prop.save()
            else:
                result['error'] = 'Недостаточно прав'
            result['row'] = object_fields(prop, pass_fields=('prop', ))
            return JsonResponse(result, safe=False)
    if mh.row:
        kwargs = {'action': 'pvalue', 'row_id': mh.row.id}
        context['url_edit_pvalue'] = reverse('%s:%s' % (CUR_APP, 'edit_prop'),
                                             kwargs=kwargs)
        context['row'] = object_fields(mh.row, pass_fields=('password', ))
        context['row']['folder'] = mh.row.get_folder()
        context['row']['thumb'] = mh.row.thumb()
        context['row']['imagine'] = mh.row.imagine()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action == 'img':
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 10
0
def edit_photo(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование фото товара"""
    mh_vars = photos_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.get_permissions(Products)  # Права от товаров/услуг
    row = mh.get_row(row_id)
    context = mh.context
    special_model_vars(mh, mh_vars, context)
    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action == 'edit' and row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удалено' % (mh.singular_obj, )
            else:
                context['error'] = 'Недостаточно прав'
    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    mh.save_row()
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
        elif action == 'update' and row:
            if mh.permissions['edit']:
                row.name = request.POST.get('name')
                row.save()
                context['success'] = 'Данные успешно записаны'
            else:
                context['error'] = 'Недостаточно прав'
        elif action == 'img' and request.FILES:
            mh.uploads()
    if mh.row:
        context['row'] = object_fields(mh.row, pass_fields=('password', ))
        context['row']['folder'] = mh.row.get_folder()
        context['row']['thumb'] = mh.row.thumb()
        context['row']['imagine'] = mh.row.imagine()
        context['redirect'] = mh.get_url_edit()
    if request.is_ajax() or action == 'img':
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    return render(request, template, context)
Ejemplo n.º 11
0
def show_cats_products(request, *args, **kwargs):
    """Вывод привязок товаров к рубрикам"""
    mh_vars = products_cats_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP)
    mh.select_related_add('product')
    #mh.select_related_add('cat')
    context = mh.context
    # Условие под выборку определенной категории
    if request.method == 'GET':
        cat_id = request.GET.get('cat_id')
        if cat_id:
            cat = None
            try:
                cat_id = int(cat_id)
            except ValueError:
                logger.exception('cat_id not int')
                cat_id = None
            if cat_id:
                cat = Blocks.objects.filter(pk=cat_id).first()
                if cat:
                    mh.filter_add(Q(cat=cat))
            if not cat:
                mh.filter_add(Q(pk=0))
    special_model_vars(mh, mh_vars, context)
    # -----------------------------
    # Вся выборка только через аякс
    # -----------------------------
    if request.is_ajax():
        only_fields = (
            'id',
            'product__id',
            'product__name',
            'product__code',
            #'cat__name'
        )
        rows = mh.standard_show(only_fields=only_fields)
        result = []
        fk_keys = {
            'product': ('id', 'name', 'code'),
            #'cat': ('name', ),
        }
        edit_urla = reverse('%s:%s' % (CUR_APP, 'edit_product'),
                            kwargs={
                                'action': 'edit',
                                'row_id': 0
                            })
        for row in rows:
            item = object_fields(
                row,
                only_fields=only_fields,
                fk_only_keys=fk_keys,
            )
            item['actions'] = row.id
            item['edit_urla'] = edit_urla.replace('/0/', '/%s/' % row.id)
            #item['folder'] = row.get_folder()
            #item['thumb'] = row.thumb()
            #item['imagine'] = row.imagine()
            result.append(item)
        if request.GET.get('page'):
            result = {
                'data': result,
                'last_page': mh.raw_paginator['total_pages'],
                'total_records': mh.raw_paginator['total_records'],
                'cur_page': mh.raw_paginator['cur_page'],
                'by': mh.raw_paginator['by'],
            }
        return JsonResponse(result, safe=False)
    template = '%stable.html' % (mh.template_prefix, )
    return render(request, template, context)