feat(health-profiles): 添加健康档案模块,支持健康史记录、家庭健康管理和档案概览功能

This commit is contained in:
richarjiang
2025-12-04 17:15:11 +08:00
parent 03bd0b041e
commit 2d7e067888
20 changed files with 1949 additions and 0 deletions

View File

@@ -3092,4 +3092,83 @@ export class UsersService {
};
}
}
/**
* 获取用户健康邀请码
* 如果用户没有邀请码,则生成一个新的
*/
async getHealthInviteCode(userId: string): Promise<{ code: ResponseCode; message: string; data: { healthInviteCode: string } }> {
try {
const user = await this.userModel.findByPk(userId);
if (!user) {
return {
code: ResponseCode.ERROR,
message: '用户不存在',
data: { healthInviteCode: '' },
};
}
// 如果用户已有邀请码,直接返回
if (user.healthInviteCode) {
return {
code: ResponseCode.SUCCESS,
message: 'success',
data: { healthInviteCode: user.healthInviteCode },
};
}
// 生成唯一的邀请码8位随机字母数字组合
const healthInviteCode = await this.generateUniqueInviteCode(8);
// 保存到数据库
user.healthInviteCode = healthInviteCode;
await user.save();
this.logger.log(`为用户 ${userId} 生成健康邀请码: ${healthInviteCode}`);
return {
code: ResponseCode.SUCCESS,
message: 'success',
data: { healthInviteCode },
};
} catch (error) {
this.logger.error(`获取健康邀请码失败: ${error instanceof Error ? error.message : '未知错误'}`);
return {
code: ResponseCode.ERROR,
message: `获取健康邀请码失败: ${error instanceof Error ? error.message : '未知错误'}`,
data: { healthInviteCode: '' },
};
}
}
/**
* 生成唯一的邀请码,确保不与数据库中已有的重复
*/
private async generateUniqueInviteCode(length: number, maxAttempts = 10): Promise<string> {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let attempt = 0; attempt < maxAttempts; attempt++) {
// 生成随机邀请码
let code = '';
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
// 检查是否已存在
const existing = await this.userModel.findOne({
where: { healthInviteCode: code },
});
if (!existing) {
return code;
}
this.logger.warn(`邀请码 ${code} 已存在,重新生成(第 ${attempt + 1} 次尝试)`);
}
// 如果多次尝试都失败,使用时间戳+随机数确保唯一性
const timestamp = Date.now().toString(36).toUpperCase();
const random = Math.random().toString(36).substring(2, 6).toUpperCase();
return `${timestamp}${random}`.substring(0, length);
}
}