예제 #1
0
def spam_tables_images(request, *args, **kwargs):
    """Работа с изображениями через redactor"""
    result = {}
    folder = 'sp-images'  # Чтобы не фигурировало spam
    make_folder(folder)
    mh_vars = spam_tables_vars.copy()
    # Список изображений:
    #[{ "thumb": "/img/1m.jpg", "image": "/img/1.jpg", "title": "Image 1", "folder": "Folder 1" }, ... ]
    # Ответ по загрузке:
    # { "filelink": "/images/img.jpg" }
    perms = get_user_permissions(request.user, mh_vars['model'])
    if request.FILES and perms['edit']:
        result['filelink'] = '/static/img/ups.png'
        f = request.FILES.get('file')
        if f:
            dest = os.path.join(folder, f.name)
            if catch_file(f, dest):
                result['filelink'] = '/media/%s' % dest
    elif request.method == 'GET':
        result = []
        items = ListDir(folder)
        for item in items:
            path = os.path.join(folder, item)
            img = '/media/%s' % path
            if isForD(path) == 'file' and extension(item):
                result.append({
                    'thumb': img,
                    'image': img,
                    'title': '',
                    'folder': folder,
                })
    return JsonResponse(result, safe=False)
예제 #2
0
def show_lines(request, *args, **kwargs):
    """Вывод линий"""
    only_fields = (
        'id',
        'name',
        'img',
        'project_joint_count',
        'project_dinc',
        'new_joints',
        'in_progress_joints',
        'repair_joints',
        'complete_joints',
        'complete_dinc',
        'titul__name',
    )
    fk_keys = {
        'titul': ('name', ),
    }
    # Права на файлы к линии
    extra_vars = {
        'files_permissions': get_user_permissions(request.user, LineFile),
    }
    return show_view(
        request,
        model_vars=lines_vars,
        cur_app=CUR_APP,
        only_fields=only_fields,
        fk_only_keys=fk_keys,
        extra_vars=extra_vars,
    )
예제 #3
0
def update_welding_joint_state(request, mh):
    """Обновление статуса заявки
       Вспомогательная функция для сохранения
    """
    permissions = get_user_permissions(request.user, WeldingJointState)
    if not mh.row.id:
        return
    state = mh.row.state
    new_state = request.POST.get('new_state')
    if new_state:
        new_state = get_welding_joint_state(new_state)
    # Новая => В работе
    new2progress = state == 1 and new_state == 2 and permissions['edit']
    # Новая => Отклоненнные заявки
    # В работе => Отклоненные заявки
    new2rejected = state in (1, 2) and new_state == 5 and permissions['edit']
    # Отклоненная => В работе
    rejected2new = state == 5 and new_state == 1 and permissions[
        'repair_completed']
    # В работе => В ремонте
    progress2repair = state == 2 and new_state == 4 and permissions['edit']
    # В ремонте => Новая
    repair2new = state == 4 and new_state == 1 and permissions[
        'repair_completed']
    # В работе => Готово
    progress2complete = state == 2 and new_state == 3 and permissions['edit']
    # Новый стык
    none2new = state is None and new_state == 1
    # -----------------
    # Установить статус
    # -----------------
    if new2progress or progress2repair or repair2new or progress2complete or none2new or new2rejected or rejected2new:
        WeldingJointState.objects.create(
            from_state=state,
            to_state=new_state,
            user=request.user,
            welding_joint=mh.row,
        )
        params = {'state': new_state}
        if not mh.row.receiver and not none2new:
            params['receiver'] = request.user
        if progress2repair:
            params['repair'] = mh.row.repair or 0
            params['repair'] += 1
            # Создаем новое заключение
            repair_conclusion = JointConclusion.objects.create(
                welding_joint=mh.row, repair=params['repair'])
        WeldingJoint.objects.filter(pk=mh.row.id).update(**params)
        for k, v in params.items():
            setattr(mh.row, k, v)
        mh.row.request_number = mh.row.update_request_number()
        # ------------------------------------
        # Пересчитать процент готовности линии
        # ------------------------------------
        if mh.row.joint and mh.row.joint.line:
            line = mh.row.joint.line
            recalc_joints(line)
        return True
    return False
