285 lines
10 KiB
Python
285 lines
10 KiB
Python
import json
|
|
import os
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import Session
|
|
from app.settings import get_settings
|
|
from app.models.base import Base
|
|
from app.models.user import User
|
|
from app.models.role import Role
|
|
from app.models.status import Status
|
|
from app.models.priority import Priority
|
|
from app.models.category import Category
|
|
from app.models.ticket import Ticket
|
|
from app.models.email_message import EmailMessage, EmailAttachment
|
|
from app.models.extra import UserRole
|
|
from app.core.security import get_password_hash
|
|
|
|
|
|
def load_data(data):
|
|
"""Load all data into database."""
|
|
|
|
settings = get_settings()
|
|
engine = create_engine(settings.DATABASE_URL)
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
with Session(engine) as session:
|
|
# Maps
|
|
user_map = {}
|
|
category_map = {}
|
|
priority_map = {}
|
|
status_map = {}
|
|
ticket_map = {}
|
|
|
|
# Load roles
|
|
print("Loading roles...")
|
|
for r in data.get('roles', []):
|
|
role = session.query(Role).filter(Role.name == r['name']).first()
|
|
if not role:
|
|
role = Role(name=r['name'], description=r.get('description'))
|
|
session.add(role)
|
|
session.commit()
|
|
|
|
default_role = session.query(Role).filter(Role.name == 'customer').first()
|
|
|
|
# Load statuses
|
|
print("Loading statuses...")
|
|
for s in data.get('statuses', []):
|
|
status = session.query(Status).filter(Status.name == s['name']).first()
|
|
if not status:
|
|
status = Status(name=s['name'], is_final=s.get('is_final', False))
|
|
session.add(status)
|
|
session.flush()
|
|
status_map[s['original_id']] = status.id
|
|
session.commit()
|
|
|
|
# Load priorities
|
|
print("Loading priorities...")
|
|
for p in data.get('priorities', []):
|
|
priority = session.query(Priority).filter(Priority.name == p['name']).first()
|
|
if not priority:
|
|
priority = Priority(name=p['name'], level=p.get('level', 1), default_response_time_minutes=60)
|
|
session.add(priority)
|
|
session.flush()
|
|
priority_map[p['original_id']] = priority.id
|
|
session.commit()
|
|
|
|
# Load categories
|
|
print("Loading categories...")
|
|
for c in data.get('categories', []):
|
|
category = session.query(Category).filter(Category.name == c['name']).first()
|
|
if not category:
|
|
category = Category(name=c['name'])
|
|
session.add(category)
|
|
session.flush()
|
|
category_map[c['original_id']] = category.id
|
|
session.commit()
|
|
|
|
# Load users
|
|
print("Loading users...")
|
|
default_password = get_password_hash("migrated123")
|
|
|
|
for u in data.get('users', []):
|
|
email = u['email']
|
|
user = session.query(User).filter(User.email == email).first()
|
|
if not user:
|
|
user = User(
|
|
first_name=u['first_name'],
|
|
last_name=u['last_name'],
|
|
email=email,
|
|
password_hash=default_password,
|
|
phone=u.get('phone'),
|
|
is_active=u.get('is_active', True)
|
|
)
|
|
session.add(user)
|
|
session.flush()
|
|
|
|
if default_role:
|
|
session.add(UserRole(user_id=user.id, role_id=default_role.id))
|
|
|
|
user_map[u['original_id']] = user.id
|
|
session.commit()
|
|
|
|
# Load tickets
|
|
print("Loading tickets...")
|
|
for t in data.get('tickets', []):
|
|
tid = t['original_id']
|
|
|
|
category_id = category_map.get(t.get('category_original_id'))
|
|
priority_id = priority_map.get(t.get('priority_original_id'))
|
|
status_id = status_map.get(t.get('status_original_id'))
|
|
requester_id = user_map.get(t.get('requester_original_id'))
|
|
owner_id = user_map.get(t.get('owner_original_id'))
|
|
|
|
if not requester_id:
|
|
continue
|
|
|
|
if not status_id:
|
|
status_id = session.query(Status).first().id
|
|
if not priority_id:
|
|
priority_id = session.query(Priority).first().id
|
|
if not category_id:
|
|
category_id = session.query(Category).first().id
|
|
|
|
created_at = datetime.fromisoformat(t['created_at']) if t.get('created_at') else datetime.utcnow()
|
|
closed_at = datetime.fromisoformat(t['closed_at']) if t.get('closed_at') else None
|
|
|
|
ticket = Ticket(
|
|
subject=t['subject'],
|
|
description=t.get('description', ''),
|
|
category_id=category_id,
|
|
priority_id=priority_id,
|
|
status_id=status_id,
|
|
source=t.get('source', 'email'),
|
|
opened_by=requester_id,
|
|
assigned_to_id=owner_id,
|
|
created_at=created_at,
|
|
closed_at=closed_at
|
|
)
|
|
session.add(ticket)
|
|
session.flush()
|
|
ticket_map[tid] = ticket.id
|
|
session.commit()
|
|
print(f" Loaded {len(ticket_map)} tickets")
|
|
|
|
# Debug: show first 10 mappings
|
|
print("\nFirst 10 ticket mappings (original -> new):")
|
|
for i, (orig, new) in enumerate(list(ticket_map.items())[:10]):
|
|
print(f" {orig} -> {new}")
|
|
|
|
# Load conversations as email messages
|
|
print("\nLoading conversations...")
|
|
conv_count = 0
|
|
|
|
for conv in data.get('conversations', []):
|
|
ticket_orig_id = conv.get('ticket_original_id')
|
|
ticket_id = ticket_map.get(ticket_orig_id)
|
|
|
|
if not ticket_id:
|
|
print(f" Warning: No ticket mapping for original_id={ticket_orig_id}")
|
|
continue
|
|
|
|
# Determine direction
|
|
conv_type = conv.get('type', 'conversation')
|
|
direction = 'incoming' if conv_type == 'conversation' else 'note'
|
|
|
|
# Parse time
|
|
sent_at = None
|
|
if conv.get('sent_at'):
|
|
try:
|
|
sent_at = datetime.fromisoformat(conv['sent_at'])
|
|
except:
|
|
pass
|
|
|
|
# Get from info
|
|
from_name = conv.get('from_name', '')
|
|
from_email = conv.get('from_email', '')
|
|
|
|
# Get to addresses
|
|
to_list = conv.get('to', [])
|
|
to_addresses = ', '.join(to_list) if to_list else ''
|
|
|
|
cc_list = conv.get('cc', [])
|
|
cc_addresses = ', '.join(cc_list) if cc_list else None
|
|
|
|
email_msg = EmailMessage(
|
|
ticket_id=ticket_id,
|
|
direction=direction,
|
|
from_address=from_email or from_name or 'system',
|
|
to_addresses=to_addresses or 'system',
|
|
cc_addresses=cc_addresses,
|
|
subject=conv.get('subject', ''),
|
|
body_text=conv.get('description', ''),
|
|
body_html=conv.get('description', ''),
|
|
is_read=True,
|
|
sent_at=sent_at,
|
|
received_at=sent_at
|
|
)
|
|
session.add(email_msg)
|
|
session.flush()
|
|
conv_count += 1
|
|
|
|
# Load attachments for this conversation
|
|
for att in data.get('attachments', []):
|
|
if att.get('conversation_id') == conv.get('conversation_id') and att.get('ticket_original_id') == ticket_orig_id:
|
|
attachment = EmailAttachment(
|
|
email_message_id=email_msg.id,
|
|
filename=att.get('filename', 'unknown'),
|
|
content_type='application/octet-stream',
|
|
file_path=att.get('local_path', '')
|
|
)
|
|
session.add(attachment)
|
|
|
|
session.commit()
|
|
print(f" Loaded {conv_count} conversations")
|
|
|
|
# Load standalone attachments
|
|
print("Loading attachments...")
|
|
att_count = 0
|
|
|
|
for att in data.get('attachments', []):
|
|
if att.get('source') != 'request':
|
|
continue
|
|
|
|
ticket_orig_id = att.get('ticket_original_id')
|
|
ticket_id = ticket_map.get(ticket_orig_id)
|
|
|
|
if not ticket_id:
|
|
continue
|
|
|
|
# Create a pseudo email message for request attachments
|
|
email_msg = EmailMessage(
|
|
ticket_id=ticket_id,
|
|
direction='incoming',
|
|
from_address='attachment',
|
|
to_addresses='system',
|
|
subject=f'Вложение: {att.get("filename", "")}',
|
|
body_text=f'Файл: {att.get("filename", "")}',
|
|
is_read=True
|
|
)
|
|
session.add(email_msg)
|
|
session.flush()
|
|
|
|
attachment = EmailAttachment(
|
|
email_message_id=email_msg.id,
|
|
filename=att.get('filename', 'unknown'),
|
|
content_type='application/octet-stream',
|
|
file_path=att.get('local_path', '')
|
|
)
|
|
session.add(attachment)
|
|
att_count += 1
|
|
|
|
session.commit()
|
|
print(f" Loaded {att_count} request attachments")
|
|
|
|
# Summary
|
|
print("\n" + "="*50)
|
|
print("Migration complete!")
|
|
print(f" - Users: {len(user_map)}")
|
|
print(f" - Tickets: {len(ticket_map)}")
|
|
print(f" - Conversations: {conv_count}")
|
|
print(f" - Attachments: {att_count}")
|
|
print("="*50)
|
|
|
|
|
|
def main():
|
|
input_file = os.path.join(os.path.dirname(__file__), "transformed_full.json")
|
|
|
|
if not os.path.exists(input_file):
|
|
print(f"Error: {input_file} not found.")
|
|
return
|
|
|
|
print(f"Loading from: {input_file}")
|
|
with open(input_file, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
|
|
load_data(data)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|