50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
"""Push close decisions from pusat to city dashboard-cpsp."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
import requests
|
|
|
|
from apps.farms.models import Cycle
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class SiteClosePushError(Exception):
|
|
def __init__(self, message: str):
|
|
self.message = message
|
|
super().__init__(message)
|
|
|
|
|
|
def push_close_decision(cycle: Cycle, *, approved: bool) -> None:
|
|
city = cycle.city_site
|
|
if not city or not city.api_base_url or not city.api_key or not cycle.source_cycle_id:
|
|
logger.info("No city channel configured for cycle %s; skip push", cycle.pk)
|
|
return
|
|
|
|
base = city.api_base_url.rstrip("/")
|
|
url = f"{base}/cycles/{cycle.source_cycle_id}/apply-close-decision/"
|
|
payload = {"decision": "approve" if approved else "reject"}
|
|
if approved:
|
|
if not cycle.end_date:
|
|
raise SiteClosePushError("Approved cycle is missing end_date.")
|
|
payload["end_date"] = cycle.end_date.isoformat()
|
|
|
|
try:
|
|
response = requests.post(
|
|
url,
|
|
json=payload,
|
|
headers={"X-API-Key": city.api_key, "Content-Type": "application/json"},
|
|
timeout=30,
|
|
)
|
|
if response.status_code >= 400:
|
|
raise SiteClosePushError(
|
|
f"Gagal kirim keputusan ke situs ({response.status_code}: {response.text[:200]})"
|
|
)
|
|
except SiteClosePushError:
|
|
raise
|
|
except requests.RequestException as exc:
|
|
logger.exception("Push close decision failed for cycle %s", cycle.pk)
|
|
raise SiteClosePushError("Gagal kirim keputusan ke situs — coba lagi") from exc
|