예제 #4
0
def fast_props2cat(request):
    """Быстрое добавление свойств к товарам по рубрике
       :param request: HttpRequest
    """
    result = {}
    perms = get_user_permissions(request.user, props_vars['model'])
    if not request.method == 'POST' or not request.POST.get(
            'props2cat') or not perms['edit']:
        result['error'] = 'Недостаточно прав' if not perms[
            'edit'] else 'Нет данных для сохранения'
        return JsonResponse(result, safe=False)
    props2cat = request.POST.getlist('props2cat')
    cat_id = request.POST.get('cat')
    if not props2cat or not cat_id:
        result['error'] = 'Недостаточно данных'
        return JsonResponse(result, safe=False)
    props2cat = [int(prop_id) for prop_id in props2cat if prop_id]
    pcats = ProductsCats.objects.select_related('product').filter(cat=cat_id)

    pvalues = PropertiesValues.objects.filter(
        prop__in=props2cat).order_by('position')
    ids_pvalues = {}
    for pvalue in pvalues:
        if pvalue.prop_id in ids_pvalues:
            continue
        ids_pvalues[pvalue.prop_id] = pvalue

    props = Property.objects.filter(pk__in=ids_pvalues.keys())
    ids_props = {prop.id: prop for prop in props}

    for pcat in pcats:
        for prop_id in props2cat:
            if not prop_id in ids_props:
                logger.info('[ERROR]: prop not found %s' % prop_id)
            prop = ids_props[prop_id]
            # Любое значение свойства привязано
            analog = ProductsProperties.objects.filter(
                prop__prop=prop,
                product=pcat.product).aggregate(Count('id'))['id__count']
            if analog:
                continue
            # Нету нифуя - создаем свойство из первого значения св-ва
            pvalue = ids_pvalues[prop.id]
            ProductsProperties.objects.create(prop=pvalue,
                                              product=pcat.product)
    result['success'] = 'Данные успешно сохранены'
    return JsonResponse(result, safe=False)
예제 #5
0
def fast_create_props(request):
    """Быстрое создание свойств пачкой
       :param request: HttpRequest
    """
    result = {}
    perms = get_user_permissions(request.user, props_vars['model'])
    if not request.method == 'POST' or not request.POST.get(
            'props') or not perms['create']:
        result['error'] = 'Недостаточно прав' if not perms[
            'create'] else 'Нет данных для сохранения'
        return JsonResponse(result, safe=False)

    props = []
    props_count = request.POST.get('props', 0)
    try:
        props_count = int(props_count)
    except ValueError:
        return JsonResponse(result, safe=False)
    for i in range(props_count):
        props.append({
            'name': request.POST.get('name_%s' % i).strip(),
            'code': request.POST.get('code_%s' % i).strip(),
        })
    already_exists = 0
    created = 0
    for prop in props:
        if not prop['name']:
            continue
        code = prop['code'] or translit(prop['name'])
        analog = Property.objects.filter(code=code)
        if analog:
            already_exists += 1
            continue
        analog = Property.objects.create(name=prop['name'], code=code)
        created += 1
    result['success'] = 'Данные успешно сохранены'
    if already_exists:
        result['success'] += '<br>Уже найдено свойств: %s' % already_exists
        result['success'] += '<br>Добавлено новых свойств: %s' % created
    if not created:
        result['error'] = 'Не добавлено ни одного свойство'
    return JsonResponse(result, safe=False)
예제 #6
0
def translate_mode(request, *args, **kwargs):
    """Перевод текстов админки"""
    result = {}
    domain = get_domain(request, priority='session')

    # Если русский, то без перевода
    if domain.get('lang') == 'rus':
        result['error'] = 'Русский то не надо переводить!'
        if request.POST.get('old_value'):
            result['old_value'] = request.POST['old_value']
        return JsonResponse(result, safe=False)

    perms = get_user_permissions(request.user, UITranslate)
    if not perms['edit']:
        result['error'] = 'Недостаточно прав'
    elif not domain:
        result['error'] = 'Не выбран домен'
    else:
        domain_pk = domain.get('pk')
        class_name = request.POST.get('pk')
        value = request.POST.get('value', '')[:254]
        value = value.strip()
        analog = UITranslate.objects.filter(class_name=class_name,
                                            domain_pk=domain_pk).first()
        # Херим, если пустое поле
        if not value:
            if analog:
                analog.delete()
            result['success'] = 'Перевод удален'
            return JsonResponse(result, safe=False)
        if not analog:
            analog = UITranslate(class_name=class_name, domain_pk=domain_pk)
        analog.value = value
        analog.save()
        result['translate'] = object_fields(analog)
        result['success'] = 'Данные записаны'

    result['domain'] = domain
    return JsonResponse(result, safe=False)
