首页 > 应用开发 > IT综合 > 实现特定格式编号自动生成
在生成诸如订单、合同等单据的时候,往往有生成特定格式编号的需求,下面介绍如何实现生成“特定前缀+年份+固定长度序号”的编号,其他类型可在此基础上进行调整。
在白码低代码开发平台上创建一个“编号表”数据表,添加两个字段:编号(字符),序号(数字)
1、创建“生编号”功能,添加“数据-获取-编号表”步骤(当前最新编号),点击步骤的“设置”按钮加载数据表属性。
2、加“数据-新增-编号表”步骤(新建数据),点击设置按钮,将编号、序号、日期属性隐藏,并把日期设为当前时间。
3、获取到相关id:
编号表id(entity):
编号表的编号属性id(field):
编号表的序号属性id(field):
编号表的日期属性id(field):
4、添加“编程”步骤,引用前面两个步骤的数据:
5、继续编写代码生成编号,完整代码如下:
async function runProcess($model = model, $plugin = plugin, $params) { let index = new Number($params.index || 0);//当前最新编号步骤的序号属性,转为数字,不存在时设为0 let date = $params.date;//当前最新编号步骤的日期属性 let inserted = $params.inserted;//新建数据步骤整个数据 let entity = "60936206dec57120cee73e2e";//编号表id let codeField = "6093620b6d8eaf20d45ed568";//编号表的编号属性id let indexField = "6093620f17f01720c753c60c";//编号表的序号属性id let size = 5;//格式序号长度 let max = Array(size + 1).join('9');//合法的最大编号值 //溢出 if (index + "" == max) { $plugin.data.removeData(entity, inserted);//删除新增的数据 $model.error(-1, "编号已达到允许的最大值!");//抛出错误提示 return; } //生成id let year = date.substr(0, 4);//当前系统最新数据的年份 let thisYear = new Date().getFullYear() + "";//今年 let isNewId = false; let id = ""; while (!isNewId) { id = await createId(index); //查询此工程编号是否存在,保证唯一性 let selected = await $plugin.data.queryData(entity, { [codeField]: id });//数据库查询 isNewId = selected.length == 0; } //将编号更新到新增数据 await $plugin.data.updateData(entity, inserted._id, { [codeField]: id,//编号 [indexField]: index,//序号 }); //生成id的方法 function createId(i) { index = i; if (year != thisYear) { //新的一年,重新从1开始 index = 1; year = thisYear; } else { //仍然是当年,继续编号 index++; } //组成id return "DD" + year + "-" + (Array(size).join('0') + index).slice(-size); } }
6、将功能发布上线。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69981626/viewspace-2771559/ ,如需转载,请注明出处,否则将追究法律责任。