Files
Brancheneinstufung2/connector-superoffice/create_email_test.py

131 lines
4.6 KiB
Python

import os
import requests
import json
import logging
import argparse
from dotenv import load_dotenv
load_dotenv(override=True)
from superoffice_client import SuperOfficeClient
from config import settings
# Setup Logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("create-email-test")
def create_email_document(person_id_input: int):
print(f"🚀 Creating Email Document for Person ID {person_id_input}...")
client = SuperOfficeClient()
if not client.access_token:
print("❌ Auth failed. Check .env")
return
# --- TARGET PERSON ---
target_person_id = person_id_input
contact_id = None
person_id = None
print(f"📡 Fetching target Person {target_person_id}...")
try:
person = client._get(f"Person/{target_person_id}")
if not person:
print(f"❌ Person {target_person_id} not found.")
return
print(f"✅ Found Person: {person.get('Firstname')} {person.get('Lastname')}")
# Get associated Contact ID
contact_id = person.get('Contact', {}).get('ContactId')
if not contact_id:
print("❌ Person has no associated company (ContactId).")
return
# Verify Contact
contact = client._get(f"Contact/{contact_id}")
if contact:
print(f"✅ Associated Company: {contact.get('Name')} (ID: {contact_id})")
person_id = target_person_id
except Exception as e:
print(f"❌ Error fetching Person/Contact: {e}")
return
if not contact_id or not person_id:
print("❌ Could not resolve Contact/Person IDs.")
return
# 2. Define Email Content
subject = "Test E-Mail from Gemini CLI (API)"
body = f"""Hallo {person.get('Firstname')},
Dies ist ein Test für die Erstellung eines E-Mail-Dokuments direkt über die SuperOffice API.
Wir nutzen das Template 'Ausg. E-Mail' (ID 157).
Viele Grüße,
Gemini"""
# 3. Create Document Payload
# Note: DocumentTemplateId 157 = "Ausg. E-Mail"
template_id = 157
payload = {
"Name": subject, # Internal Name
"Header": subject, # Subject Line
# "OurRef": {"AssociateId": my_associate_id}, # Omitted, hoping SO uses API User context
"Contact": {"ContactId": contact_id},
"Person": {"PersonId": person_id},
"DocumentTemplate": {"DocumentTemplateId": template_id},
"Content": body
}
print(f"📤 Sending POST /Document payload...")
try:
doc = client._post("Document", payload)
if doc:
doc_id = doc.get('DocumentId')
print(f"✅ Document Created Successfully!")
print(f" ID: {doc_id}")
print(f" Name: {doc.get('Name')}")
print(f" Template: {doc.get('DocumentTemplate', {}).get('Name')}")
# Construct direct link
# Format: https://online3.superoffice.com/Cust26720/default.aspx?document_id=334050
env = settings.SO_ENVIRONMENT
cust_id = settings.SO_CONTEXT_IDENTIFIER
# Note: This is a best-guess link format for SO Online
link = f"https://{env}.superoffice.com/{cust_id}/default.aspx?document_id={doc_id}"
print(f"🔗 Direct Link: {link}")
# 4. Create Linked Appointment (Activity)
print("📅 Creating Linked Appointment (Email Sent Activity)...")
appt_payload = {
"Description": body,
"Contact": {"ContactId": contact_id},
"Person": {"PersonId": person_id},
"Task": {"Id": 6}, # 6 = Document / Email Out
"Document": {"DocumentId": doc_id},
"MainHeader": f"E-Mail: {subject}"[:40]
}
try:
appt = client._post("Appointment", appt_payload)
if appt:
print(f"✅ Appointment Created: {appt.get('AppointmentId')}")
else:
print("⚠️ Failed to create appointment (None response).")
except Exception as e:
print(f"⚠️ Failed to create appointment: {e}")
else:
print("❌ Failed to create document (Response was empty/None).")
except Exception as e:
print(f"❌ Error creating document: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Create a test email document in SuperOffice.')
parser.add_argument('person_id', type=int, help='The SuperOffice Person ID to attach the email to.')
args = parser.parse_args()
create_email_document(args.person_id)