#!/usr/bin/env python3
"""
global template creator
"""
import asyncio
import aiohttp
import json
import os
import sys
from datetime import datetime, timezone, timedelta
from jose import jwt
sys.path.append('.')
from common.config.app_settings import app_settings
from webapi.config.site_settings import site_settings
class GlobalTemplateCreator:
def __init__(self):
# use site_settings to get base_url
host = 'localhost' if site_settings.SERVER_HOST == '0.0.0.0' else site_settings.SERVER_HOST
port = site_settings.SERVER_PORT
self.base_url = f"http://{host}:{port}/api/notification"
self.admin_token = None
self.templates = []
print(f"🔧 use config: {self.base_url}")
def generate_test_tokens(self):
"""generate test JWT token"""
secret_key = app_settings.SECRET_KEY
algorithm = "HS256"
# generate admin token
admin_payload = {
"role": 8, # ADMINISTRATOR = 8
"tenant_id": None,
"exp": datetime.now(timezone.utc) + timedelta(hours=1)
}
admin_token = jwt.encode(admin_payload, secret_key, algorithm=algorithm)
# generate tenant token
tenant_payload = {
"role": 2, # BUSINESS = 2
"tenant_id": "magicleaps",
"exp": datetime.now(timezone.utc) + timedelta(hours=1)
}
tenant_token = jwt.encode(tenant_payload, secret_key, algorithm=algorithm)
print("\n🔑 generated test tokens:")
print("=" * 60)
print(f"Admin Token: {admin_token}")
print(f"Tenant Token: {tenant_token}")
print(f"Secret Key: {secret_key[:20]}...")
print("=" * 60)
return admin_token, tenant_token
async def get_admin_token(self):
"""get admin token"""
print("🔑 get admin token...")
try:
admin_token, tenant_token = self.generate_test_tokens()
self.admin_token = admin_token
if self.admin_token:
print("✅ admin token retrieved successfully")
return True
else:
print("❌ admin token retrieval failed")
return False
except Exception as e:
print(f"❌ error getting token: {e}")
return False
async def create_template(self, template_data):
"""create template"""
if not self.admin_token:
print("❌ no valid admin token")
return False
headers = {"Authorization": f"Bearer {self.admin_token}"}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/admin/global_templates/create",
json=template_data,
headers=headers
) as response:
print(f"status code: {response.status}")
response_text = await response.text()
print(f"response: {response_text}")
if response.status == 201:
print(f"✅ template '{template_data['template_id']}' created successfully")
return True
else:
print(f"❌ template '{template_data['template_id']}' creation failed: {response_text}")
return False
async def create_assessment_result_template(self):
"""create assessment result notification template"""
print("\n📝 create assessment result notification template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "assessment_result_notification",
"region": 1,
"subject": "笔试结果 - {{candidate_name}}",
"body": """
尊敬的 {{candidate_name}},
感谢您参加我们的笔试考核。以下是您的评估结果:
📊 评估详情
- 候选人姓名:{{candidate_name}}
- 评估日期:{{assessment_date}}
- 评估时长:{{duration_minutes}} 分钟
🔍 执行结果
- 执行状态:{{execution_status}}
- 执行时间:{{execution_time}} 毫秒
- 测试用例通过率:{{test_cases_passed}}/{{total_test_cases}} ({{pass_rate}}%)
⚠️ 执行错误信息
{{execution_errors}}
📈 详细结果
{{detailed_results}}
🎯 评估结论
{{assessment_conclusion}}
如有任何疑问,请联系我们的技术团队:
邮箱:{{tech_support_email}}
电话:{{tech_support_phone}}
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "assessment_result_notification",
"region": 0,
"subject": "Assessment Result - {{candidate_name}}",
"body": """
Dear {{candidate_name}},
Thank you for participating in our assessment. Here are your evaluation results:
📊 Assessment Details
- Candidate Name: {{candidate_name}}
- Assessment Date: {{assessment_date}}
- Duration: {{duration_minutes}} minutes
🔍 Execution Results
- Execution Status: {{execution_status}}
- Execution Time: {{execution_time}} milliseconds
- Test Cases Passed: {{test_cases_passed}}/{{total_test_cases}} ({{pass_rate}}%)
⚠️ Execution Errors
{{execution_errors}}
📈 Detailed Results
{{detailed_results}}
🎯 Assessment Conclusion
{{assessment_conclusion}}
If you have any questions, please contact our technical team:
Email: {{tech_support_email}}
Phone: {{tech_support_phone}}
Best regards,
{{company_name}} Technical Team
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_deadline_reminder_template(self):
"""create deadline reminder template"""
print("\n📝 create deadline reminder template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "deadline_reminder",
"region": 1,
"subject": "截止期限提醒 - {{task_name}}",
"body": """
尊敬的 {{recipient_name}},
📋 任务详情
- 任务名称:{{task_name}}
- 任务描述:{{task_description}}
- 截止日期:{{deadline_date}}
- 剩余时间:{{remaining_time}}
⏰ 时间信息
- 当前时间:{{current_time}}
- 截止时间:{{deadline_time}}
- 剩余天数:{{days_remaining}} 天
📝 任务要求
{{task_requirements}}
请务必在截止日期前完成相关任务。如有任何问题,请联系:
邮箱:{{contact_email}}
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "deadline_reminder",
"region": 0,
"subject": "Deadline Reminder - {{task_name}}",
"body": """
Dear {{recipient_name}},
⚠️ Deadline Reminder
You have a task that is approaching its deadline:
📋 Task Details
- Task Name: {{task_name}}
- Task Description: {{task_description}}
- Deadline Date: {{deadline_date}}
- Time
⏰ Time Information
- Current Time: {{current_time}}
- Deadline Time: {{deadline_time}}
- Days Remaining: {{days_remaining}} days
📝 Task Requirements
{{task_requirements}}
Please ensure to complete the related task before the deadline. If you have any questions, please contact:
Email: {{contact_email}}
Thank you!
{{company_name}} Team
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_interview_status_update_template(self):
"""create interview status update template"""
print("\n📝 create interview status update template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "interview_status_update",
"region": 1,
"subject": "面试状态更新 - {{candidate_name}}",
"body": """
尊敬的 {{candidate_name}},
您的面试状态已更新:
👤 候选人信息
- 姓名:{{candidate_name}}
- 应聘职位:{{position_name}}
- 申请编号:{{application_id}}
📊 状态更新
- 当前状态:{{current_status}}
- 更新日期:{{update_date}}
- 更新时间:{{update_time}}
📋 状态详情
{{status_details}}
⏰ 重要时间
- 面试时间:{{interview_time}}
- 面试地点:{{interview_location}}
- 面试官:{{interviewer_name}}
📞 联系方式
- 面试官邮箱:{{interviewer_email}}
- 面试官电话:{{interviewer_phone}}
- 公司地址:{{company_address}}
祝面试顺利!
{{company_name}} 人力资源部
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "interview_status_update",
"region": 0,
"subject": "Interview Status Update - {{candidate_name}}",
"body": """
Dear {{candidate_name}},
Your interview status has been updated:
👤 Candidate Information
- Name: {{candidate_name}}
- Position Applied: {{position_name}}
- Application ID: {{application_id}}
📊 Status Update
- Current Status: {{current_status}}
- Update Date: {{update_date}}
- Update Time: {{update_time}}
📋 Status Details
{{status_details}}
📅 Next Steps
{{next_steps}}
⏰ Important Times
- Interview Time: {{interview_time}}
- Interview Location: {{interview_location}}
- Interviewer: {{interviewer_name}}
📞 Contact Information
- Interviewer Email: {{interviewer_email}}
- Interviewer Phone: {{interviewer_phone}}
- Company Address: {{company_address}}
Please review and prepare relevant materials in a timely manner.
Good luck with your interview!
{{company_name}} Human Resources Department
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_welcome_email_template(self):
"""create welcome email template"""
print("\n📝 create welcome email template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "welcome_email",
"region": 1,
"subject": "欢迎加入 {{company_name}} - {{new_employee_name}}",
"body": """
亲爱的 {{new_employee_name}},
🎉 欢迎加入 {{company_name}}!
我们很高兴地通知您,您已成功加入我们的团队。以下是您的入职信息:
👤 员工信息
- 姓名:{{new_employee_name}}
- 员工编号:{{employee_id}}
- 部门:{{department}}
- 职位:{{position}}
- 入职日期:{{start_date}}
🏢 公司信息
- 公司名称:{{company_name}}
- 公司地址:{{company_address}}
- 联系电话:{{company_phone}}
📋 入职安排
{{onboarding_schedule}}
👥 联系人
- 直属经理:{{manager_name}} ({{manager_email}})
- HR联系人:{{hr_contact_name}} ({{hr_contact_email}})
- IT支持:{{it_support_email}}
🎯 第一周安排
{{first_week_schedule}}
再次欢迎您的加入!
{{company_name}} 团队
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "welcome_email",
"region": 0,
"subject": "Welcome to {{company_name}} - {{new_employee_name}}",
"body": """
Dear {{new_employee_name}},
🎉 Welcome to {{company_name}}!
We are pleased to inform you that you have successfully joined our team. Here is your onboarding information:
👤 Employee Information
- Name: {{new_employee_name}}
- Employee ID: {{employee_id}}
- Department: {{department}}
- Position: {{position}}
- Start Date: {{start_date}}
🏢 Company Information
- Company Name: {{company_name}}
- Company Address: {{company_address}}
- Contact Phone: {{company_phone}}
📋 Onboarding Schedule
{{onboarding_schedule}}
🔑 System Access Information
- Email: {{email_address}}
- Initial Password: {{initial_password}}
- System Login URL: {{system_login_url}}
👥 Contacts
- Direct Manager: {{manager_name}} ({{manager_email}})
- HR Contact: {{hr_contact_name}} ({{hr_contact_email}})
- IT Support: {{it_support_email}}
🎯 First Week Schedule
{{first_week_schedule}}
If you have any questions, please feel free to contact us.
Welcome aboard!
{{company_name}} Team
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_password_reset_template(self):
"""create password reset email template"""
print("\n📝 create password reset email template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "password_reset_email",
"region": 1,
"subject": "密码重置请求 - {{user_name}}",
"body": """
尊敬的 {{user_name}},
我们收到了您的密码重置请求。
🔐 重置信息
- 用户名:{{user_name}}
- 邮箱:{{email_address}}
- 请求时间:{{request_time}}
- 请求IP:{{request_ip}}
🔗 重置链接
点击重置密码
或复制链接:{{reset_link}}
⚠️ 重要提醒
- • 此链接将在 {{expiry_hours}} 小时后失效
- • 请勿将此链接分享给他人
- • 如果您没有请求重置密码,请忽略此邮件
📱 验证码
{{verification_code}}
🔒 安全提示
- • 请使用强密码(包含大小写字母、数字和特殊字符)
- • 不要使用与其他账户相同的密码
- • 定期更换密码以确保账户安全
如有任何问题,请联系技术支持:
邮箱:{{support_email}}
电话:{{support_phone}}
谢谢!
{{company_name}} 技术支持团队
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "password_reset_email",
"region": 0,
"subject": "Password Reset Request - {{user_name}}",
"body": """
Dear {{user_name}},
We have received your password reset request.
🔐 Reset Information
- Username: {{user_name}}
- Email: {{email_address}}
- Request Time: {{request_time}}
- Request IP: {{request_ip}}
⚠️ Important Reminder
- • This link will expire in {{expiry_hours}} hours
- • Please do not share this link with others
- • If you did not request a password reset, please ignore this email
📱 Verification Code
{{verification_code}}
🔒 Security Tips
- • Please use a strong password (containing uppercase and lowercase letters, numbers, and special characters)
- • Do not use the same password as other accounts
- • Change your password regularly to ensure account security
If you have any questions, please contact technical support:
Email: {{support_email}}
Phone: {{support_phone}}
Thank you!
{{company_name}} Technical Support Team
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_account_verification_template(self):
"""create account verification email template"""
print("\n📝 create account verification email template...")
# Chinese version (region: 1)
template_data_cn = {
"template_id": "account_verification_email",
"region": 1,
"subject": "账号验证 - {{user_name}}",
"body": """
尊敬的 {{user_name}},
感谢您注册 {{company_name}} 的账户。请验证您的邮箱地址以完成注册。
👤 账户信息
- 用户名:{{user_name}}
- 邮箱地址:{{email_address}}
- 注册时间:{{registration_time}}
🔗 验证链接
点击验证邮箱
或复制链接:{{verification_link}}
📱 验证码
{{verification_code}}
⏰ 验证期限
- 验证链接有效期:{{expiry_hours}} 小时
- 请在 {{expiry_time}} 前完成验证
✅ 验证步骤
- 点击上面的验证链接,或
- 在登录页面输入验证码:{{verification_code}}
⚠️ 安全提醒
- • 请勿将验证码分享给他人
- • 如果您没有注册账户,请忽略此邮件
- • 验证完成后,请立即登录并修改初始密码
📞 需要帮助?
- 技术支持:{{support_email}}
- 客服热线:{{support_phone}}
🎯 验证完成后,您将可以:
- • 访问所有功能
- • 接收重要通知
- • 管理个人信息
"""
}
# English version (region: 0)
template_data_en = {
"template_id": "account_verification_email",
"region": 0,
"subject": "Account Verification - {{user_name}}",
"body": """
Dear {{user_name}},
Thank you for registering an account with {{company_name}}. Please verify your email address to complete your registration.
👤 Account Information
- Username: {{user_name}}
- Email Address: {{email_address}}
- Registration Time: {{registration_time}}
📱 Verification Code
{{verification_code}}
⏰ Verification Period
- Verification Link Valid: {{expiry_hours}} hours
- Please complete verification before {{expiry_time}}
✅ Verification Steps
- Click the verification link above, or
- Enter the verification code on the login page: {{verification_code}}
⚠️ Security Reminder
- • Please do not share the verification code with others
- • If you did not register an account, please ignore this email
- • After verification, please log in immediately and change your initial password
📞 Need Help?
- Technical Support: {{support_email}}
- Customer Service: {{support_phone}}
🎯 After verification, you will be able to:
- • Access all features
- • Receive important notifications
- • Manage personal information
Thank you!
{{company_name}} Team
"""
}
success_cn = await self.create_template(template_data_cn)
success_en = await self.create_template(template_data_en)
return success_cn and success_en
async def create_all_templates(self):
"""create all templates"""
print("🚀 start creating global templates...")
print("=" * 60)
# get admin token
await self.get_admin_token()
# create all templates
templates_to_create = [
self.create_assessment_result_template,
self.create_deadline_reminder_template,
self.create_interview_status_update_template,
self.create_welcome_email_template,
self.create_password_reset_template,
self.create_account_verification_template
]
success_count = 0
for create_func in templates_to_create:
if await create_func():
success_count += 1
print(f"\n✅ templates created successfully! created {success_count}/{len(templates_to_create)} templates")
# display created template list
print("\n📋 created templates list:")
template_names = [
"assessment_result_notification - 评估结果通知",
"deadline_reminder - 截止期限提醒",
"interview_status_update - 面试状态更新",
"welcome_email - 欢迎邮件",
"password_reset_email - 密码重置邮件",
"account_verification_email - 账号验证邮件"
]
for i, name in enumerate(template_names, 1):
print(f"{i}. {name}")
async def main():
"""main function"""
creator = GlobalTemplateCreator()
await creator.create_all_templates()
if __name__ == "__main__":
asyncio.run(main())