Beispiel #1
0
 def get(self, account_id, category_id):
     """Возвращает дерево категорий, начиная с category_id категории"""
     with db.connection as con:
         service = CategoriesService(con)
         tree_category = service.get_subcategories_tree(
             account_id, category_id)
         return jsonify(tree_category), 200
Beispiel #2
0
    def get(self, account_id):
        """Возвращает деревья категорий, принадлежащих пользователю"""
        with db.connection as con:
            service = CategoriesService(con)
            tree_categories = service.get_subcategories_tree(account_id)

        return jsonify(tree_categories), 200
Beispiel #3
0
def get_category_by_id(id: int, user):
    categories_service = CategoriesService()

    try:
        return categories_service.get_category_by_id(id, user)
    except UnAuthorized:
        return json_response.unauthorized()
    except CategoryDoesntExist:
        return json_response.not_found()
Beispiel #4
0
def get_categories(user):
    categories_service = CategoriesService()

    try:
        return json_response.success(categories_service.get_categories(user))
    except UnAuthorized:
        return json_response.unauthorized()
    except NoCategories:
        return json_response.not_found()
Beispiel #5
0
def delete_category_by_id(id: int, user):
    categories_service = CategoriesService()

    try:
        return json_response.success(
            categories_service.delete_category_by_id(id, user))
    except UnAuthorized:
        return json_response.unauthorized()
    except CategoryDoesntExist:
        return json_response.not_found()
Beispiel #6
0
def edit_category_by_id(id: int, user):
    data = request.get_json()
    categories_service = CategoriesService()

    try:
        return json_response.success(
            categories_service.edit_category_by_id(id, data, user))
    except UnAuthorized:
        return json_response.unauthorized()
    except CategoryDoesntExist:
        return json_response.not_found()
Beispiel #7
0
def create_category(user):
    data = request.get_json()
    categories_service = CategoriesService()

    try:
        return json_response.success(
            categories_service.create_category(data, user))
    except UnAuthorized:
        return json_response.unauthorized()
    except CategoryAlreadyExist:
        return json_response.conflict()
Beispiel #8
0
    def post(self):
        # Проверка авторизации
        account_id = session.get('user_id')
        if not account_id:
            return '', 403

        request_json = request.json

        # Обработка даты
        date = request_json.get('date')
        if date:
            date = int(time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S")))
        else:
            date = int(time.time())

        # Обработка данных и валидация
        try:
            operation = {
                "date": date,
                "type": request_json['type'],
                "description": request_json.get('description'),
                "amount": request_json['amount'],
                "category_id": request_json.get('category_id'),
                "account_id": account_id,
            }
        except KeyError as e:
            return "", 400

        # Чтение операции из базы
        if operation.get('category_id') is not None:
            category_service = CategoriesService()
            category = category_service.read(category_id=operation['category_id'], account_id=account_id)
            if not category:
                return "", 403

            # Получение имени родительской категории
            parent_category = category_service.read(category_id=category.pop('parent_id'), account_id=account_id)

            # Формирование сведений о категории
            category.pop('account_id')
            category['parent_name'] = parent_category.get('name')
        else:
            category = None

        # Запись операции в базу
        operation_service = OperationService()
        operation_service.create_operation(data=operation)

        # Формируем ответ
        operation.pop('category_id')
        operation['category'] = category

        return jsonify(operation), 201
Beispiel #9
0
 def patch(self, account_id, category_id):
     """Функция для весенний изменений в категорию"""
     with db.connection as con:
         service = CategoriesService(con)
         try:
             category = service.update_category(dict(request.json),
                                                category_id, account_id)
         except CategoryDoesNotExistError:
             return '', 400
         except CategoryConflictError as error:
             return jsonify(dict(error.category)), 409
         except PermissionError:
             return '', 403
         else:
             return jsonify(category), 200
Beispiel #10
0
    def patch(self, category_id: int):
        # account_id = session['id']
        account_id = 1  # для тестов
        request_json = request.json
        parent_id = request_json.get('parent_id')
        name = request_json.get('name')
        new_data = {
            'account_id': account_id,
            'id': category_id,
            'parent_id': parent_id
        }
        if name is not None:
            new_data['name'] = name

        service = CategoriesService()
        result = service.edit(data=new_data)
        return jsonify(result), 200
Beispiel #11
0
 def post(self, account_id):
     """Функция добавления категории"""
     try:
         category = CreateCategorySchema().load(request.json)
     except ValidationError as error:
         return jsonify(error.messages), 400
     else:
         with db.connection as con:
             service = CategoriesService(con)
             try:
                 category = service.create_category(category, account_id)
             except CategoryDoesNotExistError:
                 return '', 400
             except PermissionError:
                 return '', 403
             except CategoryConflictError as error:
                 return jsonify(dict(error.category)), 409
             return jsonify(category), 200
Beispiel #12
0
    def build_report_query(self, filters):
        """Конструктор запроса WHERE"""
        query_template = """
            {where_query}
            ORDER BY date
            """
        where_clauses = []
        params = []
        for key, value in filters.items():
            if key == 'category_id':
                """Проверка категории на существование, наличие прав"""
                if value == '0':
                    where_clauses.append(f' {key} is NULL ')
                else:
                    CategoriesService(self.connection).parent_category_exists(
                        value, filters['account_id'])
                    """Поиск всех категорий-детей"""
                    cur = self.connection.execute(
                        f"""
                        WITH RECURSIVE subtree(id)
                        AS (SELECT id
                            FROM categories
                            WHERE account_id = {filters['account_id']} AND id = {value}
                        UNION ALL
                            SELECT categories.id
                            FROM categories
                            INNER JOIN subtree ON categories.parent_id = subtree.id)
                        SELECT id
                        FROM subtree
                        ORDER BY id
                        """, )
                    list_id = []
                    for elem in cur.fetchall():
                        list_id.append(elem[0])
                    if len(list_id) == 1:
                        list_id = list_id[0]
                        where_clauses.append(f' {key} = {list_id} ')
                    else:
                        list_id = tuple(list_id)
                        where_clauses.append(f' {key} IN {list_id} ')
            elif key == 'from':
                where_clauses.append(f' date >= ?')
                params.append(value)
            elif key == 'to':
                where_clauses.append(f' date <= ?')
                params.append(value)
            elif key == 'type' or key == 'account_id':
                where_clauses.append(f' {key} = ?')
                params.append(value)
            else:
                continue

        where_query = ''
        if where_clauses:
            where_query = 'WHERE {}'.format(' AND '.join(where_clauses))
        query = query_template.format(where_query=where_query)
        return query, params
Beispiel #13
0
 def category_check(self, category_id, account_id):
     """ Проверяет существование и является ли account_id
         владельцем категории под category_id """
     if category_id is not None:
         CategoriesService(self.connection).parent_category_exists(
             category_id, account_id)
Beispiel #14
0
 def delete(self, account_id, category_id):
     """Функция для удаления категории и всех её потомков"""
     with db.connection as con:
         service = CategoriesService(con)
         service.delete_category(category_id)
         return '', 204