contract_col_set.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Lan
  6. * @date 2025/11/24
  7. * @version
  8. */
  9. const ContractSetting = require('../const/contract');
  10. module.exports = app => {
  11. class ContractColSet extends app.BaseService {
  12. /**
  13. * 构造函数
  14. *
  15. * @param {Object} ctx - egg全局变量
  16. * @return {void}
  17. */
  18. constructor(ctx) {
  19. super(ctx);
  20. this.tableName = 'contract_col_set';
  21. }
  22. _analysisData(data) {
  23. if (!data) return;
  24. if(data['info']) data['info'] = JSON.parse(data['info']);
  25. }
  26. async loadContractColSet(spid, tid = null, type) {
  27. const result = await this.getDataByCondition({ spid, tid, type });
  28. this._analysisData(result);
  29. return result;
  30. }
  31. async initContractColSet(spid, tid = null, type) {
  32. const data = {
  33. spid,
  34. tid,
  35. type,
  36. info: JSON.stringify(ContractSetting.defaultColSet[type])
  37. }
  38. await this.db.insert(this.tableName, data);
  39. }
  40. async getContractColSet(spid, tid = null, type) {
  41. const curSet = await this.loadContractColSet(spid, tid, type);
  42. if (curSet) return curSet;
  43. await this.initContractColSet(spid, tid, type);
  44. return await this.loadContractColSet(spid, tid, type);
  45. }
  46. async setContractColSet(spid, tid = null, type, colSetType, colSet) {
  47. const data = {};
  48. data[colSetType] = JSON.stringify(colSet);
  49. await this.defaultUpdate(data, { where: { spid, tid, type } });
  50. }
  51. analysisColSetWithDefine(colSetDefine, colSet, defaultColSet) {
  52. const result = [];
  53. const colSetDefineMap = new Map(); // 用 Map 优化字段查找(O(1) 复杂度)
  54. const colSetFieldSet = new Set(); // 记录 colSet 中已存在的字段,避免重复
  55. colSetDefine.forEach(csd => {
  56. colSetDefineMap.set(csd.field, csd);
  57. });
  58. for (const cs of colSet) {
  59. const field = cs.field;
  60. const csd = colSetDefineMap.get(field); // 从字段定义中取 name、fixed
  61. const dcs = defaultColSet.find(x => x.field === field); // 取默认配置(兜底)
  62. if (csd) {
  63. // 合并:colSetDefine(name、fixed)> colSet(show、alias、顺序)> defaultColSet(兜底)
  64. result.push({ ...dcs, ...cs, ...csd });
  65. }
  66. colSetFieldSet.add(field); // 标记该字段已处理
  67. }
  68. // 按 colSetDefine 中未处理的顺序,补充到结果末尾
  69. for (const csd of colSetDefine) {
  70. const field = csd.field;
  71. if (!colSetFieldSet.has(field)) { // 未在 colSet 中找到的字段
  72. const dcs = defaultColSet.find(x => x.field === field); // 取默认配置
  73. result.push({ ...dcs, ...csd });
  74. }
  75. }
  76. return result;
  77. }
  78. }
  79. return ContractColSet;
  80. };