如何根据所选报告选项权重匹配返回对应TemplateId
报告结构存储与模板匹配实现方案
数据层级结构
数据库中存储的报告结构层级如下:
- 主键:
ReportId - 核心关联字段:
Report_Options:报告支持的配置选项集合,每个选项包含两个对应数组:Option_Value:选项的所有可选值Option_Weight:和可选值一一对应的整数权重
Templates:同一报告下的可用模板集合,每个模板对应一组合法的选项组合,包含:TemplateID:模板唯一标识TemplateOptionWeight:数组类型,存储该模板适配的所有选项组合的权重乘积
示例存储结构
对应JSON格式存储内容如下:
{ "ReportId": "RPTPIN001", "ReportDesc": "Monthly Sales report", "ReportCat":"Sales", "ReportOpt": [ { "Label": "Weekly Summary", "OptionType":"Boolean", "OptionValues":["Yes", "No"], "OptionWeight":[1,2] }, { "Label": "Comapre to", "OptionType":"dropdown", "OptionValues":["Prev Month", "Prev Qtr" , "Prev Year"], "OptionWeight":[3,4,5] } ], "Templates": [ { "TemplateId": "FTLPIN001", "TemplateData":"xxxxxxxxx", "TemplateOptionWeight":[3,4,5] }, { "TemplateId": "FTLPIN002", "TemplateData":"yyyyyyyy", "TemplateOptionWeight":[6,8,10] } ] }
匹配逻辑实现
权重乘积匹配逻辑可直接落地,只要保证所有选项的权重为互质数(推荐用质数赋值),就不会出现不同选项组合乘积重复的匹配错误,具体步骤如下:
- 解析用户提交的选项,逐个匹配对应权重
针对示例中的用户选择:- 选项
Weekly Summary=No:找到ReportOpt中Label为Weekly Summary的配置,定位OptionValues中No的索引为1,取同索引的权重值为2 - 选项
Compare To=Prev Year:找到ReportOpt中Label为Comapre to的配置(注意原数据存在拼写错误,匹配时需和存储值完全一致),定位OptionValues中Prev Year的索引为2,取同索引的权重值为5
- 选项
- 计算选中所有权重的乘积:
2 * 5 = 10 - 遍历当前
ReportId下的所有模板,找到TemplateOptionWeight数组包含值10的模板,返回对应的TemplateId即可,示例中匹配结果为FTLPIN002
逻辑实现参考代码
function getMatchedTemplate(report, userSelections) { // 收集选中项对应权重 const weights = userSelections.map(sel => { const opt = report.ReportOpt.find(item => item.Label === sel.label) const valIdx = opt.OptionValues.indexOf(sel.value) return opt.OptionWeight[valIdx] }) // 计算权重乘积 const product = weights.reduce((res, num) => res * num, 1) // 匹配对应模板 return report.Templates.find(tpl => tpl.TemplateOptionWeight.includes(product))?.TemplateId } // 调用示例 const userSelection = [ {label: "Weekly Summary", value: "No"}, {label: "Comapre to", value: "Prev Year"} ] // 传入示例report数据,返回值为FTLPIN002 console.log(getMatchedTemplate(reportData, userSelection))
注意:如果后续报告选项数量增加,要提前给每个选项的可选值分配足够大的互质权重,避免乘积数值溢出或出现乘积重复的冲突。
内容的提问来源于stack exchange,提问作者gudu
相关产品推荐
相关产品推荐

