Ejemplo n.º 1
0
def remove_marked_objects(request):
    result = []

    models_to_remove = [(StorageItem, 'Товары на складе', 'товар на складе'),
                        (Document, 'Документы', 'документ'),
                        (Product, 'Товары', 'товар'),
                        (Contractor, 'Контрагенты', 'контрагент')]
    for model, description, operation_description in models_to_remove:
        success_list = []
        fail_list = []
        objects_to_remove = model.objects.filter(to_remove=True)
        for obj in objects_to_remove:
            string_description = str(obj)
            try:
                obj.delete()
                success_list.append(string_description)
                Operation.objects.create(
                    username=get_username_for_operation(request.user),
                    operation=
                    f'Удален {operation_description} {string_description}')
            except ProtectedError:
                fail_list.append(string_description)
                Operation.objects.create(
                    username=get_username_for_operation(request.user),
                    operation=
                    f'Не удалось удалить {operation_description} {string_description}'
                )
        if success_list or fail_list:
            result.append({
                'description': description,
                'success_list': success_list,
                'fail_list': fail_list
            })

    return Response(data=result, status=status.HTTP_200_OK)
Ejemplo n.º 2
0
    def update(self, request, *args, **kwargs):
        pk = kwargs['pk']
        updated_element = self.model.objects.filter(pk=pk).first()
        result = viewsets.ModelViewSet.update(self, request, *args, **kwargs)
        if updated_element:
            to_remove_before = updated_element.to_remove
            main_fields_before = self._get_model_field_values(updated_element)
            updated_element.refresh_from_db()
            to_remove_after = updated_element.to_remove
            main_fields_after = self._get_model_field_values(updated_element)

            username = get_username_for_operation(request.user)
            if main_fields_before != main_fields_after:
                print(main_fields_before)
                print(main_fields_after)

                operation = f'Изменен {self.model_verbose_name}: {updated_element}'
                Operation.objects.create(username=username,
                                         operation=operation)
            if not to_remove_before and to_remove_after:
                operation = f'{self.model_verbose_name} помечен на удаление: {updated_element}'
                Operation.objects.create(username=username,
                                         operation=operation)
            if to_remove_before and not to_remove_after:
                operation = f'Снята пометка на уделение с {self.model_verbose_name}: {updated_element}'
                Operation.objects.create(username=username,
                                         operation=operation)

        return result
Ejemplo n.º 3
0
def unapply_document(request, document_id):
    document = Document.objects.filter(pk=document_id).first()
    if not document:
        return Response(
            {'error': f'Документ с номером {document_id} не найден'},
            status=status.HTTP_400_BAD_REQUEST)
    if not document.apply_flag:
        return Response(
            {'error': f'Документ с номером {document_id} не проведен'},
            status=status.HTTP_400_BAD_REQUEST)

    # Отменяем проведение приходного документа
    if document.destination_type == Document.RECEIPT:
        try:
            unapply_receipt_document(document)
        except Exception as ex:
            return Response(
                {
                    'error':
                    f'Невозможно отменить проведение документа. Недостаточно товара на складе: {ex}'
                },
                status=status.HTTP_400_BAD_REQUEST)

    # Отменяем проведение расходного документа
    elif document.destination_type == Document.EXPENSE:
        unapply_expense_document(document)

    # Если ошибок не возникло - помечаем документ как не проведенный и регистрируем операцию
    document.apply_flag = False
    document.save()
    Operation.objects.create(
        username=get_username_for_operation(request.user),
        operation=f'Отменено проведение документа {document}')
    return Response(status=status.HTTP_200_OK)
Ejemplo n.º 4
0
 def create(self, request, *args, **kwargs):
     result = viewsets.ModelViewSet.create(self, request, *args, **kwargs)
     pk = result.data['id']
     created_element = self.model.objects.filter(pk=pk).first()
     if created_element:
         username = get_username_for_operation(request.user)
         operation = f'Создан {self.model_verbose_name}: {created_element}'
         Operation.objects.create(username=username, operation=operation)
     return result
Ejemplo n.º 5
0
 def create(self, request, *args, **kwargs):
     result = viewsets.ModelViewSet.create(self, request, *args, **kwargs)
     document_id = request.data.get('document')
     document = Document.objects.get(pk=document_id)
     document_item = DocumentItem.objects.get(pk=result.data['id'])
     Operation.objects.create(
         username=get_username_for_operation(request.user),
         operation=f'В документ {document} добавлен товар {document_item}')
     return result
Ejemplo n.º 6
0
    def destroy(self, request, *args, **kwargs):
        document_item_id = kwargs.get('pk')
        document_item = DocumentItem.objects.filter(
            pk=document_item_id).first()
        result = viewsets.ModelViewSet.destroy(self, request, *args, **kwargs)

        if document_item:
            Operation.objects.create(
                username=get_username_for_operation(request.user),
                operation=
                f'Из документа {document_item.document} удален товар {document_item}'
            )
        return result
Ejemplo n.º 7
0
    def update(self, request, *args, **kwargs):
        document_item_id = kwargs.get('pk')
        document_item = DocumentItem.objects.filter(
            pk=document_item_id).first()
        result = viewsets.ModelViewSet.update(self, request, *args, **kwargs)

        if document_item:
            count_before = document_item.count
            count_after = result.data['count']
            if count_before != count_after:
                Operation.objects.create(
                    username=get_username_for_operation(request.user),
                    operation=
                    f'В документе {document_item.document} изменено количество товара {document_item.product.title} '
                    f'(было {count_before}, стало {count_after})')
        return result
Ejemplo n.º 8
0
def import_products(request):
    uploaded_file = request.data['uploaded_file']
    path = get_tmp_file_path('uploaded_file.xlsx')
    with open(path, 'wb') as output_file:
        output_file.write(uploaded_file.read())

    try:
        created_records = action(file_path=path)
        Operation.objects.create(
            username=get_username_for_operation(request.user),
            operation=f'Импортировано товаров: {created_records}')
    except Exception as ex:
        return Response(data=f'Ошибка при импорте: {ex}',
                        status=status.HTTP_400_BAD_REQUEST)
    finally:
        os.remove(path)

    return Response(status=status.HTTP_200_OK)