import logging from urllib.parse import urljoin import requests from django.conf import settings logger = logging.getLogger(__name__) class OneCClientError(Exception): """Raised when the 1C HTTP service is unavailable or returns an error.""" class OneCClient: """Thin HTTP client for the 1C side of the exchange. The 1C side is expected to expose an HTTP service (``/hs/homm``) with the endpoints described in ``docs/openapi-1c-outbound.yaml``. """ def __init__( self, base_url: str | None = None, username: str | None = None, password: str | None = None, timeout: int | None = None, ): self.base_url = (base_url or settings.ONEC_BASE_URL or "").rstrip("/") self.username = username if username is not None else settings.ONEC_USERNAME self.password = password if password is not None else settings.ONEC_PASSWORD self.timeout = timeout or settings.ONEC_TIMEOUT self.auth = ( (self.username, self.password) if self.username else None ) def _request(self, method: str, path: str, **kwargs) -> dict: if not self.base_url: raise OneCClientError("ONEC_BASE_URL не настроен") url = urljoin(f"{self.base_url}/", path.lstrip("/")) try: response = requests.request( method, url, auth=self.auth, timeout=self.timeout, headers={"Accept": "application/json"}, **kwargs, ) except requests.RequestException as exc: raise OneCClientError(f"1C недоступна: {exc}") from exc if response.status_code >= 400: raise OneCClientError( f"1C вернула {response.status_code}: {response.text[:500]}" ) if not response.content: return {} try: return response.json() except ValueError as exc: raise OneCClientError("1C вернула не-JSON ответ") from exc def fetch_catalog(self, since=None) -> dict: params = {"since": since.isoformat()} if since else {} return self._request("GET", "catalog/changes", params=params) def push_order(self, payload: dict) -> dict: return self._request("POST", "orders", json=payload) def push_order_status(self, external_id: str, payload: dict) -> dict: return self._request("POST", f"orders/{external_id}/status", json=payload) def push_customer(self, payload: dict) -> dict: return self._request("POST", "customers", json=payload) def fetch_order_status(self, external_id: str) -> dict: return self._request("GET", f"orders/{external_id}/status")