|
| 1 | +"""Interface to communicate with Fogbugz API |
| 2 | +
|
| 3 | +- Simple client to create cases in Fogbugz |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import logging |
| 8 | +from typing import Any |
| 9 | +from urllib.parse import urljoin |
| 10 | + |
| 11 | +import httpx |
| 12 | +from aiohttp import web |
| 13 | +from pydantic import AnyUrl, BaseModel, Field, SecretStr |
| 14 | + |
| 15 | +from ..products import products_service |
| 16 | +from ..products.models import Product |
| 17 | +from .settings import get_plugin_settings |
| 18 | + |
| 19 | +_logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +_JSON_CONTENT_TYPE = "application/json" |
| 22 | +_UNKNOWN_ERROR_MESSAGE = "Unknown error occurred" |
| 23 | + |
| 24 | +_FOGBUGZ_TIMEOUT: float = Field( |
| 25 | + default=45.0, description="API request timeout in seconds" |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +class FogbugzCaseCreate(BaseModel): |
| 30 | + fogbugz_project_id: str = Field(description="Project ID in Fogbugz") |
| 31 | + title: str = Field(description="Case title") |
| 32 | + description: str = Field(description="Case description/first comment") |
| 33 | + |
| 34 | + |
| 35 | +class FogbugzRestClient: |
| 36 | + """REST client for Fogbugz API""" |
| 37 | + |
| 38 | + def __init__(self, api_token: SecretStr, base_url: AnyUrl) -> None: |
| 39 | + self._client = httpx.AsyncClient(timeout=_FOGBUGZ_TIMEOUT) |
| 40 | + self._api_token = api_token |
| 41 | + self._base_url = base_url |
| 42 | + |
| 43 | + async def _make_api_request(self, json_payload: dict[str, Any]) -> dict[str, Any]: |
| 44 | + """Make a request to Fogbugz API with common formatting""" |
| 45 | + # Fogbugz requires multipart/form-data with stringified JSON |
| 46 | + files = {"request": (None, json.dumps(json_payload), _JSON_CONTENT_TYPE)} |
| 47 | + |
| 48 | + url = urljoin(f"{self._base_url}", "f/api/0/jsonapi") |
| 49 | + |
| 50 | + response = await self._client.post(url, files=files) |
| 51 | + response.raise_for_status() |
| 52 | + response_data: dict[str, Any] = response.json() |
| 53 | + return response_data |
| 54 | + |
| 55 | + async def create_case(self, data: FogbugzCaseCreate) -> str: |
| 56 | + """Create a new case in Fogbugz""" |
| 57 | + json_payload = { |
| 58 | + "cmd": "new", |
| 59 | + "token": self._api_token.get_secret_value(), |
| 60 | + "ixProject": data.fogbugz_project_id, |
| 61 | + "sTitle": data.title, |
| 62 | + "sEvent": data.description, |
| 63 | + } |
| 64 | + |
| 65 | + response_data = await self._make_api_request(json_payload) |
| 66 | + |
| 67 | + # Fogbugz API returns case ID in the response |
| 68 | + case_id = response_data.get("data", {}).get("case", {}).get("ixBug", None) |
| 69 | + if case_id is None: |
| 70 | + msg = "Failed to create case in Fogbugz" |
| 71 | + raise ValueError(msg) |
| 72 | + |
| 73 | + return str(case_id) |
| 74 | + |
| 75 | + async def resolve_case(self, case_id: str) -> None: |
| 76 | + """Resolve a case in Fogbugz""" |
| 77 | + json_payload = { |
| 78 | + "cmd": "resolve", |
| 79 | + "token": self._api_token.get_secret_value(), |
| 80 | + "ixBug": case_id, |
| 81 | + } |
| 82 | + |
| 83 | + response_data = await self._make_api_request(json_payload) |
| 84 | + |
| 85 | + # Check if the operation was successful |
| 86 | + if response_data.get("error"): |
| 87 | + error_msg = response_data.get("error", _UNKNOWN_ERROR_MESSAGE) |
| 88 | + msg = f"Failed to resolve case in Fogbugz: {error_msg}" |
| 89 | + raise ValueError(msg) |
| 90 | + |
| 91 | + async def get_case_status(self, case_id: str) -> str: |
| 92 | + """Get the status of a case in Fogbugz""" |
| 93 | + json_payload = { |
| 94 | + "cmd": "search", |
| 95 | + "token": self._api_token.get_secret_value(), |
| 96 | + "q": case_id, |
| 97 | + "cols": "sStatus", |
| 98 | + } |
| 99 | + |
| 100 | + response_data = await self._make_api_request(json_payload) |
| 101 | + |
| 102 | + # Check if the operation was successful |
| 103 | + if response_data.get("error"): |
| 104 | + error_msg = response_data.get("error", _UNKNOWN_ERROR_MESSAGE) |
| 105 | + msg = f"Failed to get case status from Fogbugz: {error_msg}" |
| 106 | + raise ValueError(msg) |
| 107 | + |
| 108 | + # Extract the status from the search results |
| 109 | + cases = response_data.get("data", {}).get("cases", []) |
| 110 | + if not cases: |
| 111 | + msg = f"Case {case_id} not found in Fogbugz" |
| 112 | + raise ValueError(msg) |
| 113 | + |
| 114 | + # Find the case with matching ixBug |
| 115 | + target_case = None |
| 116 | + for case in cases: |
| 117 | + if str(case.get("ixBug")) == str(case_id): |
| 118 | + target_case = case |
| 119 | + break |
| 120 | + |
| 121 | + if target_case is None: |
| 122 | + msg = f"Case {case_id} not found in search results" |
| 123 | + raise ValueError(msg) |
| 124 | + |
| 125 | + # Get the status from the found case |
| 126 | + status: str = target_case.get("sStatus", "") |
| 127 | + if not status: |
| 128 | + msg = f"Status not found for case {case_id}" |
| 129 | + raise ValueError(msg) |
| 130 | + |
| 131 | + return status |
| 132 | + |
| 133 | + async def reopen_case(self, case_id: str, assigned_fogbugz_person_id: str) -> None: |
| 134 | + """Reopen a case in Fogbugz (uses reactivate for resolved cases, reopen for closed cases)""" |
| 135 | + # First get the current status to determine which command to use |
| 136 | + current_status = await self.get_case_status(case_id) |
| 137 | + |
| 138 | + # Determine the command based on current status |
| 139 | + if current_status.lower().startswith("resolved"): |
| 140 | + cmd = "reactivate" |
| 141 | + elif current_status.lower().startswith("closed"): |
| 142 | + cmd = "reopen" |
| 143 | + else: |
| 144 | + msg = f"Cannot reopen case {case_id} with status '{current_status}'. Only resolved or closed cases can be reopened." |
| 145 | + raise ValueError(msg) |
| 146 | + |
| 147 | + json_payload = { |
| 148 | + "cmd": cmd, |
| 149 | + "token": self._api_token.get_secret_value(), |
| 150 | + "ixBug": case_id, |
| 151 | + "ixPersonAssignedTo": assigned_fogbugz_person_id, |
| 152 | + } |
| 153 | + |
| 154 | + response_data = await self._make_api_request(json_payload) |
| 155 | + |
| 156 | + # Check if the operation was successful |
| 157 | + if response_data.get("error"): |
| 158 | + error_msg = response_data.get("error", _UNKNOWN_ERROR_MESSAGE) |
| 159 | + msg = f"Failed to reopen case in Fogbugz: {error_msg}" |
| 160 | + raise ValueError(msg) |
| 161 | + |
| 162 | + |
| 163 | +_APP_KEY = f"{__name__}.{FogbugzRestClient.__name__}" |
| 164 | + |
| 165 | + |
| 166 | +async def setup_fogbugz_rest_client(app: web.Application) -> None: |
| 167 | + """Setup Fogbugz REST client""" |
| 168 | + settings = get_plugin_settings(app) |
| 169 | + |
| 170 | + # Fail fast if unexpected configuration |
| 171 | + products: list[Product] = products_service.list_products(app=app) |
| 172 | + for product in products: |
| 173 | + if product.support_standard_group_id is not None: |
| 174 | + if product.support_assigned_fogbugz_person_id is None: |
| 175 | + msg = ( |
| 176 | + f"Product '{product.name}' has support_standard_group_id set " |
| 177 | + "but `support_assigned_fogbugz_person_id` is not configured." |
| 178 | + ) |
| 179 | + raise ValueError(msg) |
| 180 | + if product.support_assigned_fogbugz_project_id is None: |
| 181 | + msg = ( |
| 182 | + f"Product '{product.name}' has support_standard_group_id set " |
| 183 | + "but `support_assigned_fogbugz_project_id` is not configured." |
| 184 | + ) |
| 185 | + raise ValueError(msg) |
| 186 | + else: |
| 187 | + _logger.info( |
| 188 | + "Product '%s' has support conversation disabled (therefore Fogbugz integration is not necessary for this product)", |
| 189 | + product.name, |
| 190 | + ) |
| 191 | + |
| 192 | + client = FogbugzRestClient( |
| 193 | + api_token=settings.FOGBUGZ_API_TOKEN, |
| 194 | + base_url=settings.FOGBUGZ_URL, |
| 195 | + ) |
| 196 | + |
| 197 | + app[_APP_KEY] = client |
| 198 | + |
| 199 | + |
| 200 | +def get_fogbugz_rest_client(app: web.Application) -> FogbugzRestClient: |
| 201 | + """Get Fogbugz REST client from app state""" |
| 202 | + app_key: FogbugzRestClient = app[_APP_KEY] |
| 203 | + return app_key |
0 commit comments