178 lines
6.9 KiB
Python
Executable file
178 lines
6.9 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""
|
|
Ekeepa Jira & PRD Dashboard Automated Sync Engine
|
|
Handles real-time status syncing, issue fetching, and bi-directional alignment
|
|
between Jira (jira.ekeepa-dev.ir) and the PRD Cockpit (ekeepa.zebellkhan.com/prds).
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import shutil
|
|
import urllib.request
|
|
import urllib.error
|
|
import subprocess
|
|
from datetime import datetime
|
|
|
|
BASE_DIR = "/workspace/prds"
|
|
ENV_PATH = os.path.join(BASE_DIR, ".jira.env")
|
|
JSON_PATH = os.path.join(BASE_DIR, "data", "prds.json")
|
|
BUILD_PATH = os.path.join(BASE_DIR, "build.py")
|
|
|
|
STATUS_CATEGORY_MAP = {
|
|
"new": "backlog", # Open, Backlog, Selected for Development
|
|
"indeterminate": "in_progress", # In Progress, Testing, Analysis, ready for marge
|
|
"done": "implemented" # Resolved, Closed, Done
|
|
}
|
|
|
|
STATUS_DETAILS = {
|
|
"backlog": {
|
|
"statusLabel": "در انتظار گرومینگ",
|
|
"folder": "backlog"
|
|
},
|
|
"in_progress": {
|
|
"statusLabel": "در حال توسعه (In Progress)",
|
|
"folder": "in_progress"
|
|
},
|
|
"implemented": {
|
|
"statusLabel": "پیادهسازی شده (Live)",
|
|
"folder": "implemented"
|
|
}
|
|
}
|
|
|
|
def load_jira_config():
|
|
if not os.path.exists(ENV_PATH):
|
|
raise FileNotFoundError(f"Configuration file not found: {ENV_PATH}")
|
|
config = {}
|
|
with open(ENV_PATH, "r", encoding="utf-8") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line and not line.startswith("#") and "=" in line:
|
|
k, v = line.split("=", 1)
|
|
config[k.strip()] = v.strip("\"'")
|
|
return config
|
|
|
|
def jira_api_call(endpoint, method="GET", body=None):
|
|
cfg = load_jira_config()
|
|
url = f"{cfg['JIRA_URL']}{endpoint}"
|
|
headers = {
|
|
"Authorization": f"Bearer {cfg['JIRA_PAT']}",
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json"
|
|
}
|
|
data = json.dumps(body).encode("utf-8") if body else None
|
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req) as resp:
|
|
return json.loads(resp.read().decode("utf-8"))
|
|
except urllib.error.HTTPError as e:
|
|
err_msg = e.read().decode("utf-8", errors="replace")
|
|
raise RuntimeError(f"Jira API error ({e.code}): {err_msg}")
|
|
|
|
def get_issue(issue_key):
|
|
endpoint = f"/rest/api/2/issue/{issue_key}?fields=summary,description,status,assignee,priority,components,created,updated"
|
|
return jira_api_call(endpoint)
|
|
|
|
def sync_dashboard():
|
|
"""Reads prds.json, fetches Jira status for each ticket, updates changes & rebuilds dashboard."""
|
|
if not os.path.exists(JSON_PATH):
|
|
print(f"Error: {JSON_PATH} not found.")
|
|
return
|
|
|
|
with open(JSON_PATH, "r", encoding="utf-8") as f:
|
|
prds = json.load(f)
|
|
|
|
changes_detected = False
|
|
|
|
for task in prds:
|
|
jira_key = task.get("jiraKey")
|
|
if not jira_key or jira_key == "None":
|
|
continue
|
|
|
|
try:
|
|
issue_data = get_issue(jira_key)
|
|
fields = issue_data.get("fields", {})
|
|
jira_status_name = fields.get("status", {}).get("name", "Unknown")
|
|
status_cat = fields.get("status", {}).get("statusCategory", {}).get("key", "new")
|
|
|
|
target_status = STATUS_CATEGORY_MAP.get(status_cat, "backlog")
|
|
current_status = task.get("status")
|
|
|
|
if target_status != current_status:
|
|
print(f"🔄 Task {jira_key} status changed in Jira: '{jira_status_name}' ({current_status} -> {target_status})")
|
|
changes_detected = True
|
|
|
|
cfg = STATUS_DETAILS[target_status]
|
|
task["status"] = target_status
|
|
task["statusLabel"] = cfg["statusLabel"]
|
|
|
|
# Move markdown file if exists
|
|
old_file_rel = task.get("filePath")
|
|
if old_file_rel:
|
|
old_file_abs = os.path.join(BASE_DIR, old_file_rel)
|
|
filename = os.path.basename(old_file_rel)
|
|
new_file_rel = os.path.join(cfg["folder"], filename)
|
|
new_file_abs = os.path.join(BASE_DIR, new_file_rel)
|
|
|
|
if old_file_abs != new_file_abs and os.path.exists(old_file_abs):
|
|
os.makedirs(os.path.dirname(new_file_abs), exist_ok=True)
|
|
shutil.move(old_file_abs, new_file_abs)
|
|
print(f" Moved file: {old_file_rel} -> {new_file_rel}")
|
|
task["filePath"] = new_file_rel
|
|
|
|
# Append changelog entry
|
|
if "versionsHistory" not in task:
|
|
task["versionsHistory"] = []
|
|
today_str = datetime.now().strftime("%Y-%m-%d")
|
|
task["versionsHistory"].insert(0, {
|
|
"version": task.get("version", "v1.0.0"),
|
|
"date": today_str,
|
|
"notes": f"همگامسازی خودکار با جیرا: تغییر وضعیت به «{jira_status_name}»"
|
|
})
|
|
|
|
except Exception as err:
|
|
print(f"⚠️ Could not check Jira status for {jira_key}: {err}")
|
|
|
|
if changes_detected:
|
|
with open(JSON_PATH, "w", encoding="utf-8") as f:
|
|
json.dump(prds, f, ensure_ascii=False, indent=2)
|
|
print("💾 Updated prds.json with new Jira states.")
|
|
|
|
# Re-build and deploy
|
|
subprocess.run([sys.executable, BUILD_PATH], check=True)
|
|
print("🚀 Dashboard successfully updated on https://ekeepa.zebellkhan.com/prds/")
|
|
else:
|
|
print("✅ All tasks are currently in sync with Jira. No changes required.")
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage:")
|
|
print(" jira_sync.py sync - Check Jira and sync dashboard statuses")
|
|
print(" jira_sync.py fetch <ISSUE_KEY> - Get full details of a Jira ticket")
|
|
sys.exit(0)
|
|
|
|
cmd = sys.argv[1].lower()
|
|
|
|
if cmd == "sync":
|
|
sync_dashboard()
|
|
elif cmd == "fetch" and len(sys.argv) > 2:
|
|
key = sys.argv[2].strip().upper()
|
|
try:
|
|
issue = get_issue(key)
|
|
fields = issue.get("fields", {})
|
|
print(f"\n📌 Ticket: {issue.get('key')}")
|
|
print(f"Summary: {fields.get('summary')}")
|
|
print(f"Status: {fields.get('status', {}).get('name')} (Category: {fields.get('status', {}).get('statusCategory', {}).get('name')})")
|
|
print(f"Priority: {fields.get('priority', {}).get('name')}")
|
|
print(f"Assignee: {fields.get('assignee', {}).get('displayName') if fields.get('assignee') else 'Unassigned'}")
|
|
print(f"Created: {fields.get('created')}")
|
|
print(f"Updated: {fields.get('updated')}")
|
|
print("\n--- Description ---")
|
|
print(fields.get("description", "No description provided."))
|
|
except Exception as e:
|
|
print(f"Error fetching issue {key}: {e}")
|
|
else:
|
|
print(f"Unknown command: {cmd}")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|