diff --git a/CHANGELOG.md b/CHANGELOG.md index 20299d7..a654cc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## 0.6.10 — 2026-11-16 + +A minor addition: the GLPI v2 `/Dropdowns/ITILCategory` routes, so a caller +can find and create ITIL categories. Existing methods are unchanged. + +### Added + +- **`search_itil_categories`, `iter_search_itil_categories`, + `get_itil_category`, `create_itil_category`, `update_itil_category` and + `delete_itil_category`** on both clients, from a new `ITILCategoryMixin` + and the `ITIL_CATEGORY_ENDPOINT` constant. +- **`skip_entity: bool = False`** on `search_itil_categories`, + `iter_search_itil_categories` and `get_itil_category`: `True` omits the + `GLPI-Entity`, `GLPI-Profile` and `GLPI-Entity-Recursive` headers so the + call spans every entity the caller can see. The write methods always send + them. +- **`GetITILCategory`, `PostITILCategory`, `PatchITILCategory` and + `DeleteITILCategory`**, modelled on `components.schemas.ITILCategory` + (entity, parent, code, templates, per-type visibility flags and + timestamps), exported from the package root and from + `glpi_python_client.models`. + ## 0.6.9 — 2026-11-10 A fix for GLPI 12. GLPI 12.0.1 sends a ticket's `ola_ttr` and `ola_tto` as an diff --git a/docs/api_reference.rst b/docs/api_reference.rst index 9af0dda..cbe0340 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -386,6 +386,29 @@ Locations :undoc-members: :show-inheritance: +ITIL Categories +--------------- + +.. autoclass:: GetITILCategory + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: PostITILCategory + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: PatchITILCategory + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: DeleteITILCategory + :members: + :undoc-members: + :show-inheritance: + Knowledge Base — Articles ------------------------- diff --git a/docs/user_guide.rst b/docs/user_guide.rst index 446520b..41de66a 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -377,6 +377,8 @@ The full set is re-exported from the package root, including ``GetTicket`` / ``PostTicket`` / ``PatchTicket`` / ``DeleteTicket``, ``GetUser`` / ``PostUser`` / ``PatchUser`` / ``DeleteUser``, ``GetLocation`` / ``PostLocation`` / ``PatchLocation`` / ``DeleteLocation``, +``GetITILCategory`` / ``PostITILCategory`` / ``PatchITILCategory`` / +``DeleteITILCategory``, ``GetEntity`` / ``PostEntity`` / ``PatchEntity`` / ``DeleteEntity``, ``GetGroup`` / ``PostGroup`` / ``PatchGroup`` / ``DeleteGroup``, ``UserAuthorization``, @@ -1228,6 +1230,7 @@ batches until the API returns fewer rows than the requested * :meth:`GlpiClient.iter_search_users` * :meth:`GlpiClient.iter_search_entities` * :meth:`GlpiClient.iter_search_groups` +* :meth:`GlpiClient.iter_search_itil_categories` .. code-block:: python diff --git a/glpi_python_client/__init__.py b/glpi_python_client/__init__.py index d3a884c..6676651 100644 --- a/glpi_python_client/__init__.py +++ b/glpi_python_client/__init__.py @@ -41,6 +41,7 @@ DeleteEntity, DeleteFollowup, DeleteGroup, + DeleteITILCategory, DeleteKBArticle, DeleteKBArticleComment, DeleteKBCategory, @@ -62,6 +63,7 @@ GetEntity, GetFollowup, GetGroup, + GetITILCategory, GetKBArticle, GetKBArticleComment, GetKBArticleRevision, @@ -99,6 +101,7 @@ PatchEntity, PatchFollowup, PatchGroup, + PatchITILCategory, PatchKBArticle, PatchKBArticleComment, PatchKBCategory, @@ -118,6 +121,7 @@ PostEntity, PostFollowup, PostGroup, + PostITILCategory, PostKBArticle, PostKBArticleComment, PostKBCategory, @@ -138,7 +142,7 @@ date_window, ) -__version__ = "0.6.9" +__version__ = "0.6.10" __all__ = [ "AsyncGlpiClient", @@ -151,6 +155,7 @@ "DeleteEntity", "DeleteFollowup", "DeleteGroup", + "DeleteITILCategory", "DeleteKBArticle", "DeleteKBArticleComment", "DeleteKBCategory", @@ -172,6 +177,7 @@ "GetEntity", "GetFollowup", "GetGroup", + "GetITILCategory", "GetKBArticle", "GetKBArticleComment", "GetKBArticleRevision", @@ -220,6 +226,7 @@ "PatchEntity", "PatchFollowup", "PatchGroup", + "PatchITILCategory", "PatchKBArticle", "PatchKBArticleComment", "PatchKBCategory", @@ -239,6 +246,7 @@ "PostEntity", "PostFollowup", "PostGroup", + "PostITILCategory", "PostKBArticle", "PostKBArticleComment", "PostKBCategory", diff --git a/glpi_python_client/_async/clients/api/__init__.py b/glpi_python_client/_async/clients/api/__init__.py index d373e5c..2933c6b 100644 --- a/glpi_python_client/_async/clients/api/__init__.py +++ b/glpi_python_client/_async/clients/api/__init__.py @@ -27,6 +27,7 @@ ) from glpi_python_client._async.clients.api.dropdowns import ( ContractTypeMixin, + ITILCategoryMixin, LocationMixin, ) from glpi_python_client._async.clients.api.knowledgebase import ( @@ -51,6 +52,7 @@ "EntityMixin", "FollowupMixin", "GroupMixin", + "ITILCategoryMixin", "KBArticleCommentMixin", "KBArticleMixin", "KBArticleRevisionMixin", diff --git a/glpi_python_client/_async/clients/api/dropdowns/__init__.py b/glpi_python_client/_async/clients/api/dropdowns/__init__.py index 0979bf3..947a6a6 100644 --- a/glpi_python_client/_async/clients/api/dropdowns/__init__.py +++ b/glpi_python_client/_async/clients/api/dropdowns/__init__.py @@ -5,6 +5,9 @@ from glpi_python_client._async.clients.api.dropdowns._contract_type import ( ContractTypeMixin, ) +from glpi_python_client._async.clients.api.dropdowns._itil_category import ( + ITILCategoryMixin, +) from glpi_python_client._async.clients.api.dropdowns._location import LocationMixin -__all__ = ["ContractTypeMixin", "LocationMixin"] +__all__ = ["ContractTypeMixin", "ITILCategoryMixin", "LocationMixin"] diff --git a/glpi_python_client/_async/clients/api/dropdowns/_itil_category.py b/glpi_python_client/_async/clients/api/dropdowns/_itil_category.py new file mode 100644 index 0000000..18fd64c --- /dev/null +++ b/glpi_python_client/_async/clients/api/dropdowns/_itil_category.py @@ -0,0 +1,233 @@ +"""GLPI ``/Dropdowns/ITILCategory`` mixin. + +The mixin exposes search, fetch, create, update, and delete helpers for the +GLPI ITIL category dropdown resource. Every call sends the client's +``GLPI-Entity`` header (and the profile and recursion headers that travel +with it) except where a read is told to skip it with ``skip_entity=True``. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator + +from glpi_python_client._async.clients.commons._constants import ( + ITIL_CATEGORY_ENDPOINT, + GlpiId, +) +from glpi_python_client._async.clients.commons._transport import TransportMixin +from glpi_python_client.models.api_schema.dropdowns._itil_category import ( + DeleteITILCategory, + GetITILCategory, + PatchITILCategory, + PostITILCategory, +) + + +class ITILCategoryMixin(TransportMixin): + """CRUD helpers for ``/Dropdowns/ITILCategory``.""" + + async def search_itil_categories( + self, + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + """Search GLPI ITIL categories with an optional RSQL filter. + + Parameters + ---------- + rsql_filter : str, optional + Raw RSQL filter forwarded as the ``filter`` query parameter. + limit : int, optional + Maximum number of records returned by the GLPI server. + start : int, optional + Zero-based offset of the first record returned. + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so the + search spans every entity the caller has access to. + + Returns + ------- + list[GetITILCategory] + Categories matching the filter. + """ + + params: dict[str, object] = {"limit": limit, "start": start} + if rsql_filter: + params["filter"] = rsql_filter + return await self._resource_list( + ITIL_CATEGORY_ENDPOINT, + GetITILCategory, + params=params, + skip_entity=skip_entity, + ) + + async def iter_search_itil_categories( + self, + rsql_filter: str = "", + *, + batch_size: int = 50, + skip_entity: bool = False, + ) -> AsyncIterator[list[GetITILCategory]]: + """Yield successive pages of GLPI ITIL categories until exhausted. + + Pagination advances the ``start`` offset after each batch and stops + when the server returns fewer items than ``batch_size``. + + Parameters + ---------- + rsql_filter : str, optional + Raw RSQL filter forwarded as the ``filter`` query parameter. + batch_size : int, optional + Number of records requested per page (default 50). + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so the + search spans every entity the caller has access to. + + Yields + ------ + list[GetITILCategory] + One page per iteration. The last yielded batch may be shorter + than ``batch_size``. + """ + + start = 0 + while True: + batch = await self.search_itil_categories( + rsql_filter, + limit=batch_size, + start=start, + skip_entity=skip_entity, + ) + if batch: + yield batch + if len(batch) < batch_size: + break + start += batch_size + + async def get_itil_category( + self, category_id: GlpiId, *, skip_entity: bool = False + ) -> GetITILCategory: + """Fetch one GLPI ITIL category by identifier. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to retrieve. + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so a + category outside the client's entity can be read. + + Returns + ------- + GetITILCategory + Validated category payload. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + return await self._resource_get( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + GetITILCategory, + failure_message=f"Failed to get ITIL category {category_id}", + skip_entity=skip_entity, + ) + + async def create_itil_category(self, category: PostITILCategory) -> int: + """Create one GLPI ITIL category. + + Parameters + ---------- + category : PostITILCategory + Request body describing the category to create. + + Returns + ------- + int + Identifier assigned by the GLPI server. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + GlpiProtocolError + If the create response is missing the ``id`` field. + """ + + return await self._resource_create( + ITIL_CATEGORY_ENDPOINT, + category, + failure_message="Failed to create ITIL category", + missing_message="GLPI ITIL category create response did not include an ID", + log_message_factory=lambda new_id: ( + f"GLPI API created ITIL category {new_id}" + ), + ) + + async def update_itil_category( + self, category_id: GlpiId, category: PatchITILCategory + ) -> None: + """Update one GLPI ITIL category with a partial body. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to update. + category : PatchITILCategory + Partial request body. + + Returns + ------- + None + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + await self._resource_update( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + category, + failure_message=f"Failed to update ITIL category {category_id}", + log_message=f"GLPI API updated ITIL category {category_id}", + ) + + async def delete_itil_category( + self, category_id: GlpiId, *, force: bool | None = None + ) -> None: + """Delete one GLPI ITIL category by identifier. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to delete. + force : bool | None, optional + When ``True`` the category is permanently deleted instead of + being moved to the trash. + + Returns + ------- + None + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + await self._resource_delete( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + failure_message=f"Failed to delete ITIL category {category_id}", + log_message=f"GLPI API deleted ITIL category {category_id}", + force=force, + delete_model_cls=DeleteITILCategory, + ) + + +__all__ = ["ITILCategoryMixin"] diff --git a/glpi_python_client/_async/clients/api/dropdowns/tests/test_itil_category.py b/glpi_python_client/_async/clients/api/dropdowns/tests/test_itil_category.py new file mode 100644 index 0000000..72b8d87 --- /dev/null +++ b/glpi_python_client/_async/clients/api/dropdowns/tests/test_itil_category.py @@ -0,0 +1,284 @@ +"""Unit tests for the ``Dropdowns/ITILCategory`` endpoint mixin.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from typing import Any + +import pytest + +from glpi_python_client import PatchITILCategory, PostITILCategory +from glpi_python_client._async._testing import ( + FailingTransportRecorder, + TransportRecorder, +) +from glpi_python_client.models.api_schema._common import IdNameRef +from glpi_python_client.models.api_schema.dropdowns import GetITILCategory + + +async def test_search_itil_categories_passes_filter_and_paging(client: Any) -> None: + """``search_itil_categories`` forwards filter, limit and start.""" + + rec = TransportRecorder(get_payload=[{"id": 4, "name": "Network"}]) + rec.install(client) + categories = await client.search_itil_categories("name==x", limit=10, start=5) + assert categories[0].id == 4 + call = rec.calls[0] + assert call["endpoint"] == "Dropdowns/ITILCategory" + assert call["params"] == {"limit": 10, "start": 5, "filter": "name==x"} + assert call["skip_entity"] is False + + +async def test_search_itil_categories_without_filter_sends_no_filter( + client: Any, +) -> None: + """With no filter the ``filter`` query parameter is omitted entirely.""" + + rec = TransportRecorder(get_payload=[]) + rec.install(client) + await client.search_itil_categories() + assert rec.calls[0]["params"] == {"limit": 50, "start": 0} + assert "filter" not in rec.calls[0]["params"] + + +async def test_search_itil_categories_forwards_skip_entity(client: Any) -> None: + """``skip_entity=True`` reaches the transport.""" + + rec = TransportRecorder(get_payload=[]) + rec.install(client) + await client.search_itil_categories("name==x", skip_entity=True) + assert rec.calls[0]["skip_entity"] is True + + +async def test_get_itil_category_targets_per_id_endpoint(client: Any) -> None: + """``get_itil_category`` reads the per-id endpoint.""" + + rec = TransportRecorder(get_payload={"id": 9, "name": "Network"}) + rec.install(client) + category = await client.get_itil_category(9) + assert category.id == 9 + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory/9" + assert rec.calls[0]["skip_entity"] is False + + +async def test_get_itil_category_forwards_skip_entity(client: Any) -> None: + """``skip_entity=True`` reaches the transport on a fetch.""" + + rec = TransportRecorder(get_payload={"id": 9, "name": "Network"}) + rec.install(client) + await client.get_itil_category(9, skip_entity=True) + assert rec.calls[0]["skip_entity"] is True + + +async def test_create_itil_category_returns_new_id(client: Any) -> None: + """``create_itil_category`` returns the identifier the server assigned.""" + + rec = TransportRecorder(post_payload={"id": 42}) + rec.install(client) + new_id = await client.create_itil_category(PostITILCategory(name="Network")) + assert new_id == 42 + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory" + + +async def test_create_itil_category_sends_body_with_entity_and_parent( + client: Any, +) -> None: + """The body carries entity, parent and the visibility flags.""" + + rec = TransportRecorder(post_payload={"id": 42}) + rec.install(client) + await client.create_itil_category( + PostITILCategory( + name="Network", + entity=IdNameRef(id=7), + parent=IdNameRef(id=3), + is_recursive=True, + is_incident_visible=True, + is_request_visible=False, + ) + ) + body = rec.calls[0]["json"] + assert body["entity"]["id"] == 7 + assert body["parent"]["id"] == 3 + assert body["is_recursive"] is True + assert body["is_incident_visible"] is True + assert body["is_request_visible"] is False + assert body["name"] == "Network" + + +async def test_update_itil_category_sends_patch(client: Any) -> None: + """``update_itil_category`` patches the per-id endpoint.""" + + rec = TransportRecorder() + rec.install(client) + await client.update_itil_category(9, PatchITILCategory(name="renamed")) + assert rec.calls[0]["method"] == "PATCH" + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory/9" + assert rec.calls[0]["json"] == {"name": "renamed"} + + +async def test_delete_itil_category_with_force(client: Any) -> None: + """``delete_itil_category(force=True)`` ships the force flag.""" + + rec = TransportRecorder() + rec.install(client) + await client.delete_itil_category(9, force=True) + call = rec.calls[0] + assert call["method"] == "DELETE" + assert call["endpoint"] == "Dropdowns/ITILCategory/9" + assert call["json"] == {"force": True} + + +async def test_delete_itil_category_without_force(client: Any) -> None: + """Without ``force`` the body carries no force flag.""" + + rec = TransportRecorder() + rec.install(client) + await client.delete_itil_category(9) + call = rec.calls[0] + assert call["method"] == "DELETE" + assert call["endpoint"] == "Dropdowns/ITILCategory/9" + assert not call["json"] + + +async def _read(client: Any) -> Any: + return await client.get_itil_category(1) + + +async def _create(client: Any) -> Any: + return await client.create_itil_category(PostITILCategory(name="x")) + + +async def _update(client: Any) -> Any: + return await client.update_itil_category(1, PatchITILCategory(name="x")) + + +async def _delete(client: Any) -> Any: + return await client.delete_itil_category(1, force=True) + + +@pytest.mark.parametrize("call", [_read]) +async def test_read_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every read helper raises on a non-success status.""" + + FailingTransportRecorder(404).install(client) + with pytest.raises(ValueError): + await call(client) + + +@pytest.mark.parametrize("call", [_create]) +async def test_create_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every create helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + await call(client) + + +@pytest.mark.parametrize("call", [_update]) +async def test_update_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every update helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + await call(client) + + +@pytest.mark.parametrize("call", [_delete]) +async def test_delete_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every delete helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + await call(client) + + +async def test_iter_search_itil_categories_yields_every_page(client: Any) -> None: + """The generator advances ``start`` and forwards ``skip_entity``.""" + + pages = [[GetITILCategory(id=i) for i in range(3)], [GetITILCategory(id=99)]] + starts: list[int] = [] + skips: list[bool] = [] + + async def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + skips.append(skip_entity) + index = start // limit + return pages[index] if index < len(pages) else [] + + client.search_itil_categories = fake_search + + batches = [ + batch + async for batch in client.iter_search_itil_categories( + "name==x", batch_size=3, skip_entity=True + ) + ] + + assert starts == [0, 3] + assert skips == [True, True] + assert [len(b) for b in batches] == [3, 1] + + +async def test_iter_search_itil_categories_stops_on_a_single_short_page( + client: Any, +) -> None: + """One short page is the last page; no second request is made.""" + + starts: list[int] = [] + + async def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + return [GetITILCategory(id=1)] + + client.search_itil_categories = fake_search + + batches = [batch async for batch in client.iter_search_itil_categories()] + + assert starts == [0] + assert len(batches) == 1 + + +async def test_iter_search_itil_categories_yields_nothing_when_empty( + client: Any, +) -> None: + """An empty first page yields no batch at all.""" + + starts: list[int] = [] + + async def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + return [] + + client.search_itil_categories = fake_search + + assert [batch async for batch in client.iter_search_itil_categories()] == [] diff --git a/glpi_python_client/_async/clients/client.py b/glpi_python_client/_async/clients/client.py index 8f00dcc..c7f45dd 100644 --- a/glpi_python_client/_async/clients/client.py +++ b/glpi_python_client/_async/clients/client.py @@ -26,6 +26,7 @@ EntityMixin, FollowupMixin, GroupMixin, + ITILCategoryMixin, KBArticleCommentMixin, KBArticleMixin, KBArticleRevisionMixin, @@ -63,6 +64,7 @@ class AsyncGlpiClient( GroupMixin, LocationMixin, ContractTypeMixin, + ITILCategoryMixin, KBCategoryMixin, KBArticleMixin, KBArticleCommentMixin, diff --git a/glpi_python_client/_async/clients/commons/_constants.py b/glpi_python_client/_async/clients/commons/_constants.py index 0050153..b509f03 100644 --- a/glpi_python_client/_async/clients/commons/_constants.py +++ b/glpi_python_client/_async/clients/commons/_constants.py @@ -24,6 +24,7 @@ # dropdowns/ CONTRACT_TYPE_ENDPOINT = "Dropdowns/ContractType" LOCATION_ENDPOINT = "Dropdowns/Location" +ITIL_CATEGORY_ENDPOINT = "Dropdowns/ITILCategory" # management/ CONTRACT_ENDPOINT = "Management/Contract" @@ -54,6 +55,7 @@ "ENTITY_ENDPOINT", "FOLLOWUP_SUFFIX", "GROUP_ENDPOINT", + "ITIL_CATEGORY_ENDPOINT", "KB_ARTICLE_ENDPOINT", "KB_CATEGORY_ENDPOINT", "KB_COMMENT_SUFFIX", diff --git a/glpi_python_client/_sync/clients/api/__init__.py b/glpi_python_client/_sync/clients/api/__init__.py index e009660..3ea45f9 100644 --- a/glpi_python_client/_sync/clients/api/__init__.py +++ b/glpi_python_client/_sync/clients/api/__init__.py @@ -27,6 +27,7 @@ ) from glpi_python_client._sync.clients.api.dropdowns import ( ContractTypeMixin, + ITILCategoryMixin, LocationMixin, ) from glpi_python_client._sync.clients.api.knowledgebase import ( @@ -51,6 +52,7 @@ "EntityMixin", "FollowupMixin", "GroupMixin", + "ITILCategoryMixin", "KBArticleCommentMixin", "KBArticleMixin", "KBArticleRevisionMixin", diff --git a/glpi_python_client/_sync/clients/api/dropdowns/__init__.py b/glpi_python_client/_sync/clients/api/dropdowns/__init__.py index 817ad59..3289007 100644 --- a/glpi_python_client/_sync/clients/api/dropdowns/__init__.py +++ b/glpi_python_client/_sync/clients/api/dropdowns/__init__.py @@ -5,6 +5,9 @@ from glpi_python_client._sync.clients.api.dropdowns._contract_type import ( ContractTypeMixin, ) +from glpi_python_client._sync.clients.api.dropdowns._itil_category import ( + ITILCategoryMixin, +) from glpi_python_client._sync.clients.api.dropdowns._location import LocationMixin -__all__ = ["ContractTypeMixin", "LocationMixin"] +__all__ = ["ContractTypeMixin", "ITILCategoryMixin", "LocationMixin"] diff --git a/glpi_python_client/_sync/clients/api/dropdowns/_itil_category.py b/glpi_python_client/_sync/clients/api/dropdowns/_itil_category.py new file mode 100644 index 0000000..43195b9 --- /dev/null +++ b/glpi_python_client/_sync/clients/api/dropdowns/_itil_category.py @@ -0,0 +1,233 @@ +"""GLPI ``/Dropdowns/ITILCategory`` mixin. + +The mixin exposes search, fetch, create, update, and delete helpers for the +GLPI ITIL category dropdown resource. Every call sends the client's +``GLPI-Entity`` header (and the profile and recursion headers that travel +with it) except where a read is told to skip it with ``skip_entity=True``. +""" + +from __future__ import annotations + +from collections.abc import Iterator + +from glpi_python_client._sync.clients.commons._constants import ( + ITIL_CATEGORY_ENDPOINT, + GlpiId, +) +from glpi_python_client._sync.clients.commons._transport import TransportMixin +from glpi_python_client.models.api_schema.dropdowns._itil_category import ( + DeleteITILCategory, + GetITILCategory, + PatchITILCategory, + PostITILCategory, +) + + +class ITILCategoryMixin(TransportMixin): + """CRUD helpers for ``/Dropdowns/ITILCategory``.""" + + def search_itil_categories( + self, + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + """Search GLPI ITIL categories with an optional RSQL filter. + + Parameters + ---------- + rsql_filter : str, optional + Raw RSQL filter forwarded as the ``filter`` query parameter. + limit : int, optional + Maximum number of records returned by the GLPI server. + start : int, optional + Zero-based offset of the first record returned. + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so the + search spans every entity the caller has access to. + + Returns + ------- + list[GetITILCategory] + Categories matching the filter. + """ + + params: dict[str, object] = {"limit": limit, "start": start} + if rsql_filter: + params["filter"] = rsql_filter + return self._resource_list( + ITIL_CATEGORY_ENDPOINT, + GetITILCategory, + params=params, + skip_entity=skip_entity, + ) + + def iter_search_itil_categories( + self, + rsql_filter: str = "", + *, + batch_size: int = 50, + skip_entity: bool = False, + ) -> Iterator[list[GetITILCategory]]: + """Yield successive pages of GLPI ITIL categories until exhausted. + + Pagination advances the ``start`` offset after each batch and stops + when the server returns fewer items than ``batch_size``. + + Parameters + ---------- + rsql_filter : str, optional + Raw RSQL filter forwarded as the ``filter`` query parameter. + batch_size : int, optional + Number of records requested per page (default 50). + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so the + search spans every entity the caller has access to. + + Yields + ------ + list[GetITILCategory] + One page per iteration. The last yielded batch may be shorter + than ``batch_size``. + """ + + start = 0 + while True: + batch = self.search_itil_categories( + rsql_filter, + limit=batch_size, + start=start, + skip_entity=skip_entity, + ) + if batch: + yield batch + if len(batch) < batch_size: + break + start += batch_size + + def get_itil_category( + self, category_id: GlpiId, *, skip_entity: bool = False + ) -> GetITILCategory: + """Fetch one GLPI ITIL category by identifier. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to retrieve. + skip_entity : bool, optional + When ``True`` the ``GLPI-Entity`` header is omitted so a + category outside the client's entity can be read. + + Returns + ------- + GetITILCategory + Validated category payload. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + return self._resource_get( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + GetITILCategory, + failure_message=f"Failed to get ITIL category {category_id}", + skip_entity=skip_entity, + ) + + def create_itil_category(self, category: PostITILCategory) -> int: + """Create one GLPI ITIL category. + + Parameters + ---------- + category : PostITILCategory + Request body describing the category to create. + + Returns + ------- + int + Identifier assigned by the GLPI server. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + GlpiProtocolError + If the create response is missing the ``id`` field. + """ + + return self._resource_create( + ITIL_CATEGORY_ENDPOINT, + category, + failure_message="Failed to create ITIL category", + missing_message="GLPI ITIL category create response did not include an ID", + log_message_factory=lambda new_id: ( + f"GLPI API created ITIL category {new_id}" + ), + ) + + def update_itil_category( + self, category_id: GlpiId, category: PatchITILCategory + ) -> None: + """Update one GLPI ITIL category with a partial body. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to update. + category : PatchITILCategory + Partial request body. + + Returns + ------- + None + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + self._resource_update( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + category, + failure_message=f"Failed to update ITIL category {category_id}", + log_message=f"GLPI API updated ITIL category {category_id}", + ) + + def delete_itil_category( + self, category_id: GlpiId, *, force: bool | None = None + ) -> None: + """Delete one GLPI ITIL category by identifier. + + Parameters + ---------- + category_id : GlpiId + Numeric identifier of the category to delete. + force : bool | None, optional + When ``True`` the category is permanently deleted instead of + being moved to the trash. + + Returns + ------- + None + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + self._resource_delete( + f"{ITIL_CATEGORY_ENDPOINT}/{category_id}", + failure_message=f"Failed to delete ITIL category {category_id}", + log_message=f"GLPI API deleted ITIL category {category_id}", + force=force, + delete_model_cls=DeleteITILCategory, + ) + + +__all__ = ["ITILCategoryMixin"] diff --git a/glpi_python_client/_sync/clients/api/dropdowns/tests/test_itil_category.py b/glpi_python_client/_sync/clients/api/dropdowns/tests/test_itil_category.py new file mode 100644 index 0000000..78e539c --- /dev/null +++ b/glpi_python_client/_sync/clients/api/dropdowns/tests/test_itil_category.py @@ -0,0 +1,284 @@ +"""Unit tests for the ``Dropdowns/ITILCategory`` endpoint mixin.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from typing import Any + +import pytest + +from glpi_python_client import PatchITILCategory, PostITILCategory +from glpi_python_client._sync._testing import ( + FailingTransportRecorder, + TransportRecorder, +) +from glpi_python_client.models.api_schema._common import IdNameRef +from glpi_python_client.models.api_schema.dropdowns import GetITILCategory + + +def test_search_itil_categories_passes_filter_and_paging(client: Any) -> None: + """``search_itil_categories`` forwards filter, limit and start.""" + + rec = TransportRecorder(get_payload=[{"id": 4, "name": "Network"}]) + rec.install(client) + categories = client.search_itil_categories("name==x", limit=10, start=5) + assert categories[0].id == 4 + call = rec.calls[0] + assert call["endpoint"] == "Dropdowns/ITILCategory" + assert call["params"] == {"limit": 10, "start": 5, "filter": "name==x"} + assert call["skip_entity"] is False + + +def test_search_itil_categories_without_filter_sends_no_filter( + client: Any, +) -> None: + """With no filter the ``filter`` query parameter is omitted entirely.""" + + rec = TransportRecorder(get_payload=[]) + rec.install(client) + client.search_itil_categories() + assert rec.calls[0]["params"] == {"limit": 50, "start": 0} + assert "filter" not in rec.calls[0]["params"] + + +def test_search_itil_categories_forwards_skip_entity(client: Any) -> None: + """``skip_entity=True`` reaches the transport.""" + + rec = TransportRecorder(get_payload=[]) + rec.install(client) + client.search_itil_categories("name==x", skip_entity=True) + assert rec.calls[0]["skip_entity"] is True + + +def test_get_itil_category_targets_per_id_endpoint(client: Any) -> None: + """``get_itil_category`` reads the per-id endpoint.""" + + rec = TransportRecorder(get_payload={"id": 9, "name": "Network"}) + rec.install(client) + category = client.get_itil_category(9) + assert category.id == 9 + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory/9" + assert rec.calls[0]["skip_entity"] is False + + +def test_get_itil_category_forwards_skip_entity(client: Any) -> None: + """``skip_entity=True`` reaches the transport on a fetch.""" + + rec = TransportRecorder(get_payload={"id": 9, "name": "Network"}) + rec.install(client) + client.get_itil_category(9, skip_entity=True) + assert rec.calls[0]["skip_entity"] is True + + +def test_create_itil_category_returns_new_id(client: Any) -> None: + """``create_itil_category`` returns the identifier the server assigned.""" + + rec = TransportRecorder(post_payload={"id": 42}) + rec.install(client) + new_id = client.create_itil_category(PostITILCategory(name="Network")) + assert new_id == 42 + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory" + + +def test_create_itil_category_sends_body_with_entity_and_parent( + client: Any, +) -> None: + """The body carries entity, parent and the visibility flags.""" + + rec = TransportRecorder(post_payload={"id": 42}) + rec.install(client) + client.create_itil_category( + PostITILCategory( + name="Network", + entity=IdNameRef(id=7), + parent=IdNameRef(id=3), + is_recursive=True, + is_incident_visible=True, + is_request_visible=False, + ) + ) + body = rec.calls[0]["json"] + assert body["entity"]["id"] == 7 + assert body["parent"]["id"] == 3 + assert body["is_recursive"] is True + assert body["is_incident_visible"] is True + assert body["is_request_visible"] is False + assert body["name"] == "Network" + + +def test_update_itil_category_sends_patch(client: Any) -> None: + """``update_itil_category`` patches the per-id endpoint.""" + + rec = TransportRecorder() + rec.install(client) + client.update_itil_category(9, PatchITILCategory(name="renamed")) + assert rec.calls[0]["method"] == "PATCH" + assert rec.calls[0]["endpoint"] == "Dropdowns/ITILCategory/9" + assert rec.calls[0]["json"] == {"name": "renamed"} + + +def test_delete_itil_category_with_force(client: Any) -> None: + """``delete_itil_category(force=True)`` ships the force flag.""" + + rec = TransportRecorder() + rec.install(client) + client.delete_itil_category(9, force=True) + call = rec.calls[0] + assert call["method"] == "DELETE" + assert call["endpoint"] == "Dropdowns/ITILCategory/9" + assert call["json"] == {"force": True} + + +def test_delete_itil_category_without_force(client: Any) -> None: + """Without ``force`` the body carries no force flag.""" + + rec = TransportRecorder() + rec.install(client) + client.delete_itil_category(9) + call = rec.calls[0] + assert call["method"] == "DELETE" + assert call["endpoint"] == "Dropdowns/ITILCategory/9" + assert not call["json"] + + +def _read(client: Any) -> Any: + return client.get_itil_category(1) + + +def _create(client: Any) -> Any: + return client.create_itil_category(PostITILCategory(name="x")) + + +def _update(client: Any) -> Any: + return client.update_itil_category(1, PatchITILCategory(name="x")) + + +def _delete(client: Any) -> Any: + return client.delete_itil_category(1, force=True) + + +@pytest.mark.parametrize("call", [_read]) +def test_read_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every read helper raises on a non-success status.""" + + FailingTransportRecorder(404).install(client) + with pytest.raises(ValueError): + call(client) + + +@pytest.mark.parametrize("call", [_create]) +def test_create_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every create helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + call(client) + + +@pytest.mark.parametrize("call", [_update]) +def test_update_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every update helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + call(client) + + +@pytest.mark.parametrize("call", [_delete]) +def test_delete_helpers_raise_on_failure( + client: Any, call: Callable[[Any], Awaitable[Any]] +) -> None: + """Every delete helper raises on a non-success status.""" + + FailingTransportRecorder(500).install(client) + with pytest.raises(ValueError): + call(client) + + +def test_iter_search_itil_categories_yields_every_page(client: Any) -> None: + """The generator advances ``start`` and forwards ``skip_entity``.""" + + pages = [[GetITILCategory(id=i) for i in range(3)], [GetITILCategory(id=99)]] + starts: list[int] = [] + skips: list[bool] = [] + + def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + skips.append(skip_entity) + index = start // limit + return pages[index] if index < len(pages) else [] + + client.search_itil_categories = fake_search + + batches = [ + batch + for batch in client.iter_search_itil_categories( + "name==x", batch_size=3, skip_entity=True + ) + ] + + assert starts == [0, 3] + assert skips == [True, True] + assert [len(b) for b in batches] == [3, 1] + + +def test_iter_search_itil_categories_stops_on_a_single_short_page( + client: Any, +) -> None: + """One short page is the last page; no second request is made.""" + + starts: list[int] = [] + + def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + return [GetITILCategory(id=1)] + + client.search_itil_categories = fake_search + + batches = [batch for batch in client.iter_search_itil_categories()] + + assert starts == [0] + assert len(batches) == 1 + + +def test_iter_search_itil_categories_yields_nothing_when_empty( + client: Any, +) -> None: + """An empty first page yields no batch at all.""" + + starts: list[int] = [] + + def fake_search( + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[GetITILCategory]: + starts.append(start) + assert len(starts) < 10, "the walk did not stop" + return [] + + client.search_itil_categories = fake_search + + assert [batch for batch in client.iter_search_itil_categories()] == [] diff --git a/glpi_python_client/_sync/clients/client.py b/glpi_python_client/_sync/clients/client.py index 55ba25a..ed0b7c5 100644 --- a/glpi_python_client/_sync/clients/client.py +++ b/glpi_python_client/_sync/clients/client.py @@ -26,6 +26,7 @@ EntityMixin, FollowupMixin, GroupMixin, + ITILCategoryMixin, KBArticleCommentMixin, KBArticleMixin, KBArticleRevisionMixin, @@ -63,6 +64,7 @@ class GlpiClient( GroupMixin, LocationMixin, ContractTypeMixin, + ITILCategoryMixin, KBCategoryMixin, KBArticleMixin, KBArticleCommentMixin, diff --git a/glpi_python_client/_sync/clients/commons/_constants.py b/glpi_python_client/_sync/clients/commons/_constants.py index 0050153..b509f03 100644 --- a/glpi_python_client/_sync/clients/commons/_constants.py +++ b/glpi_python_client/_sync/clients/commons/_constants.py @@ -24,6 +24,7 @@ # dropdowns/ CONTRACT_TYPE_ENDPOINT = "Dropdowns/ContractType" LOCATION_ENDPOINT = "Dropdowns/Location" +ITIL_CATEGORY_ENDPOINT = "Dropdowns/ITILCategory" # management/ CONTRACT_ENDPOINT = "Management/Contract" @@ -54,6 +55,7 @@ "ENTITY_ENDPOINT", "FOLLOWUP_SUFFIX", "GROUP_ENDPOINT", + "ITIL_CATEGORY_ENDPOINT", "KB_ARTICLE_ENDPOINT", "KB_CATEGORY_ENDPOINT", "KB_COMMENT_SUFFIX", diff --git a/glpi_python_client/models/__init__.py b/glpi_python_client/models/__init__.py index 5038f31..03a8d68 100644 --- a/glpi_python_client/models/__init__.py +++ b/glpi_python_client/models/__init__.py @@ -75,12 +75,16 @@ ) from glpi_python_client.models.api_schema.dropdowns import ( DeleteContractType, + DeleteITILCategory, DeleteLocation, GetContractType, + GetITILCategory, GetLocation, PatchContractType, + PatchITILCategory, PatchLocation, PostContractType, + PostITILCategory, PostLocation, ) from glpi_python_client.models.api_schema.enums import ( @@ -147,6 +151,7 @@ "DeleteEntity", "DeleteFollowup", "DeleteGroup", + "DeleteITILCategory", "DeleteKBArticle", "DeleteKBArticleComment", "DeleteKBCategory", @@ -168,6 +173,7 @@ "GetEntity", "GetFollowup", "GetGroup", + "GetITILCategory", "GetKBArticle", "GetKBArticleComment", "GetKBArticleRevision", @@ -205,6 +211,7 @@ "PatchEntity", "PatchFollowup", "PatchGroup", + "PatchITILCategory", "PatchKBArticle", "PatchKBArticleComment", "PatchKBCategory", @@ -224,6 +231,7 @@ "PostEntity", "PostFollowup", "PostGroup", + "PostITILCategory", "PostKBArticle", "PostKBArticleComment", "PostKBCategory", diff --git a/glpi_python_client/models/api_schema/dropdowns/__init__.py b/glpi_python_client/models/api_schema/dropdowns/__init__.py index 59e645e..9a4f047 100644 --- a/glpi_python_client/models/api_schema/dropdowns/__init__.py +++ b/glpi_python_client/models/api_schema/dropdowns/__init__.py @@ -6,6 +6,12 @@ PatchContractType, PostContractType, ) +from glpi_python_client.models.api_schema.dropdowns._itil_category import ( + DeleteITILCategory, + GetITILCategory, + PatchITILCategory, + PostITILCategory, +) from glpi_python_client.models.api_schema.dropdowns._location import ( DeleteLocation, GetLocation, @@ -15,11 +21,15 @@ __all__ = [ "DeleteContractType", + "DeleteITILCategory", "DeleteLocation", "GetContractType", + "GetITILCategory", "GetLocation", "PatchContractType", + "PatchITILCategory", "PatchLocation", "PostContractType", + "PostITILCategory", "PostLocation", ] diff --git a/glpi_python_client/models/api_schema/dropdowns/_itil_category.py b/glpi_python_client/models/api_schema/dropdowns/_itil_category.py new file mode 100644 index 0000000..e9754ae --- /dev/null +++ b/glpi_python_client/models/api_schema/dropdowns/_itil_category.py @@ -0,0 +1,199 @@ +"""GLPI ``ITILCategory`` schemas for the ``/Dropdowns/ITILCategory`` endpoints. + +The field layout mirrors ``components.schemas.ITILCategory`` from the GLPI +OpenAPI contract. Read-only contract fields (``id``, ``completename``, +``level``) are excluded from request models. +""" + +from __future__ import annotations + +from datetime import datetime + +from glpi_python_client.models._base import GlpiModel +from glpi_python_client.models.api_schema._common import IdNameRef + + +class GetITILCategory(GlpiModel): + """Response shape returned by ``GET /Dropdowns/ITILCategory`` endpoints. + + Mirrors ``components.schemas.ITILCategory``. No field carries a + ``description`` in the OpenAPI contract; the parameter notes below + reflect the field names, types and ``readOnly`` flags as advertised. + + Parameters + ---------- + id : int | None, optional + Native GLPI identifier (``readOnly``). + name : str | None, optional + Short display name of the category. + completename : str | None, optional + Full hierarchical path of the category (``readOnly``). + level : int | None, optional + Depth of the category in the hierarchy tree (``readOnly``). + comment : str | None, optional + Free-form comment associated with the category. + entity : IdNameRef | None, optional + Reference to the owning GLPI entity. + is_recursive : bool | None, optional + Whether the category is visible to child entities. + parent : IdNameRef | None, optional + Reference to the parent category in the hierarchy. + user : IdNameRef | None, optional + Reference to the user in charge of the category. + group : IdNameRef | None, optional + Reference to the group in charge of the category. + code : str | None, optional + Short code assigned to the category. + is_helpdesk_visible : bool | None, optional + Whether the category is visible in the simplified interface. + ticket_incident_template : IdNameRef | None, optional + Default ticket template for incidents. + ticket_request_template : IdNameRef | None, optional + Default ticket template for requests. + change_template : IdNameRef | None, optional + Default change template. + problem_template : IdNameRef | None, optional + Default problem template. + is_incident_visible : bool | None, optional + Whether the category can be used on incidents. + is_request_visible : bool | None, optional + Whether the category can be used on requests. + is_change_visible : bool | None, optional + Whether the category can be used on changes. + is_problem_visible : bool | None, optional + Whether the category can be used on problems. + knowbase_category : IdNameRef | None, optional + Reference to the linked knowledge base category. + date_creation : datetime | None, optional + Creation timestamp of the record (``format: date-time``). + date_mod : datetime | None, optional + Last modification timestamp of the record (``format: date-time``). + """ + + id: int | None = None + name: str | None = None + completename: str | None = None + level: int | None = None + comment: str | None = None + entity: IdNameRef | None = None + is_recursive: bool | None = None + parent: IdNameRef | None = None + user: IdNameRef | None = None + group: IdNameRef | None = None + code: str | None = None + is_helpdesk_visible: bool | None = None + ticket_incident_template: IdNameRef | None = None + ticket_request_template: IdNameRef | None = None + change_template: IdNameRef | None = None + problem_template: IdNameRef | None = None + is_incident_visible: bool | None = None + is_request_visible: bool | None = None + is_change_visible: bool | None = None + is_problem_visible: bool | None = None + knowbase_category: IdNameRef | None = None + date_creation: datetime | None = None + date_mod: datetime | None = None + + +class PostITILCategory(GlpiModel): + """Request body for ``POST /Dropdowns/ITILCategory``. + + Read-only contract fields (``id``, ``completename``, ``level``) are + intentionally excluded because the server rejects them on input. + + Parameters + ---------- + name : str | None, optional + Short display name of the category. + comment : str | None, optional + Free-form comment associated with the category. + entity : IdNameRef | None, optional + Reference to the owning GLPI entity. + is_recursive : bool | None, optional + Whether the category is visible to child entities. + parent : IdNameRef | None, optional + Reference to the parent category in the hierarchy. + user : IdNameRef | None, optional + Reference to the user in charge of the category. + group : IdNameRef | None, optional + Reference to the group in charge of the category. + code : str | None, optional + Short code assigned to the category. + is_helpdesk_visible : bool | None, optional + Whether the category is visible in the simplified interface. + ticket_incident_template : IdNameRef | None, optional + Default ticket template for incidents. + ticket_request_template : IdNameRef | None, optional + Default ticket template for requests. + change_template : IdNameRef | None, optional + Default change template. + problem_template : IdNameRef | None, optional + Default problem template. + is_incident_visible : bool | None, optional + Whether the category can be used on incidents. + is_request_visible : bool | None, optional + Whether the category can be used on requests. + is_change_visible : bool | None, optional + Whether the category can be used on changes. + is_problem_visible : bool | None, optional + Whether the category can be used on problems. + knowbase_category : IdNameRef | None, optional + Reference to the linked knowledge base category. + date_creation : datetime | None, optional + Creation timestamp to set on the record (``format: date-time``). + date_mod : datetime | None, optional + Last modification timestamp to set on the record + (``format: date-time``). + """ + + name: str | None = None + comment: str | None = None + entity: IdNameRef | None = None + is_recursive: bool | None = None + parent: IdNameRef | None = None + user: IdNameRef | None = None + group: IdNameRef | None = None + code: str | None = None + is_helpdesk_visible: bool | None = None + ticket_incident_template: IdNameRef | None = None + ticket_request_template: IdNameRef | None = None + change_template: IdNameRef | None = None + problem_template: IdNameRef | None = None + is_incident_visible: bool | None = None + is_request_visible: bool | None = None + is_change_visible: bool | None = None + is_problem_visible: bool | None = None + knowbase_category: IdNameRef | None = None + date_creation: datetime | None = None + date_mod: datetime | None = None + + +class PatchITILCategory(PostITILCategory): + """Request body for ``PATCH /Dropdowns/ITILCategory/{id}``. + + The contract uses the same ``ITILCategory`` schema for create and + partial-update bodies; ``PatchITILCategory`` is kept distinct so client + mixins can express the intent of the operation explicitly. + """ + + +class DeleteITILCategory(GlpiModel): + """Query parameters for ``DELETE /Dropdowns/ITILCategory/{id}``. + + Parameters + ---------- + force : bool | None, optional + When ``True``, permanently delete the category instead of moving + the record to the GLPI trash. When ``False`` or :data:`None`, + the server applies its default behaviour. + """ + + force: bool | None = None + + +__all__ = [ + "DeleteITILCategory", + "GetITILCategory", + "PatchITILCategory", + "PostITILCategory", +] diff --git a/glpi_python_client/models/api_schema/dropdowns/tests/test_dropdowns_schemas.py b/glpi_python_client/models/api_schema/dropdowns/tests/test_dropdowns_schemas.py index fa34008..dc33407 100644 --- a/glpi_python_client/models/api_schema/dropdowns/tests/test_dropdowns_schemas.py +++ b/glpi_python_client/models/api_schema/dropdowns/tests/test_dropdowns_schemas.py @@ -3,9 +3,13 @@ from __future__ import annotations from glpi_python_client.models.api_schema.dropdowns import ( + DeleteITILCategory, DeleteLocation, + GetITILCategory, GetLocation, + PatchITILCategory, PatchLocation, + PostITILCategory, PostLocation, ) @@ -59,3 +63,66 @@ def test_delete_location_default() -> None: """``DeleteLocation`` exposes ``force`` as optional.""" assert DeleteLocation().force is None + + +def test_get_itil_category_full_payload() -> None: + """``GetITILCategory`` accepts every contract field of ``ITILCategory``.""" + + ref = {"id": 5, "name": "ref"} + payload = { + "id": 3, + "name": "Network", + "completename": "IT > Network", + "level": 2, + "comment": "network issues", + "entity": {"id": 7, "name": "root"}, + "is_recursive": True, + "parent": {"id": 1, "name": "IT"}, + "user": ref, + "group": ref, + "code": "NET", + "is_helpdesk_visible": True, + "ticket_incident_template": ref, + "ticket_request_template": ref, + "change_template": ref, + "problem_template": ref, + "is_incident_visible": True, + "is_request_visible": False, + "is_change_visible": True, + "is_problem_visible": False, + "knowbase_category": ref, + "date_creation": "2026-01-02T03:04:05+00:00", + "date_mod": "2026-01-03T03:04:05+00:00", + } + category = GetITILCategory.model_validate(payload) + assert category.completename == "IT > Network" + assert category.level == 2 + assert category.entity is not None + assert category.entity.id == 7 + assert category.parent is not None + assert category.parent.id == 1 + assert category.knowbase_category is not None + assert category.is_request_visible is False + assert category.date_mod is not None + assert category.extra_payload == {} + + +def test_post_itil_category_rejects_read_only_fields() -> None: + """Read-only fields land in ``extra_payload`` for server-side rejection.""" + + for forbidden in ("id", "completename", "level"): + category = PostITILCategory.model_validate({"name": "Net", forbidden: "x"}) + assert category.extra_payload == {forbidden: "x"} + + +def test_patch_itil_category_partial_body() -> None: + """``PatchITILCategory`` accepts a partial body.""" + + PatchITILCategory.model_validate({"comment": "moved"}) + + +def test_delete_itil_category_default() -> None: + """``DeleteITILCategory`` exposes ``force`` as optional.""" + + assert DeleteITILCategory().force is None + assert DeleteITILCategory(force=True).force is True diff --git a/glpi_python_client/testing/tests/test_exports.py b/glpi_python_client/testing/tests/test_exports.py index 8f947db..47abd94 100644 --- a/glpi_python_client/testing/tests/test_exports.py +++ b/glpi_python_client/testing/tests/test_exports.py @@ -104,3 +104,27 @@ def test_user_authorization_exported_from_top_level_and_models() -> None: for module in (glpi_python_client, models): assert hasattr(module, "UserAuthorization") assert "UserAuthorization" in module.__all__ + + +_ITIL_CATEGORY_MODELS = ( + "GetITILCategory", + "PostITILCategory", + "PatchITILCategory", + "DeleteITILCategory", +) + + +def test_itil_category_models_exported_from_top_level() -> None: + """Every ITILCategory model is importable from ``glpi_python_client``.""" + + for name in _ITIL_CATEGORY_MODELS: + assert hasattr(glpi_python_client, name), name + assert name in glpi_python_client.__all__, name + + +def test_itil_category_models_exported_from_models_package() -> None: + """Every ITILCategory model is importable from ``glpi_python_client.models``.""" + + for name in _ITIL_CATEGORY_MODELS: + assert hasattr(models, name), name + assert name in models.__all__, name diff --git a/pyproject.toml b/pyproject.toml index bd797b5..82301b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ exclude = [ [project] name = "glpi-python-client" -version = "0.6.9" +version = "0.6.10" description = "A typed Python client for GLPI ITSM APIs." readme = "README.md" requires-python = ">=3.11" diff --git a/skills/README.md b/skills/README.md index 25e835c..99f92c7 100644 --- a/skills/README.md +++ b/skills/README.md @@ -12,7 +12,7 @@ These skills are source-tree project material. They are included in source distr | `glpi-ticket-workflow` | Search, fetch, create, update, or delete tickets | `GetTicket`, `PostTicket`, `PatchTicket`, `DeleteTicket` | | `glpi-ticket-timeline` | Read timeline records or write followups, tasks, solutions, and document links | `PostFollowup`, `PostTicketTask`, `PostSolution`, `PostTimelineDocument` (plus matching Get/Patch/Delete for followups/tasks/solutions; document reads return `GetDocument`, not a `GetTimelineDocument`) | | `glpi-document-workflow` | Manage document metadata, upload binary content, download binaries | `GetDocument`, `PostDocument`, `PatchDocument`, `DeleteDocument` | -| `glpi-user-location-provisioning` | Search and provision users, locations, entities, and groups; group recursion and user authorizations | `GetUser`, `PostUser`, `GetLocation`, `PostLocation`, `GetEntity`, `PostEntity`, `GetGroup`, `PostGroup`, `UserAuthorization` | +| `glpi-user-location-provisioning` | Search and provision users, locations, entities, groups, and ITIL categories; group recursion and user authorizations | `GetUser`, `PostUser`, `GetLocation`, `PostLocation`, `GetEntity`, `PostEntity`, `GetGroup`, `PostGroup`, `GetITILCategory`, `PostITILCategory`, `UserAuthorization` | | `glpi-reporting-and-context` | Aggregate ticket statistics, aggregate task durations, or load one ticket context bundle | `GlpiClient`, `GlpiTicketContext`, public enums | | `glpi-team-members` | List, add, or remove ticket team members | `GetTeamMember`, `PostTeamMember` | | `glpi-knowledge-base` | Search, read, or write KB articles, categories, comments, and revisions | `GetKBArticle`, `PostKBArticle`, `GetKBCategory`, `GetKBArticleComment`, `GetKBArticleRevision` | diff --git a/skills/glpi-asset-workflow/SKILL.md b/skills/glpi-asset-workflow/SKILL.md index 6fb7287..3bfa6cc 100644 --- a/skills/glpi-asset-workflow/SKILL.md +++ b/skills/glpi-asset-workflow/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials allowed to read or write assets." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Asset Workflow diff --git a/skills/glpi-client-setup/SKILL.md b/skills/glpi-client-setup/SKILL.md index bfd4efe..dea767e 100644 --- a/skills/glpi-client-setup/SKILL.md +++ b/skills/glpi-client-setup/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to a GLPI v2 API, and valid GLPI credentials." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Client Setup diff --git a/skills/glpi-contract-workflow/SKILL.md b/skills/glpi-contract-workflow/SKILL.md index 08d851a..3599a5e 100644 --- a/skills/glpi-contract-workflow/SKILL.md +++ b/skills/glpi-contract-workflow/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials allowed to read or write contracts." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Contract Workflow diff --git a/skills/glpi-document-workflow/SKILL.md b/skills/glpi-document-workflow/SKILL.md index cf4111d..a99571d 100644 --- a/skills/glpi-document-workflow/SKILL.md +++ b/skills/glpi-document-workflow/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and v1 credentials configured on the client for binary uploads." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Document Workflow diff --git a/skills/glpi-knowledge-base/SKILL.md b/skills/glpi-knowledge-base/SKILL.md index 6291611..feb786b 100644 --- a/skills/glpi-knowledge-base/SKILL.md +++ b/skills/glpi-knowledge-base/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and — for category writes only — a legacy v1 session (v1_base_url + v1_user_token)." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Knowledge Base diff --git a/skills/glpi-plugin-fields/SKILL.md b/skills/glpi-plugin-fields/SKILL.md index a8c3805..dfbd2bd 100644 --- a/skills/glpi-plugin-fields/SKILL.md +++ b/skills/glpi-plugin-fields/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, the GLPI Fields plugin installed server-side, and a legacy v1 session (v1_base_url + v1_user_token) — every method in this family goes over the v1 API." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Plugin Fields diff --git a/skills/glpi-reporting-and-context/SKILL.md b/skills/glpi-reporting-and-context/SKILL.md index dc10de1..8c7bbf6 100644 --- a/skills/glpi-reporting-and-context/SKILL.md +++ b/skills/glpi-reporting-and-context/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials allowed to read tickets, tasks, users, entities, and timeline records." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Reporting And Context diff --git a/skills/glpi-team-members/SKILL.md b/skills/glpi-team-members/SKILL.md index 1e87501..3b2cd5b 100644 --- a/skills/glpi-team-members/SKILL.md +++ b/skills/glpi-team-members/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials allowed to manage ticket teams." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Team Members diff --git a/skills/glpi-ticket-timeline/SKILL.md b/skills/glpi-ticket-timeline/SKILL.md index 3c3467c..8f02b07 100644 --- a/skills/glpi-ticket-timeline/SKILL.md +++ b/skills/glpi-ticket-timeline/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, and network access to the GLPI v2 API." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Ticket Timeline diff --git a/skills/glpi-ticket-workflow/SKILL.md b/skills/glpi-ticket-workflow/SKILL.md index 929cee3..b6c11b0 100644 --- a/skills/glpi-ticket-workflow/SKILL.md +++ b/skills/glpi-ticket-workflow/SKILL.md @@ -5,7 +5,7 @@ license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials accepted by GlpiClient." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI Ticket Workflow diff --git a/skills/glpi-user-location-provisioning/SKILL.md b/skills/glpi-user-location-provisioning/SKILL.md index 48be143..6d93231 100644 --- a/skills/glpi-user-location-provisioning/SKILL.md +++ b/skills/glpi-user-location-provisioning/SKILL.md @@ -1,11 +1,11 @@ --- name: glpi-user-location-provisioning -description: "Search GLPI users, locations, and entities, or create, update, and delete users and locations and entities with the synchronous glpi_python_client.GlpiClient or the asynchronous AsyncGlpiClient, and the matching Get/Post/Patch/Delete models. Use for user lookup, entity lookup, location lookup, user provisioning, location creation, GLPI entity defaults, or RSQL filters." +description: "Search GLPI users, locations, and entities, or create, update, and delete users and locations and entities with the synchronous glpi_python_client.GlpiClient or the asynchronous AsyncGlpiClient, and the matching Get/Post/Patch/Delete models. Use for user lookup, entity lookup, location lookup, user provisioning, location creation, GLPI entity defaults, ITIL category lookup and creation (search_itil_categories, create_itil_category), or RSQL filters." license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to the GLPI v2 API, and credentials allowed to read or write users, locations, and entities." metadata: package: glpi-python-client - version: "0.6.9" + version: "0.6.10" --- # GLPI User, Location, And Entity Provisioning @@ -24,6 +24,10 @@ Users live under `/Administration/User`, entities under `/Administration/Entity` 6. Delete with `delete_user(user_id, force=True|False|None)` and the matching `delete_location` / `delete_entity` helpers. 7. Group recursion and user authorizations are not in the v2 API (its `Group` schema has no `is_recursive`, and there is no route for a user's profile/entity rows), so they go through the legacy v1 session and need `v1_base_url` / `v1_user_token`; without them each raises `RuntimeError`. `set_group_recursive(group_id, recursive=True)` sets the flag on a group. `list_user_authorizations(user_id)` returns `UserAuthorization` rows (`id`, `user_id`, `profile_id`, `entity_id`, `is_recursive`, `is_dynamic`, `is_default_profile`); `add_user_authorization(user_id, profile_id=..., entity_id=..., recursive=False)` returns the new row id; `update_user_authorization(authorization_id, entity_id=None, recursive=None)` changes only what you pass and raises `GlpiValidationError` with neither; `delete_user_authorization(authorization_id)` removes a row. A v1 write answered `false` raises `GlpiProtocolError` with the server's message. +## ITIL categories + +ITIL categories live under `/Dropdowns/ITILCategory` and follow the same shape: `search_itil_categories(rsql_filter, limit=..., start=..., skip_entity=False)`, `iter_search_itil_categories(rsql_filter, batch_size=..., skip_entity=False)`, `get_itil_category(category_id, skip_entity=False)`, `create_itil_category(PostITILCategory(...))`, `update_itil_category(category_id, PatchITILCategory(...))` and `delete_itil_category(category_id, force=...)`. A search and a fetch are narrowed by the client's `GLPI-Entity` headers; pass `skip_entity=True` to look across every entity the caller can see. A category is placed with `entity=IdNameRef(id=...)` and nested under another with `parent=IdNameRef(id=...)`; `is_recursive`, `is_incident_visible`, `is_request_visible`, `is_change_visible` and `is_problem_visible` control where it can be used. `id`, `completename` and `level` are read-only. + ## Examples Search for a user by username: