#!/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 = { "id": "test_admin_user", "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 = { "id": "test_tenant_user", "role": 2, # BUSINESS = 2 "tenant_id": "test_tenant_user", "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}/templates/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": """
{company_name} Logo

尊敬的 {candidate_name},

感谢您参加我们的笔试考核。以下是您的评估结果:

📊 评估详情

🔍 执行结果

⚠️ 执行错误信息

{execution_errors}

📈 详细结果

{detailed_results}

🎯 评估结论

{assessment_conclusion}

如有任何疑问,请联系我们的技术团队:

邮箱:{tech_support_email}

电话:{tech_support_phone}

祝好!
{company_name} 技术团队

""" } # English version (region: 0) template_data_en = { "template_id": "assessment_result_notification", "region": 0, "subject": "Assessment Result - {candidate_name}", "body": """
{company_name} Logo

Dear {candidate_name},

Thank you for participating in our assessment. Here are your evaluation results:

📊 Assessment Details

🔍 Execution Results

⚠️ 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": """
{company_name} Logo

尊敬的 {recipient_name},

⚠️ 截止期限提醒

您有一个任务即将到期:

📋 任务详情

⏰ 时间信息

📝 任务要求

{task_requirements}

🔗 相关链接

请务必在截止日期前完成相关任务。如有任何问题,请联系:

邮箱:{contact_email}

谢谢!
{company_name} 团队

""" } # English version (region: 0) template_data_en = { "template_id": "deadline_reminder", "region": 0, "subject": "Deadline Reminder - {task_name}", "body": """
{company_name} Logo

Dear {recipient_name},

⚠️ Deadline Reminder

You have a task that is approaching its deadline:

📋 Task Details

⏰ Time Information

📝 Task Requirements

{task_requirements}

🔗 Related Links

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": """
{company_name} Logo

尊敬的 {candidate_name},

您的面试状态已更新:

👤 候选人信息

📊 状态更新

📋 状态详情

{status_details}

📅 下一步安排

{next_steps}

⏰ 重要时间

📞 联系方式

请及时查看并准备相关材料。

祝面试顺利!
{company_name} 人力资源部

""" } # English version (region: 0) template_data_en = { "template_id": "interview_status_update", "region": 0, "subject": "Interview Status Update - {candidate_name}", "body": """
{company_name} Logo

Dear {candidate_name},

Your interview status has been updated:

👤 Candidate Information

📊 Status Update

📋 Status Details

{status_details}

📅 Next Steps

{next_steps}

⏰ Important Times

📞 Contact Information

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": """
{company_name} Logo

亲爱的 {new_employee_name},

🎉 欢迎加入 {company_name}!

我们很高兴地通知您,您已成功加入我们的团队。以下是您的入职信息:

👤 员工信息

🏢 公司信息

📋 入职安排

{onboarding_schedule}

🔑 系统访问信息

📚 重要资源

👥 联系人

🎯 第一周安排

{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": """
{company_name} Logo

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

🏢 Company Information

📋 Onboarding Schedule

{onboarding_schedule}

🔑 System Access Information

📚 Important Resources

👥 Contacts

🎯 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": """
{company_name} Logo

尊敬的 {user_name},

我们收到了您的密码重置请求。

🔐 重置信息

🔗 重置链接

点击重置密码

或复制链接:{reset_link}

⚠️ 重要提醒

📱 验证码

{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": """
{company_name} Logo

Dear {user_name},

We have received your password reset request.

🔐 Reset Information

🔗 Reset Link

Click to Reset Password

Or copy the link: {reset_link}

⚠️ Important Reminder

📱 Verification Code

{verification_code}

🔒 Security Tips

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": """
{company_name} Logo

尊敬的 {user_name},

感谢您注册 {company_name} 的账户。请验证您的邮箱地址以完成注册。

👤 账户信息

🔗 验证链接

点击验证邮箱

或复制链接:{verification_link}

📱 验证码

{verification_code}

⏰ 验证期限

✅ 验证步骤

  1. 点击上面的验证链接,或
  2. 在登录页面输入验证码:{verification_code}

⚠️ 安全提醒

📞 需要帮助?

🎯 验证完成后,您将可以:

谢谢!
{company_name} 团队

""" } # English version (region: 0) template_data_en = { "template_id": "account_verification_email", "region": 0, "subject": "Account Verification - {user_name}", "body": """
{company_name} Logo

Dear {user_name},

Thank you for registering an account with {company_name}. Please verify your email address to complete your registration.

👤 Account Information

🔗 Verification Link

Click to Verify Email

Or copy the link: {verification_link}

📱 Verification Code

{verification_code}

⏰ Verification Period

✅ Verification Steps

  1. Click the verification link above, or
  2. Enter the verification code on the login page: {verification_code}

⚠️ Security Reminder

📞 Need Help?

🎯 After verification, you will be able to:

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())