From b0b147c7327dadc0c60085c86d5f6aa94ddf93a6 Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 00:44:09 +0100 Subject: [PATCH 1/3] Add pending reason operations to both GLPI clients: the v2 catalogue read and the v1 per-ticket item get, set and clear, with their models and docs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 + docs/api_reference.rst | 19 + docs/user_guide.rst | 56 +++ glpi_python_client/__init__.py | 4 + .../_async/clients/api/__init__.py | 2 + .../_async/clients/api/assistance/__init__.py | 5 +- .../clients/api/assistance/_pending_reason.py | 331 ++++++++++++++++++ .../assistance/tests/test_pending_reason.py | 199 +++++++++++ glpi_python_client/_async/clients/client.py | 2 + .../_async/clients/commons/_constants.py | 2 + .../_sync/clients/api/__init__.py | 2 + .../_sync/clients/api/assistance/__init__.py | 5 +- .../clients/api/assistance/_pending_reason.py | 331 ++++++++++++++++++ .../assistance/tests/test_pending_reason.py | 199 +++++++++++ glpi_python_client/_sync/clients/client.py | 2 + .../_sync/clients/commons/_constants.py | 2 + glpi_python_client/models/__init__.py | 4 + .../models/api_schema/assistance/__init__.py | 6 + .../api_schema/assistance/_pending_reason.py | 102 ++++++ .../testing/tests/test_exports.py | 12 + skills/glpi-ticket-workflow/SKILL.md | 2 +- 21 files changed, 1301 insertions(+), 3 deletions(-) create mode 100644 glpi_python_client/_async/clients/api/assistance/_pending_reason.py create mode 100644 glpi_python_client/_async/clients/api/assistance/tests/test_pending_reason.py create mode 100644 glpi_python_client/_sync/clients/api/assistance/_pending_reason.py create mode 100644 glpi_python_client/_sync/clients/api/assistance/tests/test_pending_reason.py create mode 100644 glpi_python_client/models/api_schema/assistance/_pending_reason.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a654cc2..e4d42bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ 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/). +## Unreleased + +### Added + +- **`list_pending_reasons`, `iter_pending_reasons`, + `get_ticket_pending_reason`, `set_ticket_pending_reason` and + `clear_ticket_pending_reason`** on both clients, from a new + `PendingReasonMixin`. The catalogue is read from the v2 + `/Assistance/PendingReason` route; a ticket's pending-reason item goes + through the legacy v1 API, because the v2 item schema omits the + catalogue id and no v2 route writes an item. The three ticket methods + need the v1 session and raise `RuntimeError` without one. + `set_ticket_pending_reason` creates or updates the item after reading + it and does not change the ticket status. +- **`PendingReason` and `PendingReasonItem`** read models, exported from + the package root and from `glpi_python_client.models`. + ## 0.6.10 — 2026-11-16 A minor addition: the GLPI v2 `/Dropdowns/ITILCategory` routes, so a caller diff --git a/docs/api_reference.rst b/docs/api_reference.rst index cbe0340..318970a 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -307,6 +307,25 @@ Ticket Team Members :undoc-members: :show-inheritance: +Pending reasons +--------------- + +Models for the GLPI pending-reason catalogue (v2) and a ticket's pending +reason item (legacy v1). The companion mixin methods are exposed on +:class:`GlpiClient` / :class:`AsyncGlpiClient` as ``list_pending_reasons``, +``iter_pending_reasons``, ``get_ticket_pending_reason``, +``set_ticket_pending_reason`` and ``clear_ticket_pending_reason``. + +.. autoclass:: PendingReason + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: PendingReasonItem + :members: + :undoc-members: + :show-inheritance: + Documents --------- diff --git a/docs/user_guide.rst b/docs/user_guide.rst index 41de66a..f2bfb8b 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -1080,6 +1080,62 @@ to ``list_item_plugin_field_rows``, ``create_item_plugin_field_row``, or ``update_item_plugin_field_row`` only when you need the raw v1 row shape. +Pending reasons +~~~~~~~~~~~~~~~ + +A pause is ticket status ``4`` (Pending) plus at most one item linking +the ticket to an entry of the pending-reason catalogue. The catalogue is +read from the v2 API; the ticket's item needs the legacy v1 session +(``v1_base_url`` and ``v1_user_token``), because the v2 item schema does +not say *which* reason a ticket carries and no v2 route writes an item. +Without the v1 session the three ticket methods raise ``RuntimeError``. + +.. code-block:: python + + from glpi_python_client import GlpiClient, GlpiTicketStatus, PatchTicket + + with GlpiClient( + glpi_api_url="https://glpi.example.com/api.php/v2", + server_timezone="Europe/Paris", + client_id="oauth-client-id", + client_secret="oauth-client-secret", + username="api-user", + password="api-password", + v1_base_url="https://glpi.example.com/apirest.php", + v1_user_token="legacy-user-token", + ) as client: + reasons = client.list_pending_reasons() + reason = reasons[0] + + # The status is the caller's to set: the item alone does not pause. + client.update_ticket(ticket_id, PatchTicket(status=GlpiTicketStatus.PENDING)) + item = client.set_ticket_pending_reason( + ticket_id, + reason.id, + followup_frequency=reason.followup_frequency or 0, + followups_before_resolution=reason.followups_before_resolution or 0, + ) + print(item.pendingreasons_id) + + print(client.get_ticket_pending_reason(ticket_id)) # item or None + + client.clear_ticket_pending_reason(ticket_id) # True, or False if none + +Things worth knowing: + +* ``set_ticket_pending_reason`` creates the item when the ticket has none + and changes it otherwise; it never provokes GLPI's duplicate-key error. + It does **not** change the ticket status. An item set on a ticket that + is not pending is stored but has no effect, and GLPI removes it when + the ticket next leaves status ``4``. +* The item does not copy the catalogue's ``followup_frequency``: pass the + frequencies wanted, or the item stores ``0``. +* ``clear_ticket_pending_reason`` leaves the ticket at status ``4``, + without a reason. Leaving status ``4`` removes the item by itself. +* A reason id that is not in the catalogue is stored without error. +* None of these calls adds a followup to the timeline. The GLPI web + interface pauses through a followup, which does. + Aggregated ticket context ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/glpi_python_client/__init__.py b/glpi_python_client/__init__.py index 6676651..209732d 100644 --- a/glpi_python_client/__init__.py +++ b/glpi_python_client/__init__.py @@ -112,6 +112,8 @@ PatchTicketTask, PatchTimelineDocument, PatchUser, + PendingReason, + PendingReasonItem, PostComputer, PostContract, PostContractCost, @@ -237,6 +239,8 @@ "PatchTicketTask", "PatchTimelineDocument", "PatchUser", + "PendingReason", + "PendingReasonItem", "PostComputer", "PostContract", "PostContractCost", diff --git a/glpi_python_client/_async/clients/api/__init__.py b/glpi_python_client/_async/clients/api/__init__.py index 2933c6b..849bba1 100644 --- a/glpi_python_client/_async/clients/api/__init__.py +++ b/glpi_python_client/_async/clients/api/__init__.py @@ -16,6 +16,7 @@ ) from glpi_python_client._async.clients.api.assets import ComputerMixin from glpi_python_client._async.clients.api.assistance import ( + PendingReasonMixin, TeamMemberMixin, TicketMixin, ) @@ -58,6 +59,7 @@ "KBArticleRevisionMixin", "KBCategoryMixin", "LocationMixin", + "PendingReasonMixin", "PluginFieldsMixin", "SolutionMixin", "TeamMemberMixin", diff --git a/glpi_python_client/_async/clients/api/assistance/__init__.py b/glpi_python_client/_async/clients/api/assistance/__init__.py index f7dfdea..c72d5a1 100644 --- a/glpi_python_client/_async/clients/api/assistance/__init__.py +++ b/glpi_python_client/_async/clients/api/assistance/__init__.py @@ -2,7 +2,10 @@ from __future__ import annotations +from glpi_python_client._async.clients.api.assistance._pending_reason import ( + PendingReasonMixin, +) from glpi_python_client._async.clients.api.assistance._team import TeamMemberMixin from glpi_python_client._async.clients.api.assistance._ticket import TicketMixin -__all__ = ["TeamMemberMixin", "TicketMixin"] +__all__ = ["PendingReasonMixin", "TeamMemberMixin", "TicketMixin"] diff --git a/glpi_python_client/_async/clients/api/assistance/_pending_reason.py b/glpi_python_client/_async/clients/api/assistance/_pending_reason.py new file mode 100644 index 0000000..1552f95 --- /dev/null +++ b/glpi_python_client/_async/clients/api/assistance/_pending_reason.py @@ -0,0 +1,331 @@ +"""GLPI pending reasons: the v2 catalogue and the v1 per-ticket item. + +A pause is ticket status ``4`` (Pending) plus at most one +``PendingReason_Item`` row linking the ticket to an entry of the +``PendingReason`` catalogue. The two halves live on different APIs: + +* The catalogue is read from the v2 ``/Assistance/PendingReason`` routes + (list and per-id). Its entries are configuration objects, so there is + no create, update or delete here. Fields are ``id``, ``name``, + ``entity``, ``is_recursive``, ``is_default``, ``followup_frequency`` + (seconds), ``followups_before_resolution``, ``comment`` and the + template and calendar links. +* The ticket's item is handled through the legacy v1 API. The v2 route + ``/Assistance/Ticket/{id}/PendingReason`` returns the item (404 when + there is none) but its schema omits ``pendingreasons_id``: it tells + that a ticket is paused with a reason, not which. No v2 route writes + an item. The three ticket methods therefore need the v1 session and + raise :class:`RuntimeError` without one. + +Behaviour of the v1 item routes, as measured on a server exposing both +APIs: + +* ``GET Ticket/{id}/PendingReason_Item`` returns a list of at most one + row. +* ``POST PendingReason_Item`` creates the item (201). It changes neither + the ticket status nor its timeline, and works whatever the status. A + second POST for the same ticket answers 400 (duplicate key on + ``items_id`` and ``itemtype``). The item does not copy the catalogue's + ``followup_frequency``: an omitted frequency is stored as ``0``. +* ``PUT PendingReason_Item/{id}`` changes the reason and the + frequencies. ``PUT Ticket/{id}`` with ``pendingreasons_id`` answers + success and ignores the reason. +* ``DELETE PendingReason_Item/{id}`` removes the item and leaves the + status at ``4``. Leaving status ``4`` (to solved, closed or processing) + removes the item by itself. +* A reason id that is not in the catalogue is stored silently. +* The GLPI interface pauses through a followup (``POST ITILFollowup`` + with ``pending=1`` and ``pendingreasons_id``), which also adds a + visible followup to the timeline. The methods here add none. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator + +from glpi_python_client._async.clients.commons._constants import ( + PENDING_REASON_ENDPOINT, + GlpiId, +) +from glpi_python_client._async.clients.commons._payloads import model_from_payload +from glpi_python_client._async.clients.commons._transport import TransportMixin +from glpi_python_client._errors import GlpiProtocolError +from glpi_python_client.models.api_schema.assistance._pending_reason import ( + PendingReason, + PendingReasonItem, +) + +_V1_FEATURE_LABEL = "pending reason helpers" +_ITEM_RESOURCE = "PendingReason_Item" +_TICKET_ITEMTYPE = "Ticket" + + +class PendingReasonMixin(TransportMixin): + """Read the pending-reason catalogue and manage a ticket's pending reason.""" + + async def list_pending_reasons( + self, + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[PendingReason]: + """List the entries of the pending-reason catalogue (v2). + + 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 + read spans every entity the caller has access to. + + Returns + ------- + list[PendingReason] + Catalogue entries matching the filter. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + params: dict[str, object] = {"limit": limit, "start": start} + if rsql_filter: + params["filter"] = rsql_filter + return await self._resource_list( + PENDING_REASON_ENDPOINT, + PendingReason, + params=params, + skip_entity=skip_entity, + ) + + async def iter_pending_reasons( + self, + rsql_filter: str = "", + *, + batch_size: int = 50, + skip_entity: bool = False, + ) -> AsyncIterator[list[PendingReason]]: + """Yield successive pages of the catalogue 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. + + Yields + ------ + list[PendingReason] + One page per iteration. The last batch may be shorter than + ``batch_size``. + """ + + start = 0 + while True: + batch = await self.list_pending_reasons( + 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_ticket_pending_reason( + self, ticket_id: GlpiId + ) -> PendingReasonItem | None: + """Return the pending-reason item of one ticket, or ``None``. + + Reads the legacy v1 route ``Ticket/{id}/PendingReason_Item``, the + only one that carries the catalogue id (``pendingreasons_id``). + An empty list means the ticket has no item. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + + Returns + ------- + PendingReasonItem | None + The ticket's item, or ``None`` when it has none. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + endpoint = f"{_TICKET_ITEMTYPE}/{ticket_id}/{_ITEM_RESOURCE}" + payload = await v1.request_json( + "GET", + endpoint, + failure_message=f"Failed to read the pending reason of ticket {ticket_id}", + ) + rows = payload if isinstance(payload, list) else [] + if not rows: + return None + return model_from_payload( + PendingReasonItem, rows[0], server_timezone=self.server_timezone + ) + + async def set_ticket_pending_reason( + self, + ticket_id: GlpiId, + reason_id: int, + *, + followup_frequency: int = 0, + followups_before_resolution: int = 0, + ) -> PendingReasonItem: + """Link one ticket to a pending reason, creating or changing its item. + + The ticket's item is read first (v1 ``GET``). When one exists it is + changed with ``PUT``; otherwise a new one is created with ``POST``, + so the duplicate-key error is never provoked, and never parsed. The + item is then read back and returned. + + This does **not** change the ticket status. The caller sets status + ``4`` (Pending) itself, before or after. An item set on a ticket + that is not pending is stored all the same, but has no effect on the + ticket, and GLPI removes it by itself the next time the ticket + leaves status ``4``. Setting a reason on a ticket that is already + pending changes the reason without touching the status. + + The item does not copy the catalogue's ``followup_frequency``: pass + the values wanted, or the item stores ``0``. A ``reason_id`` that is + not in the catalogue is stored without error. The call adds nothing + to the ticket timeline. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + reason_id : int + Identifier of the catalogue entry, see :meth:`list_pending_reasons`. + followup_frequency : int, optional + Delay between automatic follow-ups, in seconds (default ``0``). + followups_before_resolution : int, optional + Number of automatic follow-ups before resolution (default ``0``). + + Returns + ------- + PendingReasonItem + The ticket's item after the write. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + GlpiProtocolError + If no item can be read back after a successful write. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + existing = await self.get_ticket_pending_reason(ticket_id) + if existing is not None and existing.id is not None: + await v1.request_json( + "PUT", + f"{_ITEM_RESOURCE}/{existing.id}", + json_body={ + "input": { + "id": existing.id, + "pendingreasons_id": reason_id, + "followup_frequency": followup_frequency, + "followups_before_resolution": followups_before_resolution, + } + }, + failure_message=( + f"Failed to update the pending reason of ticket {ticket_id}" + ), + ) + else: + await v1.request_json( + "POST", + _ITEM_RESOURCE, + json_body={ + "input": { + "itemtype": _TICKET_ITEMTYPE, + "items_id": ticket_id, + "pendingreasons_id": reason_id, + "followup_frequency": followup_frequency, + "followups_before_resolution": followups_before_resolution, + } + }, + failure_message=( + f"Failed to set the pending reason of ticket {ticket_id}" + ), + ) + item = await self.get_ticket_pending_reason(ticket_id) + if item is None: + raise GlpiProtocolError( + f"GLPI stored no pending reason item for ticket {ticket_id} " + "after the write" + ) + return item + + async def clear_ticket_pending_reason(self, ticket_id: GlpiId) -> bool: + """Remove the pending-reason item of one ticket, if it has one. + + Deletes the item through v1 ``DELETE PendingReason_Item/{id}``. The + ticket status is left unchanged (a ticket cleared while at status + ``4`` stays pending, without a reason). When the ticket has no item + nothing is sent and ``False`` is returned. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + + Returns + ------- + bool + ``True`` when an item was deleted, ``False`` when there was none. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + existing = await self.get_ticket_pending_reason(ticket_id) + if existing is None or existing.id is None: + return False + await v1.request_json( + "DELETE", + f"{_ITEM_RESOURCE}/{existing.id}", + failure_message=( + f"Failed to clear the pending reason of ticket {ticket_id}" + ), + ) + return True + + +__all__ = ["PendingReasonMixin"] diff --git a/glpi_python_client/_async/clients/api/assistance/tests/test_pending_reason.py b/glpi_python_client/_async/clients/api/assistance/tests/test_pending_reason.py new file mode 100644 index 0000000..392a202 --- /dev/null +++ b/glpi_python_client/_async/clients/api/assistance/tests/test_pending_reason.py @@ -0,0 +1,199 @@ +"""Unit tests for the pending-reason client mixin.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from glpi_python_client import GlpiProtocolError, PendingReason, PendingReasonItem +from glpi_python_client._async._testing import TransportRecorder + + +class _FakeV1: + """Stand-in for the v1 session that replays queued ``request_json`` answers.""" + + def __init__(self, responses: list[object]) -> None: + self.responses = list(responses) + self.calls: list[dict[str, Any]] = [] + + async def request_json( + self, + method: str, + path: str, + *, + params: dict[str, object] | None = None, + json_body: dict[str, object] | None = None, + success_statuses: tuple[int, ...] = (200, 201, 204, 206), + failure_message: str | None = None, + ) -> object: + self.calls.append({"method": method, "path": path, "json_body": json_body}) + if not self.responses: + raise AssertionError(f"Unexpected v1 call: {method} {path}") + return self.responses.pop(0) + + async def close(self) -> None: + """No-op; the real session is closed with the client.""" + + +_ITEM = { + "id": 5, + "itemtype": "Ticket", + "items_id": 42, + "pendingreasons_id": 3, + "followup_frequency": 3600, + "followups_before_resolution": 2, + "bump_count": 0, + "last_bump_date": None, + "previous_status": 2, +} + + +async def test_list_pending_reasons_reads_the_v2_catalogue(client: Any) -> None: + """The catalogue is a paged v2 read of ``Assistance/PendingReason``.""" + + rec = TransportRecorder( + get_payload=[ + { + "id": 3, + "name": "Waiting for the requester", + "is_default": True, + "followup_frequency": 86400, + "followups_before_resolution": 3, + "entity": {"id": 0, "name": "Root"}, + } + ] + ) + rec.install(client) + reasons = await client.list_pending_reasons("name==x", limit=10, start=5) + assert isinstance(reasons[0], PendingReason) + assert reasons[0].followup_frequency == 86400 + call = rec.calls[0] + assert call["endpoint"] == "Assistance/PendingReason" + assert call["params"] == {"limit": 10, "start": 5, "filter": "name==x"} + + +async def test_iter_pending_reasons_stops_on_a_short_page(client: Any) -> None: + """The iterator yields a page shorter than ``batch_size`` and stops.""" + + rec = TransportRecorder(get_payload=[{"id": 1}]) + rec.install(client) + pages = [page async for page in client.iter_pending_reasons(batch_size=2)] + assert [[r.id for r in page] for page in pages] == [[1]] + assert rec.calls[0]["params"] == {"limit": 2, "start": 0} + + +async def test_get_ticket_pending_reason_present(client: Any) -> None: + """A ticket's item is read with v1 ``GET Ticket/{id}/PendingReason_Item``.""" + + fake = _FakeV1([[_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = await client.get_ticket_pending_reason(42) + assert isinstance(item, PendingReasonItem) + assert item.pendingreasons_id == 3 + assert item.previous_status == 2 + assert fake.calls == [ + {"method": "GET", "path": "Ticket/42/PendingReason_Item", "json_body": None} + ] + + +async def test_get_ticket_pending_reason_absent(client: Any) -> None: + """An empty list means the ticket has no item.""" + + client._v1 = _FakeV1([[]]) # type: ignore[assignment] + assert await client.get_ticket_pending_reason(42) is None + + +async def test_set_ticket_pending_reason_posts_when_no_item(client: Any) -> None: + """With no item the reason is created with POST and never PUT.""" + + fake = _FakeV1([[], {"id": 5, "message": ""}, [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = await client.set_ticket_pending_reason( + 42, 3, followup_frequency=3600, followups_before_resolution=2 + ) + assert item.id == 5 + assert [c["method"] for c in fake.calls] == ["GET", "POST", "GET"] + assert fake.calls[1]["path"] == "PendingReason_Item" + assert fake.calls[1]["json_body"] == { + "input": { + "itemtype": "Ticket", + "items_id": 42, + "pendingreasons_id": 3, + "followup_frequency": 3600, + "followups_before_resolution": 2, + } + } + + +async def test_set_ticket_pending_reason_defaults_send_zero(client: Any) -> None: + """The frequencies default to 0 and are always sent.""" + + fake = _FakeV1([[], {"id": 5}, [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + await client.set_ticket_pending_reason(42, 3) + body = fake.calls[1]["json_body"] + assert body["input"]["followup_frequency"] == 0 + assert body["input"]["followups_before_resolution"] == 0 + + +async def test_set_ticket_pending_reason_puts_when_item_exists(client: Any) -> None: + """With an item the reason is changed with PUT and never POST.""" + + fake = _FakeV1([[_ITEM], [{"5": True, "message": ""}], [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = await client.set_ticket_pending_reason(42, 4, followup_frequency=60) + assert item.id == 5 + assert [c["method"] for c in fake.calls] == ["GET", "PUT", "GET"] + assert fake.calls[1]["path"] == "PendingReason_Item/5" + assert fake.calls[1]["json_body"] == { + "input": { + "id": 5, + "pendingreasons_id": 4, + "followup_frequency": 60, + "followups_before_resolution": 0, + } + } + + +async def test_set_ticket_pending_reason_rejects_unreadable_result( + client: Any, +) -> None: + """A write that leaves no readable item raises a protocol error.""" + + client._v1 = _FakeV1([[], {"id": 5}, []]) # type: ignore[assignment] + with pytest.raises(GlpiProtocolError): + await client.set_ticket_pending_reason(42, 3) + + +async def test_clear_ticket_pending_reason_deletes_the_item(client: Any) -> None: + """Clearing deletes the ticket's item and reports it.""" + + fake = _FakeV1([[_ITEM], [{"5": True, "message": ""}]]) + client._v1 = fake # type: ignore[assignment] + assert await client.clear_ticket_pending_reason(42) is True + assert [c["method"] for c in fake.calls] == ["GET", "DELETE"] + assert fake.calls[1]["path"] == "PendingReason_Item/5" + + +async def test_clear_ticket_pending_reason_without_item_sends_no_delete( + client: Any, +) -> None: + """With no item the answer is False and nothing is deleted.""" + + fake = _FakeV1([[]]) + client._v1 = fake # type: ignore[assignment] + assert await client.clear_ticket_pending_reason(42) is False + assert [c["method"] for c in fake.calls] == ["GET"] + + +async def test_ticket_methods_need_the_v1_session(client: Any) -> None: + """The three ticket methods raise the missing-v1-session error.""" + + assert client._v1 is None + with pytest.raises(RuntimeError, match="v1 session"): + await client.get_ticket_pending_reason(42) + with pytest.raises(RuntimeError, match="v1 session"): + await client.set_ticket_pending_reason(42, 3) + with pytest.raises(RuntimeError, match="v1 session"): + await client.clear_ticket_pending_reason(42) diff --git a/glpi_python_client/_async/clients/client.py b/glpi_python_client/_async/clients/client.py index c7f45dd..ddfabc2 100644 --- a/glpi_python_client/_async/clients/client.py +++ b/glpi_python_client/_async/clients/client.py @@ -32,6 +32,7 @@ KBArticleRevisionMixin, KBCategoryMixin, LocationMixin, + PendingReasonMixin, PluginFieldsMixin, SolutionMixin, TeamMemberMixin, @@ -69,6 +70,7 @@ class AsyncGlpiClient( KBArticleMixin, KBArticleCommentMixin, KBArticleRevisionMixin, + PendingReasonMixin, PluginFieldsMixin, TicketContextMixin, StatisticsMixin, diff --git a/glpi_python_client/_async/clients/commons/_constants.py b/glpi_python_client/_async/clients/commons/_constants.py index b509f03..7687ef5 100644 --- a/glpi_python_client/_async/clients/commons/_constants.py +++ b/glpi_python_client/_async/clients/commons/_constants.py @@ -33,6 +33,7 @@ # assistance/ TICKET_ENDPOINT = "Assistance/Ticket" TEAM_MEMBER_SUFFIX = "TeamMember" +PENDING_REASON_ENDPOINT = "Assistance/PendingReason" # assistance/timeline/ FOLLOWUP_SUFFIX = "Timeline/Followup" @@ -61,6 +62,7 @@ "KB_COMMENT_SUFFIX", "KB_REVISION_SUFFIX", "LOCATION_ENDPOINT", + "PENDING_REASON_ENDPOINT", "SOLUTION_SUFFIX", "TASK_SUFFIX", "TEAM_MEMBER_SUFFIX", diff --git a/glpi_python_client/_sync/clients/api/__init__.py b/glpi_python_client/_sync/clients/api/__init__.py index 3ea45f9..314d235 100644 --- a/glpi_python_client/_sync/clients/api/__init__.py +++ b/glpi_python_client/_sync/clients/api/__init__.py @@ -16,6 +16,7 @@ ) from glpi_python_client._sync.clients.api.assets import ComputerMixin from glpi_python_client._sync.clients.api.assistance import ( + PendingReasonMixin, TeamMemberMixin, TicketMixin, ) @@ -58,6 +59,7 @@ "KBArticleRevisionMixin", "KBCategoryMixin", "LocationMixin", + "PendingReasonMixin", "PluginFieldsMixin", "SolutionMixin", "TeamMemberMixin", diff --git a/glpi_python_client/_sync/clients/api/assistance/__init__.py b/glpi_python_client/_sync/clients/api/assistance/__init__.py index 50f44db..eb7485b 100644 --- a/glpi_python_client/_sync/clients/api/assistance/__init__.py +++ b/glpi_python_client/_sync/clients/api/assistance/__init__.py @@ -2,7 +2,10 @@ from __future__ import annotations +from glpi_python_client._sync.clients.api.assistance._pending_reason import ( + PendingReasonMixin, +) from glpi_python_client._sync.clients.api.assistance._team import TeamMemberMixin from glpi_python_client._sync.clients.api.assistance._ticket import TicketMixin -__all__ = ["TeamMemberMixin", "TicketMixin"] +__all__ = ["PendingReasonMixin", "TeamMemberMixin", "TicketMixin"] diff --git a/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py b/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py new file mode 100644 index 0000000..7ad8ca5 --- /dev/null +++ b/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py @@ -0,0 +1,331 @@ +"""GLPI pending reasons: the v2 catalogue and the v1 per-ticket item. + +A pause is ticket status ``4`` (Pending) plus at most one +``PendingReason_Item`` row linking the ticket to an entry of the +``PendingReason`` catalogue. The two halves live on different APIs: + +* The catalogue is read from the v2 ``/Assistance/PendingReason`` routes + (list and per-id). Its entries are configuration objects, so there is + no create, update or delete here. Fields are ``id``, ``name``, + ``entity``, ``is_recursive``, ``is_default``, ``followup_frequency`` + (seconds), ``followups_before_resolution``, ``comment`` and the + template and calendar links. +* The ticket's item is handled through the legacy v1 API. The v2 route + ``/Assistance/Ticket/{id}/PendingReason`` returns the item (404 when + there is none) but its schema omits ``pendingreasons_id``: it tells + that a ticket is paused with a reason, not which. No v2 route writes + an item. The three ticket methods therefore need the v1 session and + raise :class:`RuntimeError` without one. + +Behaviour of the v1 item routes, as measured on a server exposing both +APIs: + +* ``GET Ticket/{id}/PendingReason_Item`` returns a list of at most one + row. +* ``POST PendingReason_Item`` creates the item (201). It changes neither + the ticket status nor its timeline, and works whatever the status. A + second POST for the same ticket answers 400 (duplicate key on + ``items_id`` and ``itemtype``). The item does not copy the catalogue's + ``followup_frequency``: an omitted frequency is stored as ``0``. +* ``PUT PendingReason_Item/{id}`` changes the reason and the + frequencies. ``PUT Ticket/{id}`` with ``pendingreasons_id`` answers + success and ignores the reason. +* ``DELETE PendingReason_Item/{id}`` removes the item and leaves the + status at ``4``. Leaving status ``4`` (to solved, closed or processing) + removes the item by itself. +* A reason id that is not in the catalogue is stored silently. +* The GLPI interface pauses through a followup (``POST ITILFollowup`` + with ``pending=1`` and ``pendingreasons_id``), which also adds a + visible followup to the timeline. The methods here add none. +""" + +from __future__ import annotations + +from collections.abc import Iterator + +from glpi_python_client._sync.clients.commons._constants import ( + PENDING_REASON_ENDPOINT, + GlpiId, +) +from glpi_python_client._sync.clients.commons._payloads import model_from_payload +from glpi_python_client._sync.clients.commons._transport import TransportMixin +from glpi_python_client._errors import GlpiProtocolError +from glpi_python_client.models.api_schema.assistance._pending_reason import ( + PendingReason, + PendingReasonItem, +) + +_V1_FEATURE_LABEL = "pending reason helpers" +_ITEM_RESOURCE = "PendingReason_Item" +_TICKET_ITEMTYPE = "Ticket" + + +class PendingReasonMixin(TransportMixin): + """Read the pending-reason catalogue and manage a ticket's pending reason.""" + + def list_pending_reasons( + self, + rsql_filter: str = "", + *, + limit: int = 50, + start: int = 0, + skip_entity: bool = False, + ) -> list[PendingReason]: + """List the entries of the pending-reason catalogue (v2). + + 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 + read spans every entity the caller has access to. + + Returns + ------- + list[PendingReason] + Catalogue entries matching the filter. + + Raises + ------ + GlpiStatusError + If the GLPI server returns a non-success HTTP status. + """ + + params: dict[str, object] = {"limit": limit, "start": start} + if rsql_filter: + params["filter"] = rsql_filter + return self._resource_list( + PENDING_REASON_ENDPOINT, + PendingReason, + params=params, + skip_entity=skip_entity, + ) + + def iter_pending_reasons( + self, + rsql_filter: str = "", + *, + batch_size: int = 50, + skip_entity: bool = False, + ) -> Iterator[list[PendingReason]]: + """Yield successive pages of the catalogue 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. + + Yields + ------ + list[PendingReason] + One page per iteration. The last batch may be shorter than + ``batch_size``. + """ + + start = 0 + while True: + batch = self.list_pending_reasons( + 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_ticket_pending_reason( + self, ticket_id: GlpiId + ) -> PendingReasonItem | None: + """Return the pending-reason item of one ticket, or ``None``. + + Reads the legacy v1 route ``Ticket/{id}/PendingReason_Item``, the + only one that carries the catalogue id (``pendingreasons_id``). + An empty list means the ticket has no item. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + + Returns + ------- + PendingReasonItem | None + The ticket's item, or ``None`` when it has none. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + endpoint = f"{_TICKET_ITEMTYPE}/{ticket_id}/{_ITEM_RESOURCE}" + payload = v1.request_json( + "GET", + endpoint, + failure_message=f"Failed to read the pending reason of ticket {ticket_id}", + ) + rows = payload if isinstance(payload, list) else [] + if not rows: + return None + return model_from_payload( + PendingReasonItem, rows[0], server_timezone=self.server_timezone + ) + + def set_ticket_pending_reason( + self, + ticket_id: GlpiId, + reason_id: int, + *, + followup_frequency: int = 0, + followups_before_resolution: int = 0, + ) -> PendingReasonItem: + """Link one ticket to a pending reason, creating or changing its item. + + The ticket's item is read first (v1 ``GET``). When one exists it is + changed with ``PUT``; otherwise a new one is created with ``POST``, + so the duplicate-key error is never provoked, and never parsed. The + item is then read back and returned. + + This does **not** change the ticket status. The caller sets status + ``4`` (Pending) itself, before or after. An item set on a ticket + that is not pending is stored all the same, but has no effect on the + ticket, and GLPI removes it by itself the next time the ticket + leaves status ``4``. Setting a reason on a ticket that is already + pending changes the reason without touching the status. + + The item does not copy the catalogue's ``followup_frequency``: pass + the values wanted, or the item stores ``0``. A ``reason_id`` that is + not in the catalogue is stored without error. The call adds nothing + to the ticket timeline. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + reason_id : int + Identifier of the catalogue entry, see :meth:`list_pending_reasons`. + followup_frequency : int, optional + Delay between automatic follow-ups, in seconds (default ``0``). + followups_before_resolution : int, optional + Number of automatic follow-ups before resolution (default ``0``). + + Returns + ------- + PendingReasonItem + The ticket's item after the write. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + GlpiProtocolError + If no item can be read back after a successful write. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + existing = self.get_ticket_pending_reason(ticket_id) + if existing is not None and existing.id is not None: + v1.request_json( + "PUT", + f"{_ITEM_RESOURCE}/{existing.id}", + json_body={ + "input": { + "id": existing.id, + "pendingreasons_id": reason_id, + "followup_frequency": followup_frequency, + "followups_before_resolution": followups_before_resolution, + } + }, + failure_message=( + f"Failed to update the pending reason of ticket {ticket_id}" + ), + ) + else: + v1.request_json( + "POST", + _ITEM_RESOURCE, + json_body={ + "input": { + "itemtype": _TICKET_ITEMTYPE, + "items_id": ticket_id, + "pendingreasons_id": reason_id, + "followup_frequency": followup_frequency, + "followups_before_resolution": followups_before_resolution, + } + }, + failure_message=( + f"Failed to set the pending reason of ticket {ticket_id}" + ), + ) + item = self.get_ticket_pending_reason(ticket_id) + if item is None: + raise GlpiProtocolError( + f"GLPI stored no pending reason item for ticket {ticket_id} " + "after the write" + ) + return item + + def clear_ticket_pending_reason(self, ticket_id: GlpiId) -> bool: + """Remove the pending-reason item of one ticket, if it has one. + + Deletes the item through v1 ``DELETE PendingReason_Item/{id}``. The + ticket status is left unchanged (a ticket cleared while at status + ``4`` stays pending, without a reason). When the ticket has no item + nothing is sent and ``False`` is returned. + + Parameters + ---------- + ticket_id : GlpiId + Numeric identifier of the ticket. + + Returns + ------- + bool + ``True`` when an item was deleted, ``False`` when there was none. + + Raises + ------ + RuntimeError + If the client has no v1 session (``v1_base_url`` and + ``v1_user_token``). + GlpiStatusError + If the v1 server returns a non-success HTTP status. + """ + + v1 = self._require_v1_session(_V1_FEATURE_LABEL) + existing = self.get_ticket_pending_reason(ticket_id) + if existing is None or existing.id is None: + return False + v1.request_json( + "DELETE", + f"{_ITEM_RESOURCE}/{existing.id}", + failure_message=( + f"Failed to clear the pending reason of ticket {ticket_id}" + ), + ) + return True + + +__all__ = ["PendingReasonMixin"] diff --git a/glpi_python_client/_sync/clients/api/assistance/tests/test_pending_reason.py b/glpi_python_client/_sync/clients/api/assistance/tests/test_pending_reason.py new file mode 100644 index 0000000..3f55943 --- /dev/null +++ b/glpi_python_client/_sync/clients/api/assistance/tests/test_pending_reason.py @@ -0,0 +1,199 @@ +"""Unit tests for the pending-reason client mixin.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from glpi_python_client import GlpiProtocolError, PendingReason, PendingReasonItem +from glpi_python_client._sync._testing import TransportRecorder + + +class _FakeV1: + """Stand-in for the v1 session that replays queued ``request_json`` answers.""" + + def __init__(self, responses: list[object]) -> None: + self.responses = list(responses) + self.calls: list[dict[str, Any]] = [] + + def request_json( + self, + method: str, + path: str, + *, + params: dict[str, object] | None = None, + json_body: dict[str, object] | None = None, + success_statuses: tuple[int, ...] = (200, 201, 204, 206), + failure_message: str | None = None, + ) -> object: + self.calls.append({"method": method, "path": path, "json_body": json_body}) + if not self.responses: + raise AssertionError(f"Unexpected v1 call: {method} {path}") + return self.responses.pop(0) + + def close(self) -> None: + """No-op; the real session is closed with the client.""" + + +_ITEM = { + "id": 5, + "itemtype": "Ticket", + "items_id": 42, + "pendingreasons_id": 3, + "followup_frequency": 3600, + "followups_before_resolution": 2, + "bump_count": 0, + "last_bump_date": None, + "previous_status": 2, +} + + +def test_list_pending_reasons_reads_the_v2_catalogue(client: Any) -> None: + """The catalogue is a paged v2 read of ``Assistance/PendingReason``.""" + + rec = TransportRecorder( + get_payload=[ + { + "id": 3, + "name": "Waiting for the requester", + "is_default": True, + "followup_frequency": 86400, + "followups_before_resolution": 3, + "entity": {"id": 0, "name": "Root"}, + } + ] + ) + rec.install(client) + reasons = client.list_pending_reasons("name==x", limit=10, start=5) + assert isinstance(reasons[0], PendingReason) + assert reasons[0].followup_frequency == 86400 + call = rec.calls[0] + assert call["endpoint"] == "Assistance/PendingReason" + assert call["params"] == {"limit": 10, "start": 5, "filter": "name==x"} + + +def test_iter_pending_reasons_stops_on_a_short_page(client: Any) -> None: + """The iterator yields a page shorter than ``batch_size`` and stops.""" + + rec = TransportRecorder(get_payload=[{"id": 1}]) + rec.install(client) + pages = [page for page in client.iter_pending_reasons(batch_size=2)] + assert [[r.id for r in page] for page in pages] == [[1]] + assert rec.calls[0]["params"] == {"limit": 2, "start": 0} + + +def test_get_ticket_pending_reason_present(client: Any) -> None: + """A ticket's item is read with v1 ``GET Ticket/{id}/PendingReason_Item``.""" + + fake = _FakeV1([[_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = client.get_ticket_pending_reason(42) + assert isinstance(item, PendingReasonItem) + assert item.pendingreasons_id == 3 + assert item.previous_status == 2 + assert fake.calls == [ + {"method": "GET", "path": "Ticket/42/PendingReason_Item", "json_body": None} + ] + + +def test_get_ticket_pending_reason_absent(client: Any) -> None: + """An empty list means the ticket has no item.""" + + client._v1 = _FakeV1([[]]) # type: ignore[assignment] + assert client.get_ticket_pending_reason(42) is None + + +def test_set_ticket_pending_reason_posts_when_no_item(client: Any) -> None: + """With no item the reason is created with POST and never PUT.""" + + fake = _FakeV1([[], {"id": 5, "message": ""}, [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = client.set_ticket_pending_reason( + 42, 3, followup_frequency=3600, followups_before_resolution=2 + ) + assert item.id == 5 + assert [c["method"] for c in fake.calls] == ["GET", "POST", "GET"] + assert fake.calls[1]["path"] == "PendingReason_Item" + assert fake.calls[1]["json_body"] == { + "input": { + "itemtype": "Ticket", + "items_id": 42, + "pendingreasons_id": 3, + "followup_frequency": 3600, + "followups_before_resolution": 2, + } + } + + +def test_set_ticket_pending_reason_defaults_send_zero(client: Any) -> None: + """The frequencies default to 0 and are always sent.""" + + fake = _FakeV1([[], {"id": 5}, [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + client.set_ticket_pending_reason(42, 3) + body = fake.calls[1]["json_body"] + assert body["input"]["followup_frequency"] == 0 + assert body["input"]["followups_before_resolution"] == 0 + + +def test_set_ticket_pending_reason_puts_when_item_exists(client: Any) -> None: + """With an item the reason is changed with PUT and never POST.""" + + fake = _FakeV1([[_ITEM], [{"5": True, "message": ""}], [_ITEM]]) + client._v1 = fake # type: ignore[assignment] + item = client.set_ticket_pending_reason(42, 4, followup_frequency=60) + assert item.id == 5 + assert [c["method"] for c in fake.calls] == ["GET", "PUT", "GET"] + assert fake.calls[1]["path"] == "PendingReason_Item/5" + assert fake.calls[1]["json_body"] == { + "input": { + "id": 5, + "pendingreasons_id": 4, + "followup_frequency": 60, + "followups_before_resolution": 0, + } + } + + +def test_set_ticket_pending_reason_rejects_unreadable_result( + client: Any, +) -> None: + """A write that leaves no readable item raises a protocol error.""" + + client._v1 = _FakeV1([[], {"id": 5}, []]) # type: ignore[assignment] + with pytest.raises(GlpiProtocolError): + client.set_ticket_pending_reason(42, 3) + + +def test_clear_ticket_pending_reason_deletes_the_item(client: Any) -> None: + """Clearing deletes the ticket's item and reports it.""" + + fake = _FakeV1([[_ITEM], [{"5": True, "message": ""}]]) + client._v1 = fake # type: ignore[assignment] + assert client.clear_ticket_pending_reason(42) is True + assert [c["method"] for c in fake.calls] == ["GET", "DELETE"] + assert fake.calls[1]["path"] == "PendingReason_Item/5" + + +def test_clear_ticket_pending_reason_without_item_sends_no_delete( + client: Any, +) -> None: + """With no item the answer is False and nothing is deleted.""" + + fake = _FakeV1([[]]) + client._v1 = fake # type: ignore[assignment] + assert client.clear_ticket_pending_reason(42) is False + assert [c["method"] for c in fake.calls] == ["GET"] + + +def test_ticket_methods_need_the_v1_session(client: Any) -> None: + """The three ticket methods raise the missing-v1-session error.""" + + assert client._v1 is None + with pytest.raises(RuntimeError, match="v1 session"): + client.get_ticket_pending_reason(42) + with pytest.raises(RuntimeError, match="v1 session"): + client.set_ticket_pending_reason(42, 3) + with pytest.raises(RuntimeError, match="v1 session"): + client.clear_ticket_pending_reason(42) diff --git a/glpi_python_client/_sync/clients/client.py b/glpi_python_client/_sync/clients/client.py index ed0b7c5..375fbf6 100644 --- a/glpi_python_client/_sync/clients/client.py +++ b/glpi_python_client/_sync/clients/client.py @@ -32,6 +32,7 @@ KBArticleRevisionMixin, KBCategoryMixin, LocationMixin, + PendingReasonMixin, PluginFieldsMixin, SolutionMixin, TeamMemberMixin, @@ -69,6 +70,7 @@ class GlpiClient( KBArticleMixin, KBArticleCommentMixin, KBArticleRevisionMixin, + PendingReasonMixin, PluginFieldsMixin, TicketContextMixin, StatisticsMixin, diff --git a/glpi_python_client/_sync/clients/commons/_constants.py b/glpi_python_client/_sync/clients/commons/_constants.py index b509f03..7687ef5 100644 --- a/glpi_python_client/_sync/clients/commons/_constants.py +++ b/glpi_python_client/_sync/clients/commons/_constants.py @@ -33,6 +33,7 @@ # assistance/ TICKET_ENDPOINT = "Assistance/Ticket" TEAM_MEMBER_SUFFIX = "TeamMember" +PENDING_REASON_ENDPOINT = "Assistance/PendingReason" # assistance/timeline/ FOLLOWUP_SUFFIX = "Timeline/Followup" @@ -61,6 +62,7 @@ "KB_COMMENT_SUFFIX", "KB_REVISION_SUFFIX", "LOCATION_ENDPOINT", + "PENDING_REASON_ENDPOINT", "SOLUTION_SUFFIX", "TASK_SUFFIX", "TEAM_MEMBER_SUFFIX", diff --git a/glpi_python_client/models/__init__.py b/glpi_python_client/models/__init__.py index 03a8d68..de0740e 100644 --- a/glpi_python_client/models/__init__.py +++ b/glpi_python_client/models/__init__.py @@ -52,6 +52,8 @@ GetTicket, PatchTeamMember, PatchTicket, + PendingReason, + PendingReasonItem, PostTeamMember, PostTicket, ) @@ -222,6 +224,8 @@ "PatchTicketTask", "PatchTimelineDocument", "PatchUser", + "PendingReason", + "PendingReasonItem", "PostComputer", "PostContract", "PostContractCost", diff --git a/glpi_python_client/models/api_schema/assistance/__init__.py b/glpi_python_client/models/api_schema/assistance/__init__.py index 7c4b925..ff1637b 100644 --- a/glpi_python_client/models/api_schema/assistance/__init__.py +++ b/glpi_python_client/models/api_schema/assistance/__init__.py @@ -5,6 +5,10 @@ :mod:`.timeline`. """ +from glpi_python_client.models.api_schema.assistance._pending_reason import ( + PendingReason, + PendingReasonItem, +) from glpi_python_client.models.api_schema.assistance._team import ( DeleteTeamMember, GetTeamMember, @@ -25,6 +29,8 @@ "GetTicket", "PatchTeamMember", "PatchTicket", + "PendingReason", + "PendingReasonItem", "PostTeamMember", "PostTicket", ] diff --git a/glpi_python_client/models/api_schema/assistance/_pending_reason.py b/glpi_python_client/models/api_schema/assistance/_pending_reason.py new file mode 100644 index 0000000..0de5b6d --- /dev/null +++ b/glpi_python_client/models/api_schema/assistance/_pending_reason.py @@ -0,0 +1,102 @@ +"""GLPI pending-reason schemas. + +A ticket is paused when its status is ``4`` (Pending) and, optionally, one +``PendingReason_Item`` row links it to an entry of the ``PendingReason`` +catalogue. Two read models cover the two halves: + +* :class:`PendingReason` -- one catalogue entry, read from the v2 + ``/Assistance/PendingReason`` routes. +* :class:`PendingReasonItem` -- the row linking one ticket to a catalogue + entry, read from the legacy v1 API (the v2 item schema omits the + catalogue id). + +Both are read models only: catalogue entries are configuration objects the +client does not write, and an item is written with a handful of arguments +rather than a request model. +""" + +from __future__ import annotations + +from glpi_python_client.models._base import GlpiModel +from glpi_python_client.models.api_schema._common import IdNameRef + + +class PendingReason(GlpiModel): + """One entry of the ``PendingReason`` catalogue (v2). + + The template and calendar links the server returns are not declared; + they land in :attr:`~glpi_python_client.models._base.GlpiModel.extra_payload`. + + Parameters + ---------- + id : int | None, optional + Native GLPI identifier of the reason. + name : str | None, optional + Display name of the reason. + entity : IdNameRef | None, optional + Reference to the owning GLPI entity. + is_recursive : bool | None, optional + Whether the reason is visible to child entities. + is_default : bool | None, optional + Whether the reason is the default one. + followup_frequency : int | None, optional + Delay between automatic follow-ups, in seconds. The catalogue + value is not copied onto a ticket's item. + followups_before_resolution : int | None, optional + Number of automatic follow-ups before the ticket is resolved. + comment : str | None, optional + Free-form comment of the reason. + """ + + id: int | None = None + name: str | None = None + entity: IdNameRef | None = None + is_recursive: bool | None = None + is_default: bool | None = None + followup_frequency: int | None = None + followups_before_resolution: int | None = None + comment: str | None = None + + +class PendingReasonItem(GlpiModel): + """The ``PendingReason_Item`` row of one paused ticket (v1). + + At most one row exists per ticket. GLPI removes it by itself when the + ticket leaves status ``4``. + + Parameters + ---------- + id : int | None, optional + Native identifier of the item row. + itemtype : str | None, optional + Itemtype the row is attached to (``"Ticket"``). + items_id : int | None, optional + Identifier of the item the row is attached to. + pendingreasons_id : int | None, optional + Identifier of the catalogue entry. GLPI stores an id that is not + in the catalogue without complaint. + followup_frequency : int | None, optional + Delay between automatic follow-ups, in seconds. ``0`` when the + item was created without a frequency. + followups_before_resolution : int | None, optional + Number of automatic follow-ups before the ticket is resolved. + bump_count : int | None, optional + Number of automatic follow-ups already sent. + last_bump_date : str | None, optional + Date of the last automatic follow-up, as GLPI returns it. + previous_status : int | None, optional + Ticket status before the pause. + """ + + id: int | None = None + itemtype: str | None = None + items_id: int | None = None + pendingreasons_id: int | None = None + followup_frequency: int | None = None + followups_before_resolution: int | None = None + bump_count: int | None = None + last_bump_date: str | None = None + previous_status: int | None = None + + +__all__ = ["PendingReason", "PendingReasonItem"] diff --git a/glpi_python_client/testing/tests/test_exports.py b/glpi_python_client/testing/tests/test_exports.py index 47abd94..4e85d26 100644 --- a/glpi_python_client/testing/tests/test_exports.py +++ b/glpi_python_client/testing/tests/test_exports.py @@ -128,3 +128,15 @@ def test_itil_category_models_exported_from_models_package() -> None: for name in _ITIL_CATEGORY_MODELS: assert hasattr(models, name), name assert name in models.__all__, name + + +_PENDING_REASON_MODELS = ("PendingReason", "PendingReasonItem") + + +def test_pending_reason_models_exported_from_both_packages() -> None: + """The pending-reason models are importable from both public packages.""" + + for module in (glpi_python_client, models): + for name in _PENDING_REASON_MODELS: + assert hasattr(module, name), name + assert name in module.__all__, name diff --git a/skills/glpi-ticket-workflow/SKILL.md b/skills/glpi-ticket-workflow/SKILL.md index b6c11b0..84672d5 100644 --- a/skills/glpi-ticket-workflow/SKILL.md +++ b/skills/glpi-ticket-workflow/SKILL.md @@ -81,4 +81,4 @@ ticket = PostTicket( - **`status` is writable, on `PatchTicket` only.** `client.update_ticket(tid, PatchTicket(status=GlpiTicketStatus.PENDING))` moves the ticket. This corrects an earlier claim in this skill that the field was read-only: GLPI's own contract publishes `Ticket.status.id` as `readOnly: true`, and that is simply wrong — a live GLPI 11 instance honours the `PATCH`. The same contract omits the `Major` level from `priority`, so treat it as a hint, not an authority. Two things it does *not* cover: `POST` **ignores** `status` (201, then the ticket reads back as `New`), which is why the field is declared on `PatchTicket` and not on `PostTicket`; and `status_id` is silently dropped, so use `status`. Posting a solution still moves the ticket to `SOLVED` on its own and remains the better call when there is a resolution to record — a bare status change leaves no trace of why. - **Key on `status.id`, never on `status.name`.** The id set is hardcoded in GLPI's core — there is no `TicketStatus` itemtype (the v1 API answers 400 for it, while `ITILCategory` and `RequestType` return instance rows), and `listSearchOptions` reports `status` as `{"table": "glpi_tickets", "datatype": "specific"}`, i.e. a column of the tickets table rather than a foreign key into a configurable one. An administrator cannot add or rename a status. The **labels** are another matter: they are translations, so the same id reads back as `"Nouveau"` on a French instance and `"New"` on an English one. The ids `7`, `8`, `9`, `11`–`14` exist but belong to the sibling ITIL types, and they are literal integers in GLPI's source: `CommonITILObject` declares `INCOMING = 1` through `OBSERVED = 8` plus `APPROVAL = 10`, and `Change` adds `EVALUATION = 9`, `TEST = 11`, `QUALIFICATION = 12`, `REFUSED = 13`, `CANCELED = 14`. Each type's `getAllStatusArray()` is a hardcoded PHP array mapping those constants to *translated* labels — no database, no config table. The set is therefore coupled to the GLPI *version*, not to the instance. - **Never widen `status` to a plain `int`.** GLPI validates *nothing* on this field: `{"status": 99}` answers 200 and stores it. The ticket then reads back as `{"id": 99, "name": "99"}`, the web form shows it as *New*, and it vanishes from the ticket list while staying open in the database — only the ticket history records the change. A typo like `55` for `5` therefore loses a ticket in total silence, and the `GlpiTicketStatus` annotation is the only thing on the whole path that can stop it. `GetTicket.status` stays the permissive `IdNameRef` for the mirror-image reason: a strict enum on the read side would blow up an entire search over one poisoned row, the way a missing `Major` once did for `priority`. -- Read-only fields are intentionally absent from `PostTicket`/`PatchTicket`; the server controls those transitions. `global_validation` is *not* one of them -- it is declared on both write models, typed `GlpiGlobalValidation | None`, whose members are `NONE = 1`, `WAITING = 2`, `ACCEPTED = 3`, `REFUSED = 4`. `GlpiGlobalValidation` is exported from the package root alongside `GlpiTicketStatus` (`NEW = 1`, `ASSIGNED = 2`, `PLANNED = 3`, `PENDING = 4`, `SOLVED = 5`, `CLOSED = 6`, `VALIDATION = 10`), `GlpiTicketType` (`INCIDENT = 1`, `REQUEST = 2`) and `GlpiPriority`; all of them stay readable on `GetTicket`. \ No newline at end of file +- Read-only fields are intentionally absent from `PostTicket`/`PatchTicket`; the server controls those transitions. `global_validation` is *not* one of them -- it is declared on both write models, typed `GlpiGlobalValidation | None`, whose members are `NONE = 1`, `WAITING = 2`, `ACCEPTED = 3`, `REFUSED = 4`. `GlpiGlobalValidation` is exported from the package root alongside `GlpiTicketStatus` (`NEW = 1`, `ASSIGNED = 2`, `PLANNED = 3`, `PENDING = 4`, `SOLVED = 5`, `CLOSED = 6`, `VALIDATION = 10`), `GlpiTicketType` (`INCIDENT = 1`, `REQUEST = 2`) and `GlpiPriority`; all of them stay readable on `GetTicket`.- **A pause is status 4 plus a pending-reason item, and the status is yours to set.** `list_pending_reasons` (and the page iterator `iter_pending_reasons`) read the v2 catalogue. A ticket's item goes through the legacy v1 session, because the v2 item schema does not say which reason a ticket carries and no v2 route writes one: `get_ticket_pending_reason(tid)` returns a `PendingReasonItem` or `None`, `set_ticket_pending_reason(tid, reason_id, followup_frequency=0, followups_before_resolution=0)` creates or changes the item and returns it, `clear_ticket_pending_reason(tid)` returns `True` or `False` when there was none. All three raise `RuntimeError` without `v1_base_url` and `v1_user_token`. Setting a reason does not change the status (send `PatchTicket(status=GlpiTicketStatus.PENDING)` yourself); an item on a ticket that is not pending is stored but inert, and GLPI deletes it when the ticket leaves status 4. The item does not copy the catalogue's `followup_frequency`, so omitting it stores 0, and an id outside the catalogue is stored without error. None of these calls adds a followup to the timeline, unlike the GLPI web interface. From 4b47b128c6c5a206235b38af4d4fcfd150b3e857 Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 00:47:25 +0100 Subject: [PATCH 2/3] Fix the pending-reason bullet in the ticket-workflow skill: it starts on its own line instead of continuing the previous bullet. Co-Authored-By: Claude Opus 5.5 --- skills/glpi-ticket-workflow/SKILL.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/skills/glpi-ticket-workflow/SKILL.md b/skills/glpi-ticket-workflow/SKILL.md index 84672d5..dde21cd 100644 --- a/skills/glpi-ticket-workflow/SKILL.md +++ b/skills/glpi-ticket-workflow/SKILL.md @@ -81,4 +81,5 @@ ticket = PostTicket( - **`status` is writable, on `PatchTicket` only.** `client.update_ticket(tid, PatchTicket(status=GlpiTicketStatus.PENDING))` moves the ticket. This corrects an earlier claim in this skill that the field was read-only: GLPI's own contract publishes `Ticket.status.id` as `readOnly: true`, and that is simply wrong — a live GLPI 11 instance honours the `PATCH`. The same contract omits the `Major` level from `priority`, so treat it as a hint, not an authority. Two things it does *not* cover: `POST` **ignores** `status` (201, then the ticket reads back as `New`), which is why the field is declared on `PatchTicket` and not on `PostTicket`; and `status_id` is silently dropped, so use `status`. Posting a solution still moves the ticket to `SOLVED` on its own and remains the better call when there is a resolution to record — a bare status change leaves no trace of why. - **Key on `status.id`, never on `status.name`.** The id set is hardcoded in GLPI's core — there is no `TicketStatus` itemtype (the v1 API answers 400 for it, while `ITILCategory` and `RequestType` return instance rows), and `listSearchOptions` reports `status` as `{"table": "glpi_tickets", "datatype": "specific"}`, i.e. a column of the tickets table rather than a foreign key into a configurable one. An administrator cannot add or rename a status. The **labels** are another matter: they are translations, so the same id reads back as `"Nouveau"` on a French instance and `"New"` on an English one. The ids `7`, `8`, `9`, `11`–`14` exist but belong to the sibling ITIL types, and they are literal integers in GLPI's source: `CommonITILObject` declares `INCOMING = 1` through `OBSERVED = 8` plus `APPROVAL = 10`, and `Change` adds `EVALUATION = 9`, `TEST = 11`, `QUALIFICATION = 12`, `REFUSED = 13`, `CANCELED = 14`. Each type's `getAllStatusArray()` is a hardcoded PHP array mapping those constants to *translated* labels — no database, no config table. The set is therefore coupled to the GLPI *version*, not to the instance. - **Never widen `status` to a plain `int`.** GLPI validates *nothing* on this field: `{"status": 99}` answers 200 and stores it. The ticket then reads back as `{"id": 99, "name": "99"}`, the web form shows it as *New*, and it vanishes from the ticket list while staying open in the database — only the ticket history records the change. A typo like `55` for `5` therefore loses a ticket in total silence, and the `GlpiTicketStatus` annotation is the only thing on the whole path that can stop it. `GetTicket.status` stays the permissive `IdNameRef` for the mirror-image reason: a strict enum on the read side would blow up an entire search over one poisoned row, the way a missing `Major` once did for `priority`. -- Read-only fields are intentionally absent from `PostTicket`/`PatchTicket`; the server controls those transitions. `global_validation` is *not* one of them -- it is declared on both write models, typed `GlpiGlobalValidation | None`, whose members are `NONE = 1`, `WAITING = 2`, `ACCEPTED = 3`, `REFUSED = 4`. `GlpiGlobalValidation` is exported from the package root alongside `GlpiTicketStatus` (`NEW = 1`, `ASSIGNED = 2`, `PLANNED = 3`, `PENDING = 4`, `SOLVED = 5`, `CLOSED = 6`, `VALIDATION = 10`), `GlpiTicketType` (`INCIDENT = 1`, `REQUEST = 2`) and `GlpiPriority`; all of them stay readable on `GetTicket`.- **A pause is status 4 plus a pending-reason item, and the status is yours to set.** `list_pending_reasons` (and the page iterator `iter_pending_reasons`) read the v2 catalogue. A ticket's item goes through the legacy v1 session, because the v2 item schema does not say which reason a ticket carries and no v2 route writes one: `get_ticket_pending_reason(tid)` returns a `PendingReasonItem` or `None`, `set_ticket_pending_reason(tid, reason_id, followup_frequency=0, followups_before_resolution=0)` creates or changes the item and returns it, `clear_ticket_pending_reason(tid)` returns `True` or `False` when there was none. All three raise `RuntimeError` without `v1_base_url` and `v1_user_token`. Setting a reason does not change the status (send `PatchTicket(status=GlpiTicketStatus.PENDING)` yourself); an item on a ticket that is not pending is stored but inert, and GLPI deletes it when the ticket leaves status 4. The item does not copy the catalogue's `followup_frequency`, so omitting it stores 0, and an id outside the catalogue is stored without error. None of these calls adds a followup to the timeline, unlike the GLPI web interface. +- Read-only fields are intentionally absent from `PostTicket`/`PatchTicket`; the server controls those transitions. `global_validation` is *not* one of them -- it is declared on both write models, typed `GlpiGlobalValidation | None`, whose members are `NONE = 1`, `WAITING = 2`, `ACCEPTED = 3`, `REFUSED = 4`. `GlpiGlobalValidation` is exported from the package root alongside `GlpiTicketStatus` (`NEW = 1`, `ASSIGNED = 2`, `PLANNED = 3`, `PENDING = 4`, `SOLVED = 5`, `CLOSED = 6`, `VALIDATION = 10`), `GlpiTicketType` (`INCIDENT = 1`, `REQUEST = 2`) and `GlpiPriority`; all of them stay readable on `GetTicket`. +- **A pause is status 4 plus a pending-reason item, and the status is yours to set.** `list_pending_reasons` (and the page iterator `iter_pending_reasons`) read the v2 catalogue. A ticket's item goes through the legacy v1 session, because the v2 item schema does not say which reason a ticket carries and no v2 route writes one: `get_ticket_pending_reason(tid)` returns a `PendingReasonItem` or `None`, `set_ticket_pending_reason(tid, reason_id, followup_frequency=0, followups_before_resolution=0)` creates or changes the item and returns it, `clear_ticket_pending_reason(tid)` returns `True` or `False` when there was none. All three raise `RuntimeError` without `v1_base_url` and `v1_user_token`. Setting a reason does not change the status (send `PatchTicket(status=GlpiTicketStatus.PENDING)` yourself); an item on a ticket that is not pending is stored but inert, and GLPI deletes it when the ticket leaves status 4. The item does not copy the catalogue's `followup_frequency`, so omitting it stores 0, and an id outside the catalogue is stored without error. None of these calls adds a followup to the timeline, unlike the GLPI web interface. From a4d7f2652d5086c7546151ba30267f79228a45da Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 01:23:16 +0100 Subject: [PATCH 3/3] State the limits of the pending-reason docs: the set race, the inert item on a never-pending ticket, and the v1 session requirement in the setup guidance. Co-Authored-By: Claude Opus 5.5 --- docs/user_guide.rst | 16 ++++++++++------ .../clients/api/assistance/_pending_reason.py | 13 +++++++++---- .../clients/api/assistance/_pending_reason.py | 13 +++++++++---- .../api_schema/assistance/_pending_reason.py | 2 +- skills/glpi-client-setup/SKILL.md | 9 ++++++--- skills/glpi-ticket-workflow/SKILL.md | 2 +- 6 files changed, 36 insertions(+), 19 deletions(-) diff --git a/docs/user_guide.rst b/docs/user_guide.rst index f2bfb8b..0baf980 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -14,8 +14,8 @@ Neither is a wrapper around the other; both are the same code, as Both clients speak the GLPI **v2** high-level API and fall back to the legacy v1 API for features that are not exposed by v2, currently -binary document uploads and the ``Fields`` plugin custom-field -helpers. They expose the exact same endpoint methods and accept the +binary document uploads, the ``Fields`` plugin custom-field +helpers and the ticket pending-reason item methods. They expose the exact same endpoint methods and accept the same constructor arguments. Public methods always return Pydantic models (or simple Python types) and never raw dictionaries. @@ -122,7 +122,9 @@ Optional constructor arguments * ``v1_base_url`` and ``v1_user_token`` — together enable the legacy v1 fallback used by :meth:`GlpiClient.upload_document` and the ``Fields`` plugin helpers such as - :meth:`GlpiClient.get_ticket_custom_fields`. + :meth:`GlpiClient.get_ticket_custom_fields`, and the ticket + pending-reason methods such as + :meth:`GlpiClient.set_ticket_pending_reason`. ``from_env`` ~~~~~~~~~~~~ @@ -1124,10 +1126,12 @@ Without the v1 session the three ticket methods raise ``RuntimeError``. Things worth knowing: * ``set_ticket_pending_reason`` creates the item when the ticket has none - and changes it otherwise; it never provokes GLPI's duplicate-key error. + and changes it otherwise, so it avoids GLPI's duplicate-key error + unless another writer creates the item between its read and its write. It does **not** change the ticket status. An item set on a ticket that - is not pending is stored but has no effect, and GLPI removes it when - the ticket next leaves status ``4``. + is not pending is stored but has no effect; GLPI removes an item when + its ticket leaves status ``4``, but one set on a ticket that never was + pending is not known to be cleaned up, so clear it explicitly. * The item does not copy the catalogue's ``followup_frequency``: pass the frequencies wanted, or the item stores ``0``. * ``clear_ticket_pending_reason`` leaves the ticket at status ``4``, diff --git a/glpi_python_client/_async/clients/api/assistance/_pending_reason.py b/glpi_python_client/_async/clients/api/assistance/_pending_reason.py index 1552f95..7d7a3bd 100644 --- a/glpi_python_client/_async/clients/api/assistance/_pending_reason.py +++ b/glpi_python_client/_async/clients/api/assistance/_pending_reason.py @@ -202,14 +202,19 @@ async def set_ticket_pending_reason( The ticket's item is read first (v1 ``GET``). When one exists it is changed with ``PUT``; otherwise a new one is created with ``POST``, - so the duplicate-key error is never provoked, and never parsed. The - item is then read back and returned. + so the duplicate-key error is avoided, and never parsed. The read and + the write are two requests, not one atomic step: a concurrent writer + that creates the item in between can still make the ``POST`` fail + with a ``400`` duplicate-key ``GlpiStatusError``. The item is then + read back and returned. This does **not** change the ticket status. The caller sets status ``4`` (Pending) itself, before or after. An item set on a ticket that is not pending is stored all the same, but has no effect on the - ticket, and GLPI removes it by itself the next time the ticket - leaves status ``4``. Setting a reason on a ticket that is already + ticket. GLPI removes an item when its ticket leaves status ``4``; + an item set on a ticket that never was pending is not known to be + cleaned up, so clear it with ``clear_ticket_pending_reason``. + Setting a reason on a ticket that is already pending changes the reason without touching the status. The item does not copy the catalogue's ``followup_frequency``: pass diff --git a/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py b/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py index 7ad8ca5..373fe8d 100644 --- a/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py +++ b/glpi_python_client/_sync/clients/api/assistance/_pending_reason.py @@ -202,14 +202,19 @@ def set_ticket_pending_reason( The ticket's item is read first (v1 ``GET``). When one exists it is changed with ``PUT``; otherwise a new one is created with ``POST``, - so the duplicate-key error is never provoked, and never parsed. The - item is then read back and returned. + so the duplicate-key error is avoided, and never parsed. The read and + the write are two requests, not one atomic step: a concurrent writer + that creates the item in between can still make the ``POST`` fail + with a ``400`` duplicate-key ``GlpiStatusError``. The item is then + read back and returned. This does **not** change the ticket status. The caller sets status ``4`` (Pending) itself, before or after. An item set on a ticket that is not pending is stored all the same, but has no effect on the - ticket, and GLPI removes it by itself the next time the ticket - leaves status ``4``. Setting a reason on a ticket that is already + ticket. GLPI removes an item when its ticket leaves status ``4``; + an item set on a ticket that never was pending is not known to be + cleaned up, so clear it with ``clear_ticket_pending_reason``. + Setting a reason on a ticket that is already pending changes the reason without touching the status. The item does not copy the catalogue's ``followup_frequency``: pass diff --git a/glpi_python_client/models/api_schema/assistance/_pending_reason.py b/glpi_python_client/models/api_schema/assistance/_pending_reason.py index 0de5b6d..1f98b3f 100644 --- a/glpi_python_client/models/api_schema/assistance/_pending_reason.py +++ b/glpi_python_client/models/api_schema/assistance/_pending_reason.py @@ -62,7 +62,7 @@ class PendingReasonItem(GlpiModel): """The ``PendingReason_Item`` row of one paused ticket (v1). At most one row exists per ticket. GLPI removes it by itself when the - ticket leaves status ``4``. + ticket leaves status ``4`` after having been pending. Parameters ---------- diff --git a/skills/glpi-client-setup/SKILL.md b/skills/glpi-client-setup/SKILL.md index dea767e..cd1cac8 100644 --- a/skills/glpi-client-setup/SKILL.md +++ b/skills/glpi-client-setup/SKILL.md @@ -1,6 +1,6 @@ --- name: glpi-client-setup -description: "Create and configure the synchronous glpi_python_client.GlpiClient or the asynchronous glpi_python_client.AsyncGlpiClient, including from_env, OAuth credential pairs, entity/profile headers, SSL settings, and the optional legacy v1 session (v1_base_url / v1_user_token) that backs document uploads, the Fields plugin helpers, KB category writes and actor-based statistics. Use before calling GLPI APIs, when configuring the v1 session for any of those features, or when the user asks how to connect to GLPI with glpi_python_client." +description: "Create and configure the synchronous glpi_python_client.GlpiClient or the asynchronous glpi_python_client.AsyncGlpiClient, including from_env, OAuth credential pairs, entity/profile headers, SSL settings, and the optional legacy v1 session (v1_base_url / v1_user_token) that backs document uploads, the Fields plugin helpers, KB category writes, ticket pending-reason items and actor-based statistics. Use before calling GLPI APIs, when configuring the v1 session for any of those features, or when the user asks how to connect to GLPI with glpi_python_client." license: MIT compatibility: "Requires Python 3.11+, glpi-python-client, network access to a GLPI v2 API, and valid GLPI credentials." metadata: @@ -56,7 +56,9 @@ call `client.close()` (or `await client.close()`) when finished. (`get_ticket_custom_fields`, `set_ticket_custom_fields`, `list_plugin_fields_containers`, `list_plugin_fields_fields`, `list_item_plugin_field_rows`, `create_item_plugin_field_row`, - `update_item_plugin_field_row`); KB category writes + `update_item_plugin_field_row`); ticket pending-reason items + (`get_ticket_pending_reason`, `set_ticket_pending_reason`, + `clear_ticket_pending_reason`); KB category writes (`set_kb_article_categories`, and `PostKBArticle.categories` / `PatchKBArticle.categories` passed to `create_kb_article` / `update_kb_article`); and actor-based statistics @@ -187,7 +189,8 @@ with GlpiClient.from_env( `upload_document` instead. - Use `glpi_api_url` for the v2 API; `v1_base_url` additionally enables every v1-backed feature listed in step 6 — document uploads, the - Fields plugin helpers, KB category writes and actor-based statistics. + Fields plugin helpers, ticket pending-reason items, KB category writes + and actor-based statistics. - Closing the client matters because it owns one or two HTTP sessions plus an OAuth token manager. Prefer the context-manager form. - Every **API** failure the library raises derives from `GlpiError`, diff --git a/skills/glpi-ticket-workflow/SKILL.md b/skills/glpi-ticket-workflow/SKILL.md index dde21cd..d1e3be8 100644 --- a/skills/glpi-ticket-workflow/SKILL.md +++ b/skills/glpi-ticket-workflow/SKILL.md @@ -82,4 +82,4 @@ ticket = PostTicket( - **Key on `status.id`, never on `status.name`.** The id set is hardcoded in GLPI's core — there is no `TicketStatus` itemtype (the v1 API answers 400 for it, while `ITILCategory` and `RequestType` return instance rows), and `listSearchOptions` reports `status` as `{"table": "glpi_tickets", "datatype": "specific"}`, i.e. a column of the tickets table rather than a foreign key into a configurable one. An administrator cannot add or rename a status. The **labels** are another matter: they are translations, so the same id reads back as `"Nouveau"` on a French instance and `"New"` on an English one. The ids `7`, `8`, `9`, `11`–`14` exist but belong to the sibling ITIL types, and they are literal integers in GLPI's source: `CommonITILObject` declares `INCOMING = 1` through `OBSERVED = 8` plus `APPROVAL = 10`, and `Change` adds `EVALUATION = 9`, `TEST = 11`, `QUALIFICATION = 12`, `REFUSED = 13`, `CANCELED = 14`. Each type's `getAllStatusArray()` is a hardcoded PHP array mapping those constants to *translated* labels — no database, no config table. The set is therefore coupled to the GLPI *version*, not to the instance. - **Never widen `status` to a plain `int`.** GLPI validates *nothing* on this field: `{"status": 99}` answers 200 and stores it. The ticket then reads back as `{"id": 99, "name": "99"}`, the web form shows it as *New*, and it vanishes from the ticket list while staying open in the database — only the ticket history records the change. A typo like `55` for `5` therefore loses a ticket in total silence, and the `GlpiTicketStatus` annotation is the only thing on the whole path that can stop it. `GetTicket.status` stays the permissive `IdNameRef` for the mirror-image reason: a strict enum on the read side would blow up an entire search over one poisoned row, the way a missing `Major` once did for `priority`. - Read-only fields are intentionally absent from `PostTicket`/`PatchTicket`; the server controls those transitions. `global_validation` is *not* one of them -- it is declared on both write models, typed `GlpiGlobalValidation | None`, whose members are `NONE = 1`, `WAITING = 2`, `ACCEPTED = 3`, `REFUSED = 4`. `GlpiGlobalValidation` is exported from the package root alongside `GlpiTicketStatus` (`NEW = 1`, `ASSIGNED = 2`, `PLANNED = 3`, `PENDING = 4`, `SOLVED = 5`, `CLOSED = 6`, `VALIDATION = 10`), `GlpiTicketType` (`INCIDENT = 1`, `REQUEST = 2`) and `GlpiPriority`; all of them stay readable on `GetTicket`. -- **A pause is status 4 plus a pending-reason item, and the status is yours to set.** `list_pending_reasons` (and the page iterator `iter_pending_reasons`) read the v2 catalogue. A ticket's item goes through the legacy v1 session, because the v2 item schema does not say which reason a ticket carries and no v2 route writes one: `get_ticket_pending_reason(tid)` returns a `PendingReasonItem` or `None`, `set_ticket_pending_reason(tid, reason_id, followup_frequency=0, followups_before_resolution=0)` creates or changes the item and returns it, `clear_ticket_pending_reason(tid)` returns `True` or `False` when there was none. All three raise `RuntimeError` without `v1_base_url` and `v1_user_token`. Setting a reason does not change the status (send `PatchTicket(status=GlpiTicketStatus.PENDING)` yourself); an item on a ticket that is not pending is stored but inert, and GLPI deletes it when the ticket leaves status 4. The item does not copy the catalogue's `followup_frequency`, so omitting it stores 0, and an id outside the catalogue is stored without error. None of these calls adds a followup to the timeline, unlike the GLPI web interface. +- **A pause is status 4 plus a pending-reason item, and the status is yours to set.** `list_pending_reasons` (and the page iterator `iter_pending_reasons`) read the v2 catalogue. A ticket's item goes through the legacy v1 session, because the v2 item schema does not say which reason a ticket carries and no v2 route writes one: `get_ticket_pending_reason(tid)` returns a `PendingReasonItem` or `None`, `set_ticket_pending_reason(tid, reason_id, followup_frequency=0, followups_before_resolution=0)` creates or changes the item and returns it, `clear_ticket_pending_reason(tid)` returns `True` or `False` when there was none. All three raise `RuntimeError` without `v1_base_url` and `v1_user_token`. Setting a reason does not change the status (send `PatchTicket(status=GlpiTicketStatus.PENDING)` yourself); an item on a ticket that is not pending is stored but inert, GLPI deletes an item when its ticket leaves status 4, but one set on a ticket that never was pending is not known to be cleaned up (clear it). The item does not copy the catalogue's `followup_frequency`, so omitting it stores 0, and an id outside the catalogue is stored without error. None of these calls adds a followup to the timeline, unlike the GLPI web interface.