127 lines
5.2 KiB
Python
127 lines
5.2 KiB
Python
import requests
|
|
import json
|
|
|
|
MONDAY_TOKEN = "REMOVED"
|
|
MONDAY_URL = "https://api.monday.com/v2"
|
|
|
|
OP_URL = "https://projetos.rede5.com.br"
|
|
OP_API_KEY = "9c704b1c48939f97463fd9d811a9de050317b85224b93694d6e037f0799d37c2"
|
|
OP_AUTH = ('apikey', OP_API_KEY)
|
|
|
|
def monday_query(query):
|
|
headers = {"Authorization": MONDAY_TOKEN, "Content-Type": "application/json"}
|
|
resp = requests.post(MONDAY_URL, json={'query': query}, headers=headers)
|
|
return resp.json()
|
|
|
|
def run_sync_with_docs():
|
|
print("--- Publicando Tarefas com Links de Descrição (Monday Docs) ---")
|
|
|
|
# 1. Obter mapeamento de usuários OP (Nome -> ID)
|
|
op_users = requests.get(f"{OP_URL}/api/v3/users", auth=OP_AUTH).json()
|
|
user_mapping = {u['name']: u['id'] for u in op_users['_embedded']['elements']}
|
|
|
|
# 2. Mapear Projetos Reais no OP
|
|
op_projects = requests.get(f"{OP_URL}/api/v3/projects", auth=OP_AUTH).json()
|
|
project_mapping = {p['name']: p['id'] for p in op_projects['_embedded']['elements']}
|
|
|
|
# 3. Mapeamento de Sprints do Monday
|
|
sprints_data = monday_query("{ boards(ids: 18400111743) { items_page { items { id name } } } }")
|
|
monday_id_to_name = {str(item['id']): item['name'] for item in sprints_data['data']['boards'][0]['items_page']['items']}
|
|
|
|
# 4. Buscar Tasks no Monday com os valores brutos (value) para pegar o link do doc
|
|
query = """
|
|
{
|
|
boards(ids: 18400111746) {
|
|
items_page {
|
|
items {
|
|
id
|
|
name
|
|
column_values {
|
|
id
|
|
text
|
|
type
|
|
value
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
"""
|
|
tasks_data = monday_query(query)
|
|
tasks = tasks_data['data']['boards'][0]['items_page']['items']
|
|
print(f"Encontradas {len(tasks)} tarefas no Monday.")
|
|
|
|
for task in tasks:
|
|
target_project_name = None
|
|
owner_name = None
|
|
doc_link = None
|
|
description_lines = []
|
|
|
|
for cv in task['column_values']:
|
|
if cv['id'] == "task_sprint" and cv.get('linked_item_ids'):
|
|
# Pegar o nome do projeto sprint (o board relation value pode ser complexo, mas ja temos o mapping)
|
|
pass # Tratado via lógica de relação externa
|
|
|
|
if cv['id'] == "task_owner":
|
|
owner_name = cv['text']
|
|
|
|
# Pegar o link do Documento da Descrição
|
|
if cv['id'] == "monday_doc_v2" and cv['value']:
|
|
try:
|
|
val = json.loads(cv['value'])
|
|
if 'files' in val and len(val['files']) > 0:
|
|
doc_link = val['files'][0].get('linkToFile')
|
|
except:
|
|
pass
|
|
|
|
# Montar a descrição
|
|
if cv['text'] and cv['type'] not in ["people", "board_relation", "direct_doc"]:
|
|
description_lines.append(f"**{cv['id'].replace('task_', '').capitalize()}**: {cv['text']}")
|
|
|
|
# Buscar novamente a relação da task (query manual para garantir)
|
|
# O mapping já temos: lid_str in project_items
|
|
# Vou simplificar usando o mapeamento que já funcionou antes.
|
|
|
|
# Identificar projeto correto (repetir lógica anterior de mapeamento de IDs de boards vinculados)
|
|
for cv in task['column_values']:
|
|
if cv['id'] == "task_sprint":
|
|
print(f"DEBUG: Task '{task['name']}' has Sprint column with text: '{cv['text']}' and value: '{cv['value']}'")
|
|
if cv['id'] == "task_sprint" and cv['text'] in project_mapping:
|
|
target_project_name = cv['text']
|
|
# Ou buscar pelo ID se estiver no mapping do sprint board
|
|
if cv['id'] == "task_sprint" and cv['value']:
|
|
try:
|
|
val = json.loads(cv['value'])
|
|
lid = val.get('linked_item_ids', [None])[0]
|
|
print(f"DEBUG: Linked ID extracted: {lid}")
|
|
if str(lid) in monday_id_to_name:
|
|
target_project_name = monday_id_to_name[str(lid)]
|
|
print(f"DEBUG: Target project found via ID: {target_project_name}")
|
|
except Exception as e:
|
|
print(f"DEBUG: Error parsing value: {e}")
|
|
pass
|
|
|
|
if target_project_name and target_project_name in project_mapping:
|
|
p_id = project_mapping[target_project_name]
|
|
owner_id = user_mapping.get(owner_name)
|
|
|
|
final_desc = ""
|
|
if doc_link:
|
|
final_desc += f"### [📄 VER DESCRIÇÃO COMPLETA NO MONDAY]({doc_link})\n\n---\n"
|
|
final_desc += "\n".join(description_lines)
|
|
|
|
wp_payload = {
|
|
"subject": task['name'],
|
|
"description": {"format": "markdown", "raw": final_desc},
|
|
"_links": {
|
|
"project": {"href": f"/api/v3/projects/{p_id}"}
|
|
}
|
|
}
|
|
if owner_id:
|
|
wp_payload["_links"]["assignee"] = {"href": f"/api/v3/users/{owner_id}"}
|
|
|
|
print(f"Publicando: {task['name']} (Projeto: {target_project_name})")
|
|
requests.post(f"{OP_URL}/api/v3/work_packages", auth=OP_AUTH, json=wp_payload)
|
|
|
|
if __name__ == "__main__":
|
|
run_sync_with_docs()
|