ервый импорт проекта

This commit is contained in:
Арсентьев Александр
2026-08-06 00:01:51 +03:00
commit a2ac226028
9523 changed files with 999716 additions and 0 deletions
+250
View File
@@ -0,0 +1,250 @@
"""Extract data from ManageEngine ServiceDesk Plus MSSQL database."""
import pymssql
import json
import os
import sys
from typing import Dict, List, Optional
from datetime import datetime
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from migrations.config import MSSQL_CONFIG
def epoch_ms_to_datetime(epoch_ms: Optional[int]) -> Optional[datetime]:
"""Convert epoch milliseconds to datetime."""
if epoch_ms and epoch_ms > 0:
return datetime.fromtimestamp(epoch_ms / 1000.0)
return None
def extract_data(
server: str = MSSQL_CONFIG["server"],
database: str = MSSQL_CONFIG["database"],
user: str = MSSQL_CONFIG["user"],
password: str = MSSQL_CONFIG["password"],
port: int = MSSQL_CONFIG.get("port", 1433)
) -> Dict[str, List[Dict]]:
"""Extract data from ManageEngine database."""
print(f"Connecting to {server}/{database}...")
conn = pymssql.connect(
server=server,
user=user,
password=password,
database=database,
port=port,
login_timeout=30
)
cursor = conn.cursor(as_dict=True)
extracted_data = {}
# Extract tickets with state info
print("Extracting tickets...")
tickets_query = """
SELECT
wo.WORKORDERID as ticket_id,
wo.TITLE as subject,
wo.DESCRIPTION as description,
wo.REQUESTERID as requester_id,
wo.CREATEDBYID as created_by_id,
wo.CREATEDTIME as created_time,
wo.COMPLETEDTIME as completed_time,
wo.RESOLVEDTIME as resolved_time,
wo.DUEBYTIME as due_by_time,
wo.DEPTID as department_id,
wo.SITEID as site_id,
wos.CATEGORYID as category_id,
wos.SUBCATEGORYID as subcategory_id,
wos.OWNERID as owner_id,
wos.STATUSID as status_id,
wos.PRIORITYID as priority_id,
wos.IMPACTID as impact_id,
wos.URGENCYID as urgency_id,
wos.REQUESTTYPEID as request_type_id
FROM WorkOrder wo
LEFT JOIN WorkOrderStates wos ON wo.WORKORDERID = wos.WORKORDERID
"""
cursor.execute(tickets_query)
tickets = cursor.fetchall()
# Convert timestamps
for ticket in tickets:
ticket['created_at'] = epoch_ms_to_datetime(ticket.pop('created_time'))
ticket['completed_at'] = epoch_ms_to_datetime(ticket.pop('completed_time'))
ticket['resolved_at'] = epoch_ms_to_datetime(ticket.pop('resolved_time'))
ticket['due_by'] = epoch_ms_to_datetime(ticket.pop('due_by_time'))
extracted_data['tickets'] = tickets
print(f" Found {len(tickets)} tickets")
# Extract users from AaaUser with contact info
print("Exting users...")
users_query = """
SELECT
u.USER_ID as user_id,
u.FIRST_NAME as first_name,
u.LAST_NAME as last_name,
u.DESCRIPTION as description,
ci.EMAILID as email,
ci.MOBILE as phone,
ci.LANDLINE as landline,
sd.STATUS as sd_status,
sd.JOBTITLE as job_title
FROM AaaUser u
LEFT JOIN AaaUserContactInfo uci ON u.USER_ID = uci.USER_ID
LEFT JOIN AaaContactInfo ci ON uci.CONTACTINFO_ID = ci.CONTACTINFO_ID
LEFT JOIN SDUser sd ON u.USER_ID = sd.USERID
WHERE u.USER_ID > 2
"""
cursor.execute(users_query)
users = cursor.fetchall()
extracted_data['users'] = users
print(f" Found {len(users)} users")
# Extract categories
print("Extracting categories...")
categories_query = """
SELECT
CATEGORYID as category_id,
CATEGORYNAME as name,
CATEGORYDESCRIPTION as description
FROM CategoryDefinition
WHERE ISDELETED = 0
"""
cursor.execute(categories_query)
extracted_data['categories'] = cursor.fetchall()
print(f" Found {len(extracted_data['categories'])} categories")
# Extract priorities
print("Extracting priorities...")
priorities_query = """
SELECT
PRIORITYID as priority_id,
PRIORITYNAME as name,
PRIORITYCOLOR as color,
PRIORITYORDER as level,
PRIORITYDESCRIPTION as description
FROM PriorityDefinition
WHERE ISDELETED = 0
"""
cursor.execute(priorities_query)
extracted_data['priorities'] = cursor.fetchall()
print(f" Found {len(extracted_data['priorities'])} priorities")
# Extract statuses
print("Extracting statuses...")
statuses_query = """
SELECT
STATUSID as status_id,
STATUSNAME as name,
ISPENDING as is_pending,
STATUSDESCRIPTION as description
FROM StatusDefinition
WHERE ISDELETED = 0
"""
cursor.execute(statuses_query)
extracted_data['statuses'] = cursor.fetchall()
print(f" Found {len(extracted_data['statuses'])} statuses")
# Extract departments
print("Extracting departments...")
departments_query = """
SELECT
DEPTID as department_id,
DEPTNAME as name,
DEPTDESC as description,
PHONENO as phone
FROM DepartmentDefinition
WHERE ISDELETED = 0
"""
try:
cursor.execute(departments_query)
extracted_data['departments'] = cursor.fetchall()
print(f" Found {len(extracted_data['departments'])} departments")
except Exception as e:
print(f" Warning: Could not extract departments: {e}")
extracted_data['departments'] = []
# Extract sites/locations
print("Extracting sites...")
sites_query = """
SELECT
SITEID as site_id,
REGIONID as region_id
FROM SiteDefinition
WHERE ISDELETED = 0
"""
try:
cursor.execute(sites_query)
extracted_data['sites'] = cursor.fetchall()
print(f" Found {len(extracted_data['sites'])} sites")
except Exception as e:
print(f" Warning: Could not extract sites: {e}")
extracted_data['sites'] = []
# Extract notes/comments - SDPNotes doesn't have WORKORDERID, skip for now
print("Extracting notes...")
extracted_data['notes'] = []
print(f" Found 0 notes (SDPNotes has no ticket reference)")
# Extract WorkOrder history
print("Extracting WorkOrder history...")
history_query = """
SELECT
HISTORYID as history_id,
WORKORDERID as ticket_id,
OPERATIONOWNERID as user_id,
OPERATIONTIME as operation_time,
DESCRIPTION as description,
OPERATION as operation
FROM WorkOrderHistory
"""
try:
cursor.execute(history_query)
history = cursor.fetchall()
for h in history:
h['created_at'] = epoch_ms_to_datetime(h.pop('operation_time'))
extracted_data['history'] = history
print(f" Found {len(history)} history records")
except Exception as e:
print(f" Warning: Could not extract history: {e}")
extracted_data['history'] = []
# Close connection
cursor.close()
conn.close()
print(f"\nExtraction complete!")
print(f" - Tickets: {len(extracted_data['tickets'])}")
print(f" - Users: {len(extracted_data['users'])}")
print(f" - Categories: {len(extracted_data['categories'])}")
print(f" - Priorities: {len(extracted_data['priorities'])}")
print(f" - Statuses: {len(extracted_data['statuses'])}")
print(f" - Notes: {len(extracted_data['notes'])}")
return extracted_data
def main():
"""Main execution function."""
try:
extracted_data = extract_data()
# Save to JSON file
output_file = os.path.join(os.path.dirname(__file__), "extracted_data.json")
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(extracted_data, f, ensure_ascii=False, indent=2, default=str)
print(f"\nData extracted to: {output_file}")
except Exception as e:
print(f"Error during extraction: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()