예제 #7
0
def edit_conclusion(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование заключений (актов)"""
    mh_vars = conclusions_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.select_related_add('welding_joint')
    mh.select_related_add('welding_joint__joint')
    mh.select_related_add('vik_controller')
    mh.select_related_add('vik_director')
    mh.select_related_add('rk_defectoscopist1')
    mh.select_related_add('rk_defectoscopist2')
    mh.select_related_add('rk_defectoscopist3')
    mh.select_related_add('pvk_director')
    mh.select_related_add('pvk_defectoscopist')
    mh.select_related_add('uzk_defectoscopist1')
    mh.select_related_add('uzk_defectoscopist2')
    mh.select_related_add('uzk_defectoscopist3')
    mh.select_related_add('uzk_operator')
    # pdf
    mh.select_related_add('welding_joint__joint__line')
    mh.select_related_add('welding_joint__joint__line__titul')
    mh.select_related_add('welding_joint__joint__line__titul__subject')
    mh.select_related_add('welding_joint__joint__line__titul__subject__company')
    row = mh.get_row(row_id)
    context = mh.context

    # Права на файлы к заключению
    context['files_permissions'] = get_user_permissions(request.user, JointConclusionFile)
    context['welding_joint_state_permissions'] = get_user_permissions(request.user, WeldingJointState)

    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        # ---------------------------------------------------
        # Вытаскиваем заявку, по которой создается заключение
        # ---------------------------------------------------
        welding_joint_str = request.GET.get('welding_joint')
        if welding_joint_str and not mh.row:
            welding_joint = WeldingJoint.objects.select_related('joint').filter(pk=welding_joint_str).first()
            if not welding_joint:
                return redirect('%s?error=not_found' % (mh.root_url, ))

            welding_joint.join_type_from = welding_joint.joint.get_join_type_from_display()
            welding_joint.join_type_to = welding_joint.joint.get_join_type_to_display()
            welding_joint.material = welding_joint.joint.get_material_display()
            welding_joint.welding_conn_view = welding_joint.joint.get_welding_conn_view_display()
            context['welding_joint'] = welding_joint_fields(welding_joint)
            context['welders'] = {}
            if welding_joint.joint:
                context['welders'] = welding_joint.joint.get_welders()
            context['welding_type'] = '?'
            for item in WELDING_TYPE_DESCRIPTIONS:
                if welding_joint.joint.welding_type == item[0]:
                    context['welding_type'] = item[1]
                    break

        if action in ('create', 'edit'):
            context['welding_type_descriptions'] = WELDING_TYPE_DESCRIPTIONS
            context['conclusion_states'] = CONCLUSION_STATES
            context['pvk_control_choices'] = JointConclusion.pvk_control_choices
            context['state_choices'] = WELDING_JOINT_STATES

        if action in ('edit', 'pdf_vik', 'pdf_rk', 'pdf_pvk', 'pdf_uzk'):
            context['welding_type'] = '%s и %s' % (
                WELDING_TYPE_DESCRIPTIONS[0][1],
                WELDING_TYPE_DESCRIPTIONS[1][1],
            )
            for item in WELDING_TYPE_DESCRIPTIONS:
                if row.welding_joint.joint.welding_type == item[0]:
                    context['welding_type'] = item[1]
                    break
            context['rk_frames'] = row.rkframes_set.all().order_by('position')
            # Номера заключений
            context.update(row.get_conclusion_numbers(row.welding_joint))

        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),
            })
            if row.welding_joint:
                context['welding_joint'] = welding_joint_fields(row.welding_joint)
                context['all_conclusions'] = JointConclusion.objects.filter(welding_joint=row.welding_joint).values_list('id', flat=True).order_by('repair')
            context['files'] = row.get_files()
            context['welders'] = {}
            if row.welding_joint.joint:
                context['welders'] = row.welding_joint.joint.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 action in ('pdf_vik', 'pdf_rk', 'pdf_pvk', 'pdf_uzk') and row:
            pdf_type = action.replace('pdf_', '')
            context.update({
                'row': row,
                'logo': full_path('misc/logo_standard.png'),
                'pdf_type': pdf_type,
                'joint': row.welding_joint.joint,
                'today': datetime.datetime.today(),
            })
            context['welders'] = {}
            if row.welding_joint and row.welding_joint.joint:
                context['welders'] = row.welding_joint.joint.get_welders()
            template = 'pdf/conclusion_%s_form.html' % pdf_type
            return render_pdf(
                request,
                template = template,
                context = context,
                download = False,
                fname = 'conclusion_%s_%s' % (
                    pdf_type,
                    row.welding_joint.joint.id,
                )
            )
    elif request.method == 'POST':
        # Общий статус ставится в save по заключениям
        pass_fields = ('state', 'repair')
        mh.post_vars(pass_fields=pass_fields)
        if action == 'create' or (action == 'edit' and row):
            # ---------------------------------
            # Без заявки стыка нельзя сохранить
            # ---------------------------------
            welding_joint = None
            welding_joint_str = mh.row_vars.get('welding_joint')
            if welding_joint_str:
                welding_joint = WeldingJoint.objects.filter(pk=welding_joint_str).first()
            if not welding_joint:
                context['error'] = 'Выберите заявку на стык'
                return JsonResponse(context)
            else:
                analog = JointConclusion.objects.filter(welding_joint=welding_joint).order_by('-repair').first()
                if not mh.row and analog:
                    context['error'] = 'Вы создаете дубликат, переадресовываем на заключение...'
                    link = reverse(
                        '%s:%s' % (CUR_APP, mh_vars['edit_urla']),
                        kwargs={'action': 'edit', 'row_id': analog.id}
                    )
                    context['redirect_on_error'] = link
                    return JsonResponse(context)

            if action == 'create':
                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                        fill_rk_frames(request, mh.row)
                else:
                    context['error'] = 'Недостаточно прав'
            if action == 'edit':
                if mh.permissions['edit']:
                    # -----------------------
                    # Изменить заявку на стык
                    # не даем в заключении
                    # -----------------------
                    mh.save_row(set_fields={'welding_joint': mh.row.welding_joint})
                    if mh.error:
                        context['error'] = mh.error
                    else:
                        context['success'] = 'Данные успешно записаны'
                        fill_rk_frames(request, mh.row)
                else:
                    context['error'] = 'Недостаточно прав'
        elif action == 'file' and request.FILES:
            # Принятую заявку не редактируем
            if mh.row.welding_joint.state == 3:
                context['error'] = 'Нельзя изменить принятую заявку'
            else:
                # Загрузка файла в JointConclusionFile
                mh.files_add('path')
                new_file = Files.objects.create(
                    desc = mh.row.welding_joint.request_number,
                    name = request.FILES['path'].name,
                )
                mh.uploads(row=new_file)
                if new_file.path:
                    joint_file = JointConclusionFile.objects.create(
                        joint_conclusion=mh.row,
                        file=new_file, )
                    new_file.update_mimetype()
                    context['success'] = 'Файл загружен'
                    context['file'] = {
                        'id': joint_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'] = 'Не удалось загрузить файл'
    if not mh.error and mh.row:
        if not 'row' in context:
            context['row'] = object_fields(mh.row)
        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)
예제 #8
0
def settings(request, app: str = 'flatcontent'):
    """Настройки для разделов
       :param app: приложение
    """
    result = {}
    app_label = '%s_' % app
    permissions = get_user_permissions(request.user, Config)
    # настройки могут быть зависимы или независимы от пользователя
    # 'user_defined': False, # Не зависят от пользователя
    # 'user_defined': True, # Зависят от пользователя
    settings_store = {
        'flatcontent': {
            'singular_obj': 'Раздел "Контент" и стат. странички',
            'rp_singular_obj': 'раздела "Контент" и стат. страничек',
            'name': 'Настройки раздела "Контент" и стат. страничек',
            'user_defined': False,
        },
        'spamcha': {
            'singular_obj': 'Раздел "Почта"',
            'rp_singular_obj': 'раздела "Почта"',
            'name': 'Настройки почты',
            'user_defined': True,
        },
        'languages': {
            'singular_obj': 'Раздел "Мультидомен"',
            'rp_singular_obj': 'раздела "Мультидомен"',
            'name': 'Настройки раздела "Мультидомен"',
            'user_defined': True,
        },
    }
    name = settings_store[app]['name']
    user_defined = settings_store[app]['user_defined']
    root_url = reverse('main_functions:settings', args=[app])
    context = {
        'app': app,
        'title': name,
        'singular_obj': settings_store[app]['singular_obj'],
        'rp_singular_obj': settings_store[app]['rp_singular_obj'],
        'user_defined': user_defined,
        'breadcrumbs': [{
            'name': name,
            'link': root_url,
        }],
        'menu': main_vars['menu'],
        'submenu': app,
    }
    template = '%s_settings.html' % (app, )
    if request.method == 'POST':
        settings = []
        settings_count = request.POST.get('settings', 0)
        try:
            settings_count = int(settings_count)
        except ValueError:
            settings_count = 0
        for i in range(settings_count):
            settings.append({
                'name': request.POST.get('name_%s' % i),
                'attr': request.POST.get('attr_%s' % i),
                'value': request.POST.get('value_%s' % i),
            })
        if permissions['edit'] or user_defined:
            configs = Config.objects.filter(attr__startswith=app_label)
            if user_defined:
                configs = configs.filter(user=request.user)
            configs.delete()
            for setting in settings:
                if not setting['attr']:
                    continue
                if not setting['attr'].startswith(app_label):
                    setting['attr'] = '%s%s' % (app_label, setting['attr'])
                analog = Config(attr=setting['attr'])
                analog.name = setting['name']
                analog.value = setting['value']
                if user_defined:
                    analog.user = request.user
                analog.save()
            result['success'] = 'Данные успешно сохранены'
        else:
            result['error'] = 'Недостаточно прав'
        return JsonResponse(result, safe=False)

    configs = Config.objects.filter(attr__startswith='%s_' % app)
    if user_defined:
        configs = configs.filter(user=request.user)
    context['rows'] = configs
    for row in context['rows']:
        if row.attr and row.attr.startswith(app):
            row.attr = row.attr.split(app_label, 1)[1]
    return render(request, template, context)
예제 #9
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)
예제 #10
0
def show_welding(request, *args, **kwargs):
    """Вывод бланк-заявок
       :param request: HttpRequest
    """
    state = kwargs.get('state')

    mh_vars = welding_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP)
    mh.select_related_add('joint')
    mh.select_related_add('joint__line')
    mh.select_related_add('joint__line__titul')
    #mh.select_related_add('joint__line__titul__subject')
    #mh.select_related_add('joint__line__titul__subject__company')
    #mh.select_related_add('joint_conclusion')
    context = mh.context
    context['welding_joint_state_permissions'] = get_user_permissions(
        request.user, WeldingJointState)

    context['repair_choices'] = WeldingJoint.repair_choices
    context['workshift_choices'] = WeldingJoint.workshift_choices
    context['control_choices'] = WeldingJoint.control_choices
    context['welding_type_choices'] = WELDING_TYPES
    context['category_choices'] = WeldingJoint.category_choices
    context['conclusion_states'] = CONCLUSION_STATES
    context['material_choices'] = MATERIALS
    context['join_types'] = JOIN_TYPES
    context['welding_conn_view_choices'] = Joint.welding_conn_view_choices
    context['state_choices'] = WELDING_JOINT_STATES

    if state and not 'state' in context['fas']['filters']:
        context['fas']['filters']['state'] = get_welding_joint_state(state)
        context['submenu'] = '%s_%s' % (mh_vars['submenu'], state)
    #if 'joint__welding_date' in context['fas']['filters']:
    #fdate = str_to_date(context['fas']['filters']['joint__welding_date'])
    #context['fas']['filters']['joint__welding_date'] = fdate
    #print(mh.filters)
    #for i, fkey in enumerate(mh.filters_and_sorters['filters']):
    #    if fkey == 'joint__welding_date':
    #        mh.filters_and_sorters['filters'][i] = fdate

    # -----------------------------
    # Вся выборка только через аякс
    # -----------------------------
    if request.is_ajax():
        only_fields = (
            'id',
            'request_number',
            'request_control_date',
            'joint__name',
            'joint__line__name',
            'joint__line__titul__name',
            #'joint__line__titul__subject__name',
            #'joint__line__titul__subject__company__name',
            'joint__diameter',
            'joint__side_thickness',
            'joint__welding_type',
            'joint__welding_date',
            'joint__material',
            'joint__join_type_from',
            'joint__join_type_to',
            'joint__welding_conn_view',
            'repair',
            'workshift',
            'control_type',
            'category',
            'control_result',
            'notice',
            'state',
        )
        rows = mh.standard_show(only_fields=only_fields)
        result = []
        fk_keys = {
            'joint': ('name', 'diameter', 'side_thickness', 'welding_date',
                      'material', 'join_type_from', 'join_type_to',
                      'welding_conn_view', 'welding_type'),
            'line': ('name', ),
            'titul': ('name', ),
            #'subject': ('name', ),
            #'company': ('name', ),
        }
        # У нас может быть много заключений на одну заявку,
        # поэтому надо вытащить последнее заключение по ремонту
        # именно из него будем выводить дефекты
        #conclusions = {row.joint_conclusion.id: [] for row in rows if hasattr(row, 'joint_conclusion')}
        ids_rows = [row.id for row in rows]
        conclusions = JointConclusion.objects.filter(
            welding_joint__in=ids_rows).order_by('-repair')
        last_conclusion_arr = {}
        ids_conclusions = {}
        for conclusion in conclusions:
            if conclusion.welding_joint_id in last_conclusion_arr:
                continue
            last_conclusion_arr[conclusion.welding_joint_id] = conclusion
            ids_conclusions[conclusion.id] = []

        rk_frames = []
        if ids_conclusions:
            rk_frames = RKFrames.objects.filter(
                joint_conclusion__in=ids_conclusions.keys(), ).exclude(
                    state=1).values('joint_conclusion', 'defects', 'notice')
        for rk_frame in rk_frames:
            ids_conclusions[rk_frame['joint_conclusion']].append('%s%s' % (
                rk_frame['defects'],
                ' (%s)' % rk_frame['notice'] if rk_frame['notice'] else '',
            ))
        for row in rows:
            item = object_fields(
                row,
                only_fields=only_fields,
                fk_only_keys=fk_keys,
            )
            #related_fields=('joint_conclusion', ))
            item['actions'] = row.id
            if row.id in last_conclusion_arr:
                conclusion = last_conclusion_arr[row.id]
                item['joint_conclusion'] = object_fields(conclusion,
                                                         only_fields=(
                                                             'date',
                                                             'state',
                                                             'vik_defects',
                                                             'pvk_defects',
                                                             'uzk_defects',
                                                         ))
                if conclusion.id in ids_conclusions:
                    item['joint_conclusion']['rk_frames'] = ids_conclusions[
                        conclusion.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, )
    context['url_form'] = reverse('%s:%s' % (CUR_APP, mh_vars['create_urla']),
                                  kwargs={'action': 'form'})
    return render(request, template, context)
예제 #11
0
def edit_welding(request, action: str, row_id: int = None, *args, **kwargs):
    """Создание/редактирование бланк-заявок
       :param request: HttpRequest
       :param action: действие над объектом (создание/редактирование/удаление)
       :param row_id: ид записи
    """
    mh_vars = welding_vars.copy()
    mh = create_model_helper(mh_vars, request, CUR_APP, action)
    mh.select_related_add('joint')
    mh.select_related_add('joint__line')
    mh.select_related_add('joint__line__titul')
    mh.select_related_add('joint__line__titul__subject')
    mh.select_related_add('joint__line__titul__subject__company')
    mh.select_related_add('requester')
    mh.select_related_add('receiver')
    row = mh.get_row(row_id)
    context = mh.context
    # Права на файлы к заявке
    context['files_permissions'] = get_user_permissions(
        request.user, WeldingJointFile)
    context['welding_joint_state_permissions'] = get_user_permissions(
        request.user, WeldingJointState)
    context['repair_choices'] = WeldingJoint.repair_choices
    context['workshift_choices'] = WeldingJoint.workshift_choices
    context['control_choices'] = WeldingJoint.control_choices
    context['welding_type_choices'] = WELDING_TYPES
    context['category_choices'] = WeldingJoint.category_choices
    context['conclusion_states'] = CONCLUSION_STATES
    context['material_choices'] = MATERIALS
    context['join_types'] = JOIN_TYPES
    context['welding_conn_view_choices'] = Joint.welding_conn_view_choices
    context['state_choices'] = WELDING_JOINT_STATES
    context['today'] = datetime.datetime.today().strftime('%d.%m.%Y')

    if mh.error:
        return redirect('%s?error=not_found' % (mh.root_url, ))
    if request.method == 'GET':
        # ----------------------------------------------
        # Вытаскиваем узел, по которому создается заявка
        # ----------------------------------------------
        joint_str = request.GET.get('joint')
        if joint_str and not mh.row:
            joint = Joint.objects.select_related(
                'line',
                'line__titul',
                'line__base',
                #'line__titul__subject',
                #'line__titul__subject__company',
            ).filter(pk=joint_str).first()
            context['row'] = {
                'joint': object_fields(joint),
            }
            context['welders'] = joint.get_welders()
            if not joint:
                return redirect('%s?error=not_found' % (mh.root_url, ))
            # -------------------------------------
            # На один стык должна быть одна заявка,
            # если на данный стык уже есть заявка,
            # тогда переадресовываем на нее
            # -------------------------------------
            analog = WeldingJoint.objects.filter(joint=joint).first()
            if analog:
                link = reverse('%s:%s' % (CUR_APP, mh_vars['edit_urla']),
                               kwargs={
                                   'action': 'form',
                                   'row_id': analog.id
                               })
                return redirect(link)
        if action in ('edit', 'form', 'pdf') and row:
            if row.id:
                context['welders'] = {}
                if row.joint:
                    context['welders'] = row.joint.get_welders()
                if row.requester:
                    context['requester'] = {
                        'name': '%s' % row.requester.customuser,
                        'function': '%s' % row.requester.customuser.function,
                        'login': row.requester.username,
                        'id': row.requester.id,
                    }
                if row.receiver:
                    context['receiver'] = {
                        'name': '%s' % row.receiver.customuser,
                        'function': '%s' % row.receiver.customuser.function,
                        'login': row.receiver.username,
                        'id': row.receiver.id,
                    }
                context['files'] = row.get_files()
                if row.joint and row.joint.line:
                    context['total_joints'] = row.joint.line.get_total_joints()

        if action == 'create':
            mh.breadcrumbs_add({
                'link':
                mh.url_create,
                'name':
                '%s %s' % (mh.action_create, mh.rp_singular_obj),
            })
        elif action in ('edit', 'form') and mh.row:
            mh.breadcrumbs_add({
                'link':
                mh.url_edit,
                'name':
                '%s %s' % (mh.action_edit, mh.rp_singular_obj),
            })
            context['joint'] = mh.row.joint
            context['state'] = mh.row.get_state_display()
            # Берем по последнему ремонту
            context['joint_conclusion'] = JointConclusion.objects.filter(
                welding_joint=mh.row).order_by('-repair').first()
        elif action == 'drop' and row:
            if mh.permissions['drop']:
                row.delete()
                mh.row = None
                context['success'] = '%s удален' % (mh.singular_obj, )
                # Пересчитать готовность линии
                recalc_joints(row.joint.line)
            else:
                context['error'] = 'Недостаточно прав'
        elif action == 'pdf' and row:
            context['row'] = row
            context['logo'] = full_path('misc/logo_standard.png')
            return render_pdf(
                request,
                template='pdf/welding_form.html',
                context=context,
                download=False,
                fname='welding_joint_%s' % row.joint.id,
            )
        elif action == 'conclusion' and row:
            # Если по акту нет заключения,
            # переадресовываем на создание,
            # Если есть - берем последнее по ремонту
            conclusion = JointConclusion.objects.filter(
                welding_joint=row).order_by('-repair').first()
            # -------------------------------
            # Ссылки не импортирую тупо меняю
            # welding на conclusion
            # -------------------------------
            create_conclusion = mh_vars['create_urla'].replace(
                'welding', 'conclusion')
            edit_conclusion = mh_vars['edit_urla'].replace(
                'welding', 'conclusion')
            if conclusion:
                link = reverse('%s:%s' % (CUR_APP, edit_conclusion),
                               kwargs={
                                   'action': 'edit',
                                   'row_id': conclusion.id
                               })
                return redirect(link)
            link = reverse('%s:%s' % (CUR_APP, create_conclusion),
                           kwargs={'action': 'create'})
            return redirect('%s?welding_joint=%s' % (link, row.id))

    elif request.method == 'POST':
        pass_fields = ()
        mh.post_vars(pass_fields=pass_fields)
        if action in ('create', 'form') or (action == 'edit' and row):
            if action == 'create':
                # -------------------------
                # Создание пока что бреем,
                # используем form действие,
                # -------------------------
                assert False

                if mh.permissions['create']:
                    mh.row = mh.model()
                    mh.save_row()
                    update_welding_joint_state(request, mh)
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            elif action == 'edit' and mh.row:
                # ------------------------------
                # Редактирование пока что бреем,
                # используем form действие,
                # ------------------------------
                assert False

                if mh.permissions['edit']:
                    mh.save_row()
                    update_welding_joint_state(request, mh)
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'
            elif action == 'form':
                # Заявки в ремонте даем редактировать,
                # чтобы гондоны смогли хотя бы со второго
                # раза правильно подать, а кто то с пятого
                if mh.row and mh.row.state in (1,
                                               5) and mh.permissions['repair']:
                    mh.permissions['edit'] = True

                if mh.permissions['edit'] and mh.row:
                    # Принятую заявку не редактируем
                    if mh.row.state == 3:
                        context['error'] = 'Нельзя изменить принятую заявку'
                    else:
                        # -------------------------------
                        # Изменять на другой стык не даем
                        # 1 стык = 1 заявка
                        # -------------------------------
                        mh.save_row(set_fields={'joint': mh.row.joint})
                        update_welding_joint_state(request, mh)
                        context['success'] = 'Данные успешно записаны'
                elif mh.permissions['create'] and not mh.row:  # NOT!
                    # --------------------------
                    # Без стыка нельзя сохранить
                    # --------------------------
                    joint = None
                    joint_str = mh.row_vars.get('joint')
                    if joint_str:
                        joint = Joint.objects.filter(pk=joint_str).first()
                    if not joint:
                        context['error'] = 'Выберите стык'
                        return JsonResponse(context)
                    else:
                        analog = WeldingJoint.objects.filter(
                            joint=joint).first()
                        if analog:
                            context[
                                'error'] = 'Вы создаете дубликат, переадресовываем на заявку...'
                            link = reverse('%s:%s' %
                                           (CUR_APP, mh_vars['edit_urla']),
                                           kwargs={
                                               'action': 'form',
                                               'row_id': analog.id
                                           })
                            context['redirect_on_error'] = link
                            return JsonResponse(context)
                    mh.row = mh.model()
                    mh.save_row()
                    update_welding_joint_state(request, mh)
                    context['success'] = 'Данные успешно записаны'
                else:
                    context['error'] = 'Недостаточно прав'

            # Если не удалось сохранить, значит не выбран стык
            if not mh.row or not mh.row.id:
                context['error'] = 'Выберите стык'
        elif action == 'file' and request.FILES:
            # Принятую заявку не редактируем
            if mh.row.state == 3:
                context['error'] = 'Нельзя изменить принятую заявку'
            else:
                # Загрузка файла в WeldingJointFile
                mh.files_add('path')
                new_file = Files.objects.create(
                    desc=mh.row.request_number,
                    name=request.FILES['path'].name,
                )
                mh.uploads(row=new_file)
                if new_file.path:
                    joint_file = WeldingJointFile.objects.create(
                        welding_joint=mh.row,
                        file=new_file,
                    )
                    new_file.update_mimetype()
                    context['success'] = 'Файл загружен'
                    context['file'] = {
                        'id': joint_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 action == 'img' and request.FILES:
            mh.uploads()
        elif action == 'state' and row:
            # Смена статуса заявки на стык
            if update_welding_joint_state(request, mh):
                context['success'] = 'Статус заявки обновлен'
            else:
                context['error'] = 'Статус заявки не обновлен'

    if mh.row:
        mh.url_form = reverse('%s:%s' % (CUR_APP, mh_vars['edit_urla']),
                              kwargs={
                                  'action': 'form',
                                  'row_id': mh.row.id
                              })
        context['url_form'] = mh.url_form
        context['row'] = object_fields(mh.row, pass_fields=('password', ))
        context['row']['folder'] = mh.row.get_folder()
        # Не надо инфу о пользователях сливать
        context['row']['receiver'] = None
        context['row']['requester'] = None
        context['redirect'] = mh.get_url_edit()
        if action == 'form':
            context['redirect'] = mh.url_form
    else:
        mh.url_form = reverse('%s:%s' % (CUR_APP, mh_vars['create_urla']),
                              kwargs={'action': 'form'})
    if request.is_ajax() or action in ('img', 'file', 'state'):
        return JsonResponse(context, safe=False)
    template = '%sedit.html' % (mh.template_prefix, )
    if action == 'form':
        mh.breadcrumbs_add({
            'link': mh.url_form,
            'name': '%s' % (mh.singular_obj, ),
        })
        template = '%sform.html' % (mh.template_prefix, )
    return render(request, template, context)