11
This commit is contained in:
199
api/middleware/schedule/services/accountValidator.js
Normal file
199
api/middleware/schedule/services/accountValidator.js
Normal file
@@ -0,0 +1,199 @@
|
||||
const db = require('../../dbProxy');
|
||||
const authorizationService = require('../../../services/authorization_service');
|
||||
const deviceManager = require('../core/deviceManager');
|
||||
|
||||
/**
|
||||
* 账户验证服务
|
||||
* 统一处理账户启用状态、授权状态、在线状态的检查
|
||||
*/
|
||||
class AccountValidator {
|
||||
/**
|
||||
* 检查账户是否启用
|
||||
* @param {string} sn_code - 设备序列号
|
||||
* @returns {Promise<{enabled: boolean, reason?: string}>}
|
||||
*/
|
||||
async checkEnabled(sn_code) {
|
||||
try {
|
||||
const pla_account = db.getModel('pla_account');
|
||||
const account = await pla_account.findOne({
|
||||
where: { sn_code, is_delete: 0 },
|
||||
attributes: ['is_enabled', 'name']
|
||||
});
|
||||
|
||||
if (!account) {
|
||||
return { enabled: false, reason: '账户不存在' };
|
||||
}
|
||||
|
||||
if (!account.is_enabled) {
|
||||
return { enabled: false, reason: '账户未启用' };
|
||||
}
|
||||
|
||||
return { enabled: true };
|
||||
} catch (error) {
|
||||
console.error(`[账户验证] 检查启用状态失败 (${sn_code}):`, error);
|
||||
return { enabled: false, reason: '检查失败' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查账户授权状态
|
||||
* @param {string} sn_code - 设备序列号
|
||||
* @returns {Promise<{authorized: boolean, days?: number, reason?: string}>}
|
||||
*/
|
||||
async checkAuthorization(sn_code) {
|
||||
try {
|
||||
const result = await authorizationService.checkAuthorization(sn_code);
|
||||
|
||||
if (!result.is_authorized) {
|
||||
return {
|
||||
authorized: false,
|
||||
days: result.days_remaining || 0,
|
||||
reason: result.message || '授权已过期'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authorized: true,
|
||||
days: result.days_remaining
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`[账户验证] 检查授权状态失败 (${sn_code}):`, error);
|
||||
return { authorized: false, reason: '授权检查失败' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查设备是否在线
|
||||
* @param {string} sn_code - 设备序列号
|
||||
* @param {number} offlineThreshold - 离线阈值(毫秒)
|
||||
* @returns {{online: boolean, lastHeartbeat?: number, reason?: string}}
|
||||
*/
|
||||
checkOnline(sn_code, offlineThreshold = 3 * 60 * 1000) {
|
||||
const device = deviceManager.devices.get(sn_code);
|
||||
|
||||
if (!device) {
|
||||
return { online: false, reason: '设备从未发送心跳' };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const lastHeartbeat = device.lastHeartbeat || 0;
|
||||
const elapsed = now - lastHeartbeat;
|
||||
|
||||
if (elapsed > offlineThreshold) {
|
||||
const minutes = Math.round(elapsed / (60 * 1000));
|
||||
return {
|
||||
online: false,
|
||||
lastHeartbeat,
|
||||
reason: `设备离线(最后心跳: ${minutes}分钟前)`
|
||||
};
|
||||
}
|
||||
|
||||
if (!device.isOnline) {
|
||||
return { online: false, lastHeartbeat, reason: '设备标记为离线' };
|
||||
}
|
||||
|
||||
return { online: true, lastHeartbeat };
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合验证(启用 + 授权 + 在线)
|
||||
* @param {string} sn_code - 设备序列号
|
||||
* @param {object} options - 验证选项
|
||||
* @param {boolean} options.checkEnabled - 是否检查启用状态(默认 true)
|
||||
* @param {boolean} options.checkAuth - 是否检查授权(默认 true)
|
||||
* @param {boolean} options.checkOnline - 是否检查在线(默认 true)
|
||||
* @param {number} options.offlineThreshold - 离线阈值(默认 3分钟)
|
||||
* @returns {Promise<{valid: boolean, reason?: string, details?: object}>}
|
||||
*/
|
||||
async validate(sn_code, options = {}) {
|
||||
const {
|
||||
checkEnabled = true,
|
||||
checkAuth = true,
|
||||
checkOnline = true,
|
||||
offlineThreshold = 3 * 60 * 1000
|
||||
} = options;
|
||||
|
||||
const details = {};
|
||||
|
||||
// 检查启用状态
|
||||
if (checkEnabled) {
|
||||
const enabledResult = await this.checkEnabled(sn_code);
|
||||
details.enabled = enabledResult;
|
||||
|
||||
if (!enabledResult.enabled) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: enabledResult.reason,
|
||||
details
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 检查授权状态
|
||||
if (checkAuth) {
|
||||
const authResult = await this.checkAuthorization(sn_code);
|
||||
details.authorization = authResult;
|
||||
|
||||
if (!authResult.authorized) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: authResult.reason,
|
||||
details
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 检查在线状态
|
||||
if (checkOnline) {
|
||||
const onlineResult = this.checkOnline(sn_code, offlineThreshold);
|
||||
details.online = onlineResult;
|
||||
|
||||
if (!onlineResult.online) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: onlineResult.reason,
|
||||
details
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true, details };
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量验证多个账户
|
||||
* @param {string[]} sn_codes - 设备序列号数组
|
||||
* @param {object} options - 验证选项
|
||||
* @returns {Promise<{valid: string[], invalid: Array<{sn_code: string, reason: string}>}>}
|
||||
*/
|
||||
async validateBatch(sn_codes, options = {}) {
|
||||
const valid = [];
|
||||
const invalid = [];
|
||||
|
||||
for (const sn_code of sn_codes) {
|
||||
const result = await this.validate(sn_code, options);
|
||||
|
||||
if (result.valid) {
|
||||
valid.push(sn_code);
|
||||
} else {
|
||||
invalid.push({ sn_code, reason: result.reason });
|
||||
}
|
||||
}
|
||||
|
||||
return { valid, invalid };
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查账户是否已登录(通过心跳数据)
|
||||
* @param {string} sn_code - 设备序列号
|
||||
* @returns {boolean}
|
||||
*/
|
||||
checkLoggedIn(sn_code) {
|
||||
const device = deviceManager.devices.get(sn_code);
|
||||
return device?.isLoggedIn || false;
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例
|
||||
const accountValidator = new AccountValidator();
|
||||
module.exports = accountValidator;
|
||||
225
api/middleware/schedule/services/configManager.js
Normal file
225
api/middleware/schedule/services/configManager.js
Normal file
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* 配置管理服务
|
||||
* 统一处理账户配置的解析和验证
|
||||
*/
|
||||
class ConfigManager {
|
||||
/**
|
||||
* 解析 JSON 配置字符串
|
||||
* @param {string|object} config - 配置字符串或对象
|
||||
* @param {object} defaultValue - 默认值
|
||||
* @returns {object} 解析后的配置对象
|
||||
*/
|
||||
static parseConfig(config, defaultValue = {}) {
|
||||
if (!config) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
if (typeof config === 'object') {
|
||||
return { ...defaultValue, ...config };
|
||||
}
|
||||
|
||||
if (typeof config === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(config);
|
||||
return { ...defaultValue, ...parsed };
|
||||
} catch (error) {
|
||||
console.warn('[配置管理] JSON 解析失败:', error.message);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析投递配置
|
||||
* @param {string|object} deliverConfig - 投递配置
|
||||
* @returns {object} 标准化的投递配置
|
||||
*/
|
||||
static parseDeliverConfig(deliverConfig) {
|
||||
const defaultConfig = {
|
||||
deliver_interval: 30, // 投递间隔(分钟)
|
||||
min_salary: 0, // 最低薪资
|
||||
max_salary: 0, // 最高薪资
|
||||
page_count: 3, // 搜索页数
|
||||
max_deliver: 10, // 最大投递数
|
||||
filter_keywords: [], // 过滤关键词
|
||||
exclude_keywords: [], // 排除关键词
|
||||
time_range: null, // 时间范围
|
||||
priority_weights: null // 优先级权重
|
||||
};
|
||||
|
||||
return this.parseConfig(deliverConfig, defaultConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析搜索配置
|
||||
* @param {string|object} searchConfig - 搜索配置
|
||||
* @returns {object} 标准化的搜索配置
|
||||
*/
|
||||
static parseSearchConfig(searchConfig) {
|
||||
const defaultConfig = {
|
||||
search_interval: 60, // 搜索间隔(分钟)
|
||||
page_count: 3, // 搜索页数
|
||||
keywords: [], // 搜索关键词
|
||||
exclude_keywords: [], // 排除关键词
|
||||
time_range: null // 时间范围
|
||||
};
|
||||
|
||||
return this.parseConfig(searchConfig, defaultConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析沟通配置
|
||||
* @param {string|object} chatStrategy - 沟通策略
|
||||
* @returns {object} 标准化的沟通配置
|
||||
*/
|
||||
static parseChatStrategy(chatStrategy) {
|
||||
const defaultConfig = {
|
||||
chat_interval: 30, // 沟通间隔(分钟)
|
||||
auto_reply: false, // 是否自动回复
|
||||
reply_template: '', // 回复模板
|
||||
time_range: null // 时间范围
|
||||
};
|
||||
|
||||
return this.parseConfig(chatStrategy, defaultConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析活跃配置
|
||||
* @param {string|object} activeStrategy - 活跃策略
|
||||
* @returns {object} 标准化的活跃配置
|
||||
*/
|
||||
static parseActiveStrategy(activeStrategy) {
|
||||
const defaultConfig = {
|
||||
active_interval: 120, // 活跃间隔(分钟)
|
||||
actions: ['view_jobs'], // 活跃动作
|
||||
time_range: null // 时间范围
|
||||
};
|
||||
|
||||
return this.parseConfig(activeStrategy, defaultConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取优先级权重配置
|
||||
* @param {object} config - 投递配置
|
||||
* @returns {object} 优先级权重
|
||||
*/
|
||||
static getPriorityWeights(config) {
|
||||
const defaultWeights = {
|
||||
salary: 0.4, // 薪资匹配度
|
||||
keyword: 0.3, // 关键词匹配度
|
||||
company: 0.2, // 公司活跃度
|
||||
distance: 0.1 // 距离(未来)
|
||||
};
|
||||
|
||||
if (!config.priority_weights) {
|
||||
return defaultWeights;
|
||||
}
|
||||
|
||||
return { ...defaultWeights, ...config.priority_weights };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取排除关键词列表
|
||||
* @param {object} config - 配置对象
|
||||
* @returns {string[]} 排除关键词数组
|
||||
*/
|
||||
static getExcludeKeywords(config) {
|
||||
if (!config.exclude_keywords) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(config.exclude_keywords)) {
|
||||
return config.exclude_keywords.filter(k => k && k.trim());
|
||||
}
|
||||
|
||||
if (typeof config.exclude_keywords === 'string') {
|
||||
return config.exclude_keywords
|
||||
.split(/[,,、]/)
|
||||
.map(k => k.trim())
|
||||
.filter(k => k);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过滤关键词列表
|
||||
* @param {object} config - 配置对象
|
||||
* @returns {string[]} 过滤关键词数组
|
||||
*/
|
||||
static getFilterKeywords(config) {
|
||||
if (!config.filter_keywords) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(config.filter_keywords)) {
|
||||
return config.filter_keywords.filter(k => k && k.trim());
|
||||
}
|
||||
|
||||
if (typeof config.filter_keywords === 'string') {
|
||||
return config.filter_keywords
|
||||
.split(/[,,、]/)
|
||||
.map(k => k.trim())
|
||||
.filter(k => k);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取薪资范围
|
||||
* @param {object} config - 配置对象
|
||||
* @returns {{min: number, max: number}} 薪资范围
|
||||
*/
|
||||
static getSalaryRange(config) {
|
||||
return {
|
||||
min: parseInt(config.min_salary) || 0,
|
||||
max: parseInt(config.max_salary) || 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时间范围
|
||||
* @param {object} config - 配置对象
|
||||
* @returns {object|null} 时间范围配置
|
||||
*/
|
||||
static getTimeRange(config) {
|
||||
return config.time_range || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证配置完整性
|
||||
* @param {object} config - 配置对象
|
||||
* @param {string[]} requiredFields - 必需字段
|
||||
* @returns {{valid: boolean, missing?: string[]}} 验证结果
|
||||
*/
|
||||
static validateConfig(config, requiredFields = []) {
|
||||
const missing = [];
|
||||
|
||||
for (const field of requiredFields) {
|
||||
if (config[field] === undefined || config[field] === null) {
|
||||
missing.push(field);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
return { valid: false, missing };
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并配置(用于覆盖默认配置)
|
||||
* @param {object} defaultConfig - 默认配置
|
||||
* @param {object} userConfig - 用户配置
|
||||
* @returns {object} 合并后的配置
|
||||
*/
|
||||
static mergeConfig(defaultConfig, userConfig) {
|
||||
return { ...defaultConfig, ...userConfig };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ConfigManager;
|
||||
395
api/middleware/schedule/services/jobFilterEngine.js
Normal file
395
api/middleware/schedule/services/jobFilterEngine.js
Normal file
@@ -0,0 +1,395 @@
|
||||
const SalaryParser = require('../utils/salaryParser');
|
||||
const KeywordMatcher = require('../utils/keywordMatcher');
|
||||
const db = require('../../dbProxy');
|
||||
|
||||
/**
|
||||
* 职位过滤引擎
|
||||
* 综合处理职位的过滤、评分和排序
|
||||
*/
|
||||
class JobFilterEngine {
|
||||
/**
|
||||
* 过滤职位列表
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {object} config - 过滤配置
|
||||
* @param {object} resumeInfo - 简历信息
|
||||
* @returns {Promise<Array>} 过滤后的职位列表
|
||||
*/
|
||||
async filterJobs(jobs, config, resumeInfo = {}) {
|
||||
if (!jobs || jobs.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let filtered = [...jobs];
|
||||
|
||||
// 1. 薪资过滤
|
||||
filtered = this.filterBySalary(filtered, config);
|
||||
|
||||
// 2. 关键词过滤
|
||||
filtered = this.filterByKeywords(filtered, config);
|
||||
|
||||
// 3. 公司活跃度过滤
|
||||
if (config.filter_inactive_companies) {
|
||||
filtered = await this.filterByCompanyActivity(filtered, config.company_active_days || 7);
|
||||
}
|
||||
|
||||
// 4. 去重(同一公司、同一职位名称)
|
||||
if (config.deduplicate) {
|
||||
filtered = this.deduplicateJobs(filtered);
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按薪资过滤
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {object} config - 配置
|
||||
* @returns {Array} 过滤后的职位
|
||||
*/
|
||||
filterBySalary(jobs, config) {
|
||||
const { min_salary = 0, max_salary = 0 } = config;
|
||||
|
||||
if (min_salary === 0 && max_salary === 0) {
|
||||
return jobs; // 无薪资限制
|
||||
}
|
||||
|
||||
return jobs.filter(job => {
|
||||
const jobSalary = SalaryParser.parse(job.salary || job.salaryDesc || '');
|
||||
return SalaryParser.isWithinRange(jobSalary, min_salary, max_salary);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按关键词过滤
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {object} config - 配置
|
||||
* @returns {Array} 过滤后的职位
|
||||
*/
|
||||
filterByKeywords(jobs, config) {
|
||||
const {
|
||||
exclude_keywords = [],
|
||||
filter_keywords = []
|
||||
} = config;
|
||||
|
||||
if (exclude_keywords.length === 0 && filter_keywords.length === 0) {
|
||||
return jobs;
|
||||
}
|
||||
|
||||
return KeywordMatcher.filterJobs(jobs, {
|
||||
excludeKeywords: exclude_keywords,
|
||||
filterKeywords: filter_keywords
|
||||
}, (job) => {
|
||||
// 组合职位名称、描述、技能要求等
|
||||
return [
|
||||
job.name || job.jobName || '',
|
||||
job.description || job.jobDescription || '',
|
||||
job.skills || '',
|
||||
job.welfare || ''
|
||||
].join(' ');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按公司活跃度过滤
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {number} activeDays - 活跃天数阈值
|
||||
* @returns {Promise<Array>} 过滤后的职位
|
||||
*/
|
||||
async filterByCompanyActivity(jobs, activeDays = 7) {
|
||||
try {
|
||||
const task_status = db.getModel('task_status');
|
||||
const thresholdDate = new Date(Date.now() - activeDays * 24 * 60 * 60 * 1000);
|
||||
|
||||
// 查询近期已投递的公司
|
||||
const recentCompanies = await task_status.findAll({
|
||||
where: {
|
||||
taskType: 'auto_deliver',
|
||||
status: 'completed',
|
||||
endTime: {
|
||||
[db.models.op.gte]: thresholdDate
|
||||
}
|
||||
},
|
||||
attributes: ['result'],
|
||||
raw: true
|
||||
});
|
||||
|
||||
// 提取公司名称
|
||||
const deliveredCompanies = new Set();
|
||||
for (const task of recentCompanies) {
|
||||
try {
|
||||
const result = JSON.parse(task.result || '{}');
|
||||
if (result.deliveredJobs) {
|
||||
result.deliveredJobs.forEach(job => {
|
||||
if (job.company) {
|
||||
deliveredCompanies.add(job.company.toLowerCase());
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略解析错误
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤掉近期已投递的公司
|
||||
return jobs.filter(job => {
|
||||
const company = (job.company || job.companyName || '').toLowerCase().trim();
|
||||
return !deliveredCompanies.has(company);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[职位过滤] 公司活跃度过滤失败:', error);
|
||||
return jobs; // 失败时返回原列表
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 去重职位
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @returns {Array} 去重后的职位
|
||||
*/
|
||||
deduplicateJobs(jobs) {
|
||||
const seen = new Set();
|
||||
const unique = [];
|
||||
|
||||
for (const job of jobs) {
|
||||
const company = (job.company || job.companyName || '').toLowerCase().trim();
|
||||
const jobName = (job.name || job.jobName || '').toLowerCase().trim();
|
||||
const key = `${company}||${jobName}`;
|
||||
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
unique.push(job);
|
||||
}
|
||||
}
|
||||
|
||||
return unique;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为职位打分
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {object} resumeInfo - 简历信息
|
||||
* @param {object} config - 配置(包含权重)
|
||||
* @returns {Array} 带分数的职位列表
|
||||
*/
|
||||
scoreJobs(jobs, resumeInfo = {}, config = {}) {
|
||||
const weights = config.priority_weights || {
|
||||
salary: 0.4,
|
||||
keyword: 0.3,
|
||||
company: 0.2,
|
||||
freshness: 0.1
|
||||
};
|
||||
|
||||
return jobs.map(job => {
|
||||
const scores = {
|
||||
salary: this.scoreSalary(job, resumeInfo),
|
||||
keyword: this.scoreKeywords(job, config),
|
||||
company: this.scoreCompany(job),
|
||||
freshness: this.scoreFreshness(job)
|
||||
};
|
||||
|
||||
// 加权总分
|
||||
const totalScore = (
|
||||
scores.salary * weights.salary +
|
||||
scores.keyword * weights.keyword +
|
||||
scores.company * weights.company +
|
||||
scores.freshness * weights.freshness
|
||||
);
|
||||
|
||||
return {
|
||||
...job,
|
||||
_scores: scores,
|
||||
_totalScore: totalScore
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 薪资匹配度评分 (0-100)
|
||||
* @param {object} job - 职位信息
|
||||
* @param {object} resumeInfo - 简历信息
|
||||
* @returns {number} 分数
|
||||
*/
|
||||
scoreSalary(job, resumeInfo) {
|
||||
const jobSalary = SalaryParser.parse(job.salary || job.salaryDesc || '');
|
||||
const expectedSalary = SalaryParser.parse(resumeInfo.expected_salary || '');
|
||||
|
||||
if (jobSalary.min === 0 || expectedSalary.min === 0) {
|
||||
return 50; // 无法判断时返回中性分
|
||||
}
|
||||
|
||||
const matchScore = SalaryParser.calculateMatch(jobSalary, expectedSalary);
|
||||
return matchScore * 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关键词匹配度评分 (0-100)
|
||||
* @param {object} job - 职位信息
|
||||
* @param {object} config - 配置
|
||||
* @returns {number} 分数
|
||||
*/
|
||||
scoreKeywords(job, config) {
|
||||
const bonusKeywords = config.filter_keywords || [];
|
||||
|
||||
if (bonusKeywords.length === 0) {
|
||||
return 50; // 无关键词时返回中性分
|
||||
}
|
||||
|
||||
const jobText = [
|
||||
job.name || job.jobName || '',
|
||||
job.description || job.jobDescription || '',
|
||||
job.skills || ''
|
||||
].join(' ');
|
||||
|
||||
const bonusResult = KeywordMatcher.calculateBonus(jobText, bonusKeywords, {
|
||||
baseScore: 10,
|
||||
maxBonus: 100
|
||||
});
|
||||
|
||||
return Math.min(bonusResult.score, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司评分 (0-100)
|
||||
* @param {object} job - 职位信息
|
||||
* @returns {number} 分数
|
||||
*/
|
||||
scoreCompany(job) {
|
||||
let score = 50; // 基础分
|
||||
|
||||
// 融资阶段加分
|
||||
const fundingStage = (job.financingStage || job.financing || '').toLowerCase();
|
||||
const fundingBonus = {
|
||||
'已上市': 30,
|
||||
'上市公司': 30,
|
||||
'd轮': 25,
|
||||
'c轮': 20,
|
||||
'b轮': 15,
|
||||
'a轮': 10,
|
||||
'天使轮': 5
|
||||
};
|
||||
|
||||
for (const [stage, bonus] of Object.entries(fundingBonus)) {
|
||||
if (fundingStage.includes(stage.toLowerCase())) {
|
||||
score += bonus;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 公司规模加分
|
||||
const scale = (job.scale || job.companyScale || '').toLowerCase();
|
||||
if (scale.includes('10000') || scale.includes('万人')) {
|
||||
score += 15;
|
||||
} else if (scale.includes('1000-9999') || scale.includes('千人')) {
|
||||
score += 10;
|
||||
} else if (scale.includes('500-999')) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
return Math.min(score, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新鲜度评分 (0-100)
|
||||
* @param {object} job - 职位信息
|
||||
* @returns {number} 分数
|
||||
*/
|
||||
scoreFreshness(job) {
|
||||
const publishTime = job.publishTime || job.createTime;
|
||||
|
||||
if (!publishTime) {
|
||||
return 50; // 无时间信息时返回中性分
|
||||
}
|
||||
|
||||
try {
|
||||
const now = Date.now();
|
||||
const pubTime = new Date(publishTime).getTime();
|
||||
const hoursAgo = (now - pubTime) / (1000 * 60 * 60);
|
||||
|
||||
// 越新鲜分数越高
|
||||
if (hoursAgo < 1) return 100;
|
||||
if (hoursAgo < 24) return 90;
|
||||
if (hoursAgo < 72) return 70;
|
||||
if (hoursAgo < 168) return 50; // 一周内
|
||||
return 30;
|
||||
|
||||
} catch (error) {
|
||||
return 50;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 排序职位
|
||||
* @param {Array} jobs - 职位列表(带分数)
|
||||
* @param {string} sortBy - 排序方式: score, salary, freshness
|
||||
* @returns {Array} 排序后的职位
|
||||
*/
|
||||
sortJobs(jobs, sortBy = 'score') {
|
||||
const sorted = [...jobs];
|
||||
|
||||
switch (sortBy) {
|
||||
case 'score':
|
||||
sorted.sort((a, b) => (b._totalScore || 0) - (a._totalScore || 0));
|
||||
break;
|
||||
|
||||
case 'salary':
|
||||
sorted.sort((a, b) => {
|
||||
const salaryA = SalaryParser.parse(a.salary || '');
|
||||
const salaryB = SalaryParser.parse(b.salary || '');
|
||||
return (salaryB.max || 0) - (salaryA.max || 0);
|
||||
});
|
||||
break;
|
||||
|
||||
case 'freshness':
|
||||
sorted.sort((a, b) => {
|
||||
const timeA = new Date(a.publishTime || a.createTime || 0).getTime();
|
||||
const timeB = new Date(b.publishTime || b.createTime || 0).getTime();
|
||||
return timeB - timeA;
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
// 默认按分数排序
|
||||
sorted.sort((a, b) => (b._totalScore || 0) - (a._totalScore || 0));
|
||||
}
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合处理:过滤 + 评分 + 排序
|
||||
* @param {Array} jobs - 职位列表
|
||||
* @param {object} config - 过滤配置
|
||||
* @param {object} resumeInfo - 简历信息
|
||||
* @param {object} options - 选项
|
||||
* @returns {Promise<Array>} 处理后的职位列表
|
||||
*/
|
||||
async process(jobs, config, resumeInfo = {}, options = {}) {
|
||||
const {
|
||||
maxCount = 10, // 最大返回数量
|
||||
sortBy = 'score' // 排序方式
|
||||
} = options;
|
||||
|
||||
// 1. 过滤
|
||||
let filtered = await this.filterJobs(jobs, config, resumeInfo);
|
||||
|
||||
console.log(`[职位过滤] 原始: ${jobs.length} 个,过滤后: ${filtered.length} 个`);
|
||||
|
||||
// 2. 评分
|
||||
const scored = this.scoreJobs(filtered, resumeInfo, config);
|
||||
|
||||
// 3. 排序
|
||||
const sorted = this.sortJobs(scored, sortBy);
|
||||
|
||||
// 4. 截取
|
||||
const result = sorted.slice(0, maxCount);
|
||||
|
||||
console.log(`[职位过滤] 最终返回: ${result.length} 个职位`);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例
|
||||
const jobFilterEngine = new JobFilterEngine();
|
||||
module.exports = jobFilterEngine;
|
||||
158
api/middleware/schedule/services/timeRangeValidator.js
Normal file
158
api/middleware/schedule/services/timeRangeValidator.js
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 时间范围验证器
|
||||
* 检查当前时间是否在指定的时间范围内(支持工作日限制)
|
||||
*/
|
||||
class TimeRangeValidator {
|
||||
/**
|
||||
* 检查当前时间是否在指定的时间范围内
|
||||
* @param {object} timeRange - 时间范围配置 {start_time: '09:00', end_time: '18:00', workdays_only: 1}
|
||||
* @returns {{allowed: boolean, reason: string}} 检查结果
|
||||
*/
|
||||
static checkTimeRange(timeRange) {
|
||||
if (!timeRange || !timeRange.start_time || !timeRange.end_time) {
|
||||
return { allowed: true, reason: '未配置时间范围' };
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const currentHour = now.getHours();
|
||||
const currentMinute = now.getMinutes();
|
||||
const currentTime = currentHour * 60 + currentMinute; // 转换为分钟数
|
||||
|
||||
// 解析开始时间和结束时间
|
||||
const [startHour, startMinute] = timeRange.start_time.split(':').map(Number);
|
||||
const [endHour, endMinute] = timeRange.end_time.split(':').map(Number);
|
||||
const startTime = startHour * 60 + startMinute;
|
||||
const endTime = endHour * 60 + endMinute;
|
||||
|
||||
// 检查是否仅工作日(使用宽松比较,兼容字符串和数字)
|
||||
if (timeRange.workdays_only == 1) {
|
||||
const dayOfWeek = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
|
||||
if (dayOfWeek === 0 || dayOfWeek === 6) {
|
||||
return { allowed: false, reason: '当前是周末,不在允许的时间范围内' };
|
||||
}
|
||||
}
|
||||
|
||||
// 检查当前时间是否在时间范围内
|
||||
if (startTime <= endTime) {
|
||||
// 正常情况:09:00 - 18:00
|
||||
if (currentTime < startTime || currentTime >= endTime) {
|
||||
const currentTimeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `当前时间 ${currentTimeStr} 不在允许的时间范围内 (${timeRange.start_time} - ${timeRange.end_time})`
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// 跨天情况:22:00 - 06:00
|
||||
if (currentTime < startTime && currentTime >= endTime) {
|
||||
const currentTimeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `当前时间 ${currentTimeStr} 不在允许的时间范围内 (${timeRange.start_time} - ${timeRange.end_time})`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { allowed: true, reason: '在允许的时间范围内' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否在工作时间内
|
||||
* @param {string} startTime - 开始时间 '09:00'
|
||||
* @param {string} endTime - 结束时间 '18:00'
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isWithinWorkingHours(startTime = '09:00', endTime = '18:00') {
|
||||
const result = this.checkTimeRange({
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
workdays_only: 0
|
||||
});
|
||||
return result.allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否是工作日
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isWorkingDay() {
|
||||
const dayOfWeek = new Date().getDay();
|
||||
return dayOfWeek !== 0 && dayOfWeek !== 6; // 非周六周日
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个可操作时间
|
||||
* @param {object} timeRange - 时间范围配置
|
||||
* @returns {Date|null} 下一个可操作时间,如果当前可操作则返回 null
|
||||
*/
|
||||
static getNextAvailableTime(timeRange) {
|
||||
const check = this.checkTimeRange(timeRange);
|
||||
if (check.allowed) {
|
||||
return null; // 当前可操作
|
||||
}
|
||||
|
||||
if (!timeRange || !timeRange.start_time) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const [startHour, startMinute] = timeRange.start_time.split(':').map(Number);
|
||||
|
||||
// 如果是工作日限制且当前是周末
|
||||
if (timeRange.workdays_only == 1) {
|
||||
const dayOfWeek = now.getDay();
|
||||
if (dayOfWeek === 0) {
|
||||
// 周日,下一个可操作时间是周一
|
||||
const nextTime = new Date(now);
|
||||
nextTime.setDate(now.getDate() + 1);
|
||||
nextTime.setHours(startHour, startMinute, 0, 0);
|
||||
return nextTime;
|
||||
} else if (dayOfWeek === 6) {
|
||||
// 周六,下一个可操作时间是下周一
|
||||
const nextTime = new Date(now);
|
||||
nextTime.setDate(now.getDate() + 2);
|
||||
nextTime.setHours(startHour, startMinute, 0, 0);
|
||||
return nextTime;
|
||||
}
|
||||
}
|
||||
|
||||
// 计算下一个开始时间
|
||||
const nextTime = new Date(now);
|
||||
nextTime.setHours(startHour, startMinute, 0, 0);
|
||||
|
||||
// 如果已经过了今天的开始时间,则设置为明天
|
||||
if (nextTime <= now) {
|
||||
nextTime.setDate(now.getDate() + 1);
|
||||
}
|
||||
|
||||
return nextTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化剩余时间
|
||||
* @param {object} timeRange - 时间范围配置
|
||||
* @returns {string} 剩余时间描述
|
||||
*/
|
||||
static formatRemainingTime(timeRange) {
|
||||
const nextTime = this.getNextAvailableTime(timeRange);
|
||||
if (!nextTime) {
|
||||
return '当前可操作';
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const diff = nextTime.getTime() - now;
|
||||
const hours = Math.floor(diff / (1000 * 60 * 60));
|
||||
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
|
||||
|
||||
if (hours > 24) {
|
||||
const days = Math.floor(hours / 24);
|
||||
return `需要等待 ${days} 天 ${hours % 24} 小时`;
|
||||
} else if (hours > 0) {
|
||||
return `需要等待 ${hours} 小时 ${minutes} 分钟`;
|
||||
} else {
|
||||
return `需要等待 ${minutes} 分钟`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TimeRangeValidator;
|
||||
Reference in New Issue
Block a user