exportStdInterfaceBase.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Zhong
  6. * @date 2019/6/20
  7. * @version
  8. */
  9. const XML_EXPORT_BASE = (() => {
  10. // 自检提示的开始记号,区分提示属于哪一部分的类型(eg: 招标、控制价),便于后续做提示的合并去重
  11. const HINT_START = '--start--';
  12. // 属性类型
  13. const TYPE = {
  14. DATE: 1, //日期类型YYYY-MM-DD
  15. DATE_TIME: 2, //日期类型YYY-MM-DDTHH:mm:ss
  16. INT: 3, //整数类型
  17. DECIMAL: 4, //数值类型,不限制小数位数
  18. NUM2: 5, //数值类型2:最多两位小数
  19. BOOL: 6 //布尔型
  20. };
  21. // 需要特殊处理的属性类型默认空值(当一个值为undefined、null的时候,默认给赋什么值)
  22. const DEFAULT_VALUE = {
  23. [TYPE.INT]: '0',
  24. [TYPE.DECIMAL]: '0',
  25. [TYPE.NUM2]: '0',
  26. [TYPE.BOOL]: 'false'
  27. };
  28. // 空白字符处理
  29. const WHITE_SPACE = {
  30. COLLAPSE: 1 //移除所有空白字符(换行、回车、空格以及制表符会被替换为空格,开头和结尾的空格会被移除,而多个连续的空格会被缩减为一个单一的空格)
  31. };
  32. // 计税方法
  33. const TAX_TYPE = {
  34. '1': '一般计税法',
  35. '2': '简易计税法',
  36. };
  37. // 承包人材料调整类型
  38. const ADJUST_TYPE = {
  39. info: 'priceInfo', // 造价信息差额调整法
  40. coe: 'priceCoe' // 价格指数调整法
  41. };
  42. // 加载数据间隔,减少服务器压力
  43. const TIMEOUT_TIME = 400;
  44. // 导出粒度
  45. const GRANULARITY = {
  46. PROJECT: 1, //导出建设项目
  47. ENGINEERING: 2, //导出单项工程
  48. TENDER: 3 //导出单位工程
  49. };
  50. // 导出的文件类型选项
  51. const EXPORT_KIND = {
  52. Tender: 1, //投标
  53. Bid: 2, //招标
  54. Control: 3 //控制价
  55. };
  56. // 配置项
  57. const CONFIG = Object.freeze({
  58. HINT_START,
  59. TYPE,
  60. WHITE_SPACE,
  61. TAX_TYPE,
  62. ADJUST_TYPE,
  63. TIMEOUT_TIME,
  64. GRANULARITY,
  65. EXPORT_KIND
  66. });
  67. // 缓存项 不需要的时候需要清空
  68. let _cache = {
  69. // 失败列表
  70. failList: [],
  71. // 项目数据(不包含详细数据,项目管理数据)
  72. projectData: {},
  73. // 当前导出类型,默认投标
  74. exportKind: EXPORT_KIND.Tender,
  75. // 记录拉取的单位工程项目详细数据,导出的时候,可能会导出多个文件,只有导出第一个文件的时候需要请求数据
  76. tenderDetailMap: {}
  77. };
  78. // 返回缓存项
  79. function getItem(key) {
  80. return _cache[key] || null;
  81. }
  82. // 设置缓存项
  83. function setItem(key, value) {
  84. // 与原数据是同类型的数据才可设置成功
  85. if (_cache[key] &&
  86. Object.prototype.toString.call(_cache[key]) ===
  87. Object.prototype.toString.call(value)) {
  88. _cache[key] = value;
  89. }
  90. }
  91. // 清空缓存项
  92. function clear() {
  93. _cache.failList = [];
  94. _cache.projectData = {};
  95. _cache.exportKind = EXPORT_KIND.Tender;
  96. _cache.tenderDetailMap = {};
  97. }
  98. const CACHE = Object.freeze({
  99. getItem,
  100. setItem,
  101. clear
  102. });
  103. /*
  104. * 定义不设置一个Node方法统一进入的原因:模板化比较直观,不分开定义节点的话,调用传参也很麻烦而且不直观。
  105. * 一个节点对应一个构造方法,方便调整配置、方便其他版本开发、接手的人看起来更直观
  106. * @param {String}name 节点名
  107. * {Array}attrs 节点属性数据
  108. * {Array}failList 失败列表
  109. * @return {void}
  110. * */
  111. function Element(name, attrs) {
  112. this.name = name;
  113. let checkData = check(name, attrs);
  114. this.fail = checkData.failHints;
  115. this.attrs = checkData.filterAttrs;
  116. handleXMLEntity(this.attrs);
  117. this.children = [];
  118. _cache.failList.push(...this.fail);
  119. }
  120. /*
  121. * xml字符实体的处理,这些特殊字符不处理会导致xml文件格式出错:""、<>、&
  122. * 要先处理&amp
  123. * */
  124. let _xmlEntity = {
  125. '&': '&amp;',
  126. '\n': '&#xA;',
  127. '"': '&quot;',
  128. '\'': '&apos;',
  129. '<': '&lt;',
  130. '>': '&gt;'
  131. };
  132. // 对每个元素的所有属性值进行特殊字符处理
  133. function handleXMLEntity(attrs) {
  134. for (let attr of attrs) {
  135. if (!attr.value) {
  136. continue;
  137. }
  138. for (let [key, value] of Object.entries(_xmlEntity)) {
  139. attr.value = attr.value.replace(new RegExp(key, 'g'), value);
  140. }
  141. }
  142. }
  143. // 获取处理实体字符后的数据
  144. function getParsedData(arr) {
  145. return arr.map(data => {
  146. for (let [key, value] of Object.entries(_xmlEntity)) {
  147. data = data.replace(new RegExp(key, 'g'), value);
  148. }
  149. return data;
  150. });
  151. }
  152. /*
  153. * 检查
  154. * 创建节点时检查节点的数据
  155. * 1.长度限制minLen,maxLen
  156. * 2.值的限制,固定范围:enumeration
  157. * @param {String}eleName 节点名称
  158. * {Array}datas 需要检查的属性数据
  159. * @return {Object} failHints没通过的属性提示 filterAttrs过滤后的属性数据(失败提示在属性是必须的时候才提示,如果该属性失败了,但是是非必要属性,那么该属性不显示)
  160. * */
  161. function check(eleName, datas) {
  162. let rst = { failHints: [], filterAttrs: [] };
  163. let dateReg = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
  164. for (let data of datas) {
  165. // 值统一转换成String
  166. data.value = !hasValue(data.value)
  167. ? DEFAULT_VALUE[data.type]
  168. ? DEFAULT_VALUE[data.type]
  169. : ''
  170. : String(data.value);
  171. if (data.whiteSpace && data.whiteSpace === WHITE_SPACE.COLLAPSE) { //处理空格相关
  172. data.value = data.value.replace(/[\r\n\t]/g, ' ');
  173. data.value = data.value.trim();
  174. data.value = data.value.replace(/\s{1,}/g, ' ');
  175. }
  176. let isFail = false;
  177. let tempFail = '';
  178. // 提示的名称需要处理,有的接口xml属性为英文,需要显示其展示名称
  179. const name = data.dName || data.name;
  180. if (data.minLen && data.value.length < data.minLen) {
  181. isFail = true;
  182. tempFail = data.failHint
  183. ? `${data.failHint}字符数不可小于${data.minLen}个。`
  184. : `${eleName}-“${data.name}”字符数不可小于${data.minLen}个。`;
  185. } else if (data.maxLen && data.value.length > data.maxLen) {
  186. isFail = true;
  187. tempFail = data.failHint
  188. ? `${data.failHint}字符数不可大于${data.maxLen}个。`
  189. : `${eleName}-“${data.name}”字符数不可大于${data.maxLen}个。`;
  190. } else if (data.enumeration && !data.enumeration.includes(data.value)) {
  191. isFail = true;
  192. let enumerationHint = data.enumerationHint
  193. ? data.enumerationHint.join(';')
  194. : data.enumeration.join(';');
  195. tempFail = data.failHint
  196. ? `${data.failHint}只能从“${enumerationHint}”中选择。`
  197. : `${eleName}-“${data.name}”只能从“${enumerationHint}”中选择。`;
  198. } else if (data.type && data.type === TYPE.DATE && !dateReg.test(data.value)) {
  199. isFail = true;
  200. tempFail = data.failHint
  201. ? `${data.failHint}日期格式必须是YYYY-MM-DD。`
  202. : `${eleName}-“${data.name}”日期格式必须是YYYY-MM-DD。`;
  203. } else if (data.type && data.type === TYPE.INT && !Number.isInteger(parseFloat(data.value))) {
  204. isFail = true;
  205. tempFail = data.failHint
  206. ? `${data.failHint}必须为整数。`
  207. : `${eleName}-“${data.name}”必须为整数。`;
  208. } else if (data.type && data.type === TYPE.DECIMAL && isNaN(parseFloat(data.value))) {
  209. isFail = true;
  210. tempFail = data.failHint
  211. ? `${data.failHint}必须为数值。`
  212. : `${eleName}-“${data.name}”必须为数值。`;
  213. } else if (data.type && data.type === TYPE.NUM2) {
  214. let v = parseFloat(data.value);
  215. if (isNaN(v)) {
  216. isFail = true;
  217. tempFail = data.failHint
  218. ? `${data.failHint}必须为数值。`
  219. : `${eleName}-“${data.name}”必须为数值。`;
  220. } else if (!data.value.length || (data.value.split('.').length > 1 && data.value.split('.')[1].length > 2)) {
  221. isFail = true;
  222. }
  223. } else if (data.type && data.type === TYPE.BOOL && !['true', 'false'].includes(String(data.value))) {
  224. isFail = true;
  225. tempFail = data.failHint
  226. ? `${data.failHint}必须为true或false。`
  227. : `${eleName}-“${data.name}”必须为true或false。`;
  228. }
  229. if (!isFail || data.required) {
  230. rst.filterAttrs.push(data);
  231. }
  232. if (isFail && data.required && tempFail) {
  233. rst.failHints.push(tempFail);
  234. }
  235. }
  236. return rst;
  237. }
  238. // 提取各导出类型的自检数据
  239. function _extractHintParts(failList) {
  240. let rst = [],
  241. curPart;
  242. for (let hint of failList) {
  243. if (hint === HINT_START) {
  244. curPart = [];
  245. rst.push(curPart);
  246. continue;
  247. }
  248. curPart.push(hint);
  249. }
  250. return rst;
  251. }
  252. // 自检提示去重
  253. function deWeightHints(failList) {
  254. let rst = [];
  255. let hintParts = _extractHintParts(failList);
  256. // 建设项目提示文本
  257. let rootHints = [],
  258. // 单位工程提示文本映射
  259. tenderMap = {},
  260. reg = /^<span style="font-weight: bold">单位工程/;
  261. for (let hintPart of hintParts) {
  262. // 单位工程xxx提示
  263. let curTenderHint;
  264. // 提取建设项目提示、各自单位工程提示
  265. for (let hint of hintPart) {
  266. if (reg.test(hint)) {
  267. curTenderHint = hint;
  268. if (!tenderMap[curTenderHint]) {
  269. tenderMap[curTenderHint] = [];
  270. }
  271. continue;
  272. }
  273. if (curTenderHint) {
  274. tenderMap[curTenderHint].push(hint);
  275. } else {
  276. rootHints.push(hint);
  277. }
  278. }
  279. }
  280. // 建设项目提示去重,放入结果中
  281. rootHints = [...new Set(rootHints)];
  282. rst.push(...rootHints);
  283. // 单位工程提示放入结果中
  284. for (let tenderHint in tenderMap) {
  285. rst.push(tenderHint);
  286. // 单位工程提示去重
  287. let tenderHints = [...new Set(tenderMap[tenderHint])];
  288. rst.push(...tenderHints);
  289. }
  290. return rst;
  291. }
  292. // 等待一段时间
  293. function setTimeoutSync(handle, time) {
  294. return new Promise((resolve, reject) => {
  295. setTimeout(() => {
  296. if (handle && typeof handle === 'function') {
  297. handle();
  298. }
  299. resolve();
  300. }, time);
  301. });
  302. }
  303. // v是否定义了,不为undefined和null
  304. function isDef(v) {
  305. return typeof v !== 'undefined' && v !== null;
  306. }
  307. function hasValue(v) {
  308. // v是否有值,不为undefined、null、''
  309. return typeof v !== 'undefined' && v !== null && v !== '';
  310. }
  311. /*
  312. * 将节点属性数据(attr数组)转换成简单key-value数据
  313. * @param {Object}ele 元素节点数据Element实例
  314. * @return {Object}
  315. * */
  316. function getPlainAttrs(ele) {
  317. const obj = {};
  318. ele.attrs.forEach(attr => obj[attr.name] = attr.value);
  319. return obj;
  320. }
  321. /*
  322. * 从fees数组中获取相关费用
  323. * @param {Array}fees 费用数组
  324. * {String}feeFields 费用字段
  325. * @return {Number}
  326. * @example getFee(source.fees, 'common.totalFee')
  327. * */
  328. function getFee(fees, feeFields) {
  329. if (!Array.isArray(fees)) {
  330. return 0;
  331. }
  332. let fields = feeFields.split('.');
  333. let fee = fees.find(data => data.fieldName === fields[0]);
  334. if (!fee) {
  335. return 0;
  336. }
  337. return fee[fields[1]] || 0;
  338. }
  339. // 获取节点的汇总价格
  340. function getAggregateFee(nodes) {
  341. let total = nodes.reduce((acc, node) => {
  342. const price = getFee(node.data.fees, 'common.totalFee');
  343. return acc += price;
  344. }, 0);
  345. return scMathUtil.roundTo(total, -2);
  346. }
  347. // 获取固定类别行的费用
  348. function getFeeByFlag(items, flag, feeFields) {
  349. const node = items.find(node => node.getFlag() === flag);
  350. return node ? getFee(node.data.fees, feeFields) : '0';
  351. }
  352. /*
  353. * 根据key获取对应的基本信息、工程特征数据
  354. * @param {Array}data
  355. * {String}key
  356. * @return {String}
  357. * @example getValueByKey(source.basicInformation, 'projectScale')
  358. * */
  359. function getValueByKey(data, key) {
  360. for (let d of data) {
  361. if (d.key === key) {
  362. return d.value;
  363. }
  364. if (d.items && d.items.length > 0) {
  365. let findData = d.items.find(x => x.key === key);
  366. if (findData) {
  367. return findData.value;
  368. }
  369. }
  370. }
  371. return '';
  372. }
  373. // 获取关联材料
  374. function getRelGLJ(allGLJs, gljId) {
  375. return allGLJs.find(glj => glj.id === gljId);
  376. }
  377. // 随机生成机器信息码:CPU信息;硬盘序列号;mac地址;
  378. // 保存在localStorage中
  379. function generateHardwareId() {
  380. const hardwareCacheId = window.localStorage.getItem('hardwareId');
  381. if (hardwareCacheId) {
  382. return hardwareCacheId;
  383. }
  384. const charList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  385. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  386. 'V', 'W', 'X', 'Y', 'Z'];
  387. function generateCpuId() {
  388. let id = '';
  389. let count = 16;
  390. while (count--) {
  391. const randomIdx = parseInt(Math.random() * 16);
  392. id += charList[randomIdx];
  393. }
  394. return id;
  395. }
  396. function generateDiskId() {
  397. let id = '';
  398. let count = 8;
  399. while (count--) {
  400. const randomIdx = parseInt(Math.random() * 36);
  401. id += charList[randomIdx];
  402. }
  403. return id;
  404. }
  405. function generateMacId() {
  406. const idList = [];
  407. let outerCount = 6;
  408. while (outerCount--) {
  409. let tempId = '';
  410. let innerCount = 2;
  411. while (innerCount--) {
  412. const randomIdx = parseInt(Math.random() * 16);
  413. tempId += charList[randomIdx];
  414. }
  415. idList.push(tempId);
  416. }
  417. return idList.join('-');
  418. }
  419. const cpuId = generateCpuId();
  420. const diskId = generateDiskId();
  421. const macId = generateMacId();
  422. const hardwareId = [cpuId, diskId, macId].join(';');
  423. window.localStorage.setItem('hardwareId', hardwareId);
  424. return hardwareId;
  425. }
  426. // 数组打平成对象
  427. function arrayToObj(arr) {
  428. let rst = {};
  429. for (let data of arr) {
  430. rst[data.key] = data.value;
  431. }
  432. return rst;
  433. }
  434. /*
  435. * 检测层数
  436. * @param {Number}maxDepth(最大深度)
  437. * {Object}node(需要检测的清单树节点)
  438. * @return {Boolean}
  439. * */
  440. function validDepth(maxDepth, node) {
  441. let nodeDepth = node.depth();
  442. let allNodes = node.getPosterity();
  443. //检测相对深度
  444. for (let n of allNodes) {
  445. let relativeDepth = n.depth() - nodeDepth;
  446. if (relativeDepth > maxDepth) {
  447. return false;
  448. }
  449. }
  450. return true;
  451. }
  452. /*
  453. * 检测唯一性,有些属性在规定的数据范围内唯一
  454. * @param {Object}constraints(约束池)
  455. * {All}data(检测的数据)
  456. * {String}hint(提示已存在的内容)
  457. * {String}subHint(额外提示,有额外提示时,不用data提示)
  458. * @return {void}
  459. * */
  460. function checkUnique(constraints, data, hint, subHint) {
  461. if (constraints.includes(data)) {
  462. let failHint = subHint
  463. ? `${hint}“${subHint}”已存在`
  464. : `${hint}“${data}”已存在`;
  465. _cache.failList.push(failHint);
  466. } else if (data) {
  467. constraints.push(data);
  468. }
  469. }
  470. //根据数据的NextSiblingID进行排序,返回排序后的数组
  471. function sortByNext(datas) {
  472. let target = [],
  473. temp = {};
  474. for (let data of datas) {
  475. temp[data.ID] = { me: data, next: null, prev: null };
  476. }
  477. for (let data of datas) {
  478. let next = temp[data.NextSiblingID] || null;
  479. temp[data.ID].next = next;
  480. if (next) {
  481. next.prev = temp[data.ID];
  482. }
  483. }
  484. let first = null;
  485. for (let data of datas) {
  486. let me = temp[data.ID];
  487. if (!me.prev) {
  488. first = me;
  489. }
  490. }
  491. if (!first) {
  492. return datas;
  493. }
  494. while (first) {
  495. target.push(first.me);
  496. first = first.next;
  497. }
  498. return target;
  499. }
  500. /*
  501. * 根据粒度获取项目(不包含详细数据)数据
  502. * @param {Number}granularity 导出粒度
  503. * {Object}summaryObj 汇总字段
  504. * {Number}tenderID 单位工程ID
  505. * {String}userID 用户ID
  506. * @return {Object} 返回的数据结构:{children: [{children: []}]} 最外层为建设项目,中间为单项工程,最底层为单位工程
  507. * */
  508. async function getProjectByGranularity(granularity, summaryObj, tenderID, userID) {
  509. let projectData = _cache.projectData;
  510. // 没有数据,需要拉取
  511. if (!Object.keys(projectData).length) {
  512. projectData = await ajaxPost('/pm/api/getProjectByGranularity', { user_id: userID, tenderID, granularity, summaryObj});
  513. _cache.projectData = projectData;
  514. }
  515. return projectData;
  516. }
  517. /*
  518. * 通过getData接口获取单位工程详细数据
  519. * @param {Number}tenderID 单位工程ID
  520. * {String}userID 用户ID
  521. * @return {Object} 跟projectObj.project的数据结构一致
  522. * */
  523. async function getTenderDetail(tenderID, userID) {
  524. // 获取单位工程详细数据
  525. let tenderDetail = _cache.tenderDetailMap[tenderID];
  526. if (!tenderDetail) {
  527. tenderDetail = PROJECT.createNew(tenderID, userID);
  528. await tenderDetail.loadDataSync();
  529. // 标记序号
  530. const count = Object.keys(_cache.tenderDetailMap).length;
  531. tenderDetail.serialNo = count + 1;
  532. _cache.tenderDetailMap[tenderID] = tenderDetail;
  533. }
  534. return tenderDetail;
  535. }
  536. /*
  537. * 提取要导出的数据
  538. * @param {Function}entryFunc 提取数据的入口方法
  539. * {Number}granularity 导出粒度: 1-建设项目、2-单项工程、3-单位工程
  540. * {Number}exportKind 导出的文件类型:1-投标、2-招标、3-控制价
  541. * {Number}tenderID 单位工程ID
  542. * {String}userID 用户ID
  543. * @return {Array} 数据结构为:[{data: Object, exportKind: Number, fileName: String}]
  544. * */
  545. async function extractExportData(entryFunc, granularity, summaryObj, exportKind, tenderID, userID) {
  546. // 默认导出建设项目
  547. if (!granularity || ![1, 2, 3].includes(granularity)) {
  548. granularity = GRANULARITY.PROJECT;
  549. }
  550. // 默认导出投标文件
  551. if (!exportKind || ![1, 2, 3].includes(exportKind)) {
  552. exportKind = EXPORT_KIND.Tender;
  553. }
  554. // 拉取标段数据:建设项目、单项工程、单位工程数据
  555. let projectData = await getProjectByGranularity(granularity, summaryObj, tenderID, userID);
  556. if (!projectData) {
  557. throw '获取项目数据错误';
  558. }
  559. // 单项工程、单位工程按照树结构数据进行排序
  560. projectData.children = sortByNext(projectData.children);
  561. for (let engData of projectData.children) {
  562. engData.children = sortByNext(engData.children);
  563. }
  564. // 提取相关项目的详细导出数据
  565. return await entryFunc(userID, exportKind, projectData);
  566. }
  567. //获取普通基数: {xxx}
  568. function getNormalBase(str) {
  569. let reg = /{.+?}/g,
  570. matchs = str.match(reg);
  571. return matchs || [];
  572. }
  573. //获取id引用基数: @xxx-xxx-xx
  574. function getIDBase(str) {
  575. let reg = /@.{36}/g,
  576. matchs = str.match(reg);
  577. return matchs || [];
  578. }
  579. // 转换基数表达式
  580. // 1.有子项,则取固定清单对应基数
  581. // 2.无子项,有基数,a.优先转换为行代号(不可自身) b.不能转换为行代号则找对应字典
  582. // 3.基数中有无法转换的,根据导出类型决定
  583. function transformCalcBase(exportKind, tenderDetail, node, { CalcBaseMap, FlagCalcBaseMap }) {
  584. let expr = node.data.calcBase || '';
  585. if (node.children.length) {
  586. let flag = node.getFlag();
  587. return FlagCalcBaseMap[flag] || '';
  588. }
  589. if (expr) {
  590. let illegal = false;
  591. let normalBase = getNormalBase(expr),
  592. idBase = getIDBase(expr);
  593. //普通基数转基数字典
  594. normalBase.forEach(base => {
  595. let replaceStr = CalcBaseMap[base];
  596. //转换成行代号的优先级比较高,进行清单匹配
  597. let flag = FlagCalcBaseMap[base];
  598. if (flag) {
  599. let flagNode = tenderDetail.mainTree.items.find(mNode => mNode.getFlag() === flag);
  600. //匹配到了 普通基数转换成行引用
  601. if (flagNode) {
  602. replaceStr = `F${flagNode.serialNo() + 1}`;
  603. }
  604. }
  605. //存在无法处理的基数
  606. if (!replaceStr) {
  607. illegal = true;
  608. return;
  609. }
  610. expr = expr.replace(new RegExp(base, 'g'), replaceStr);
  611. });
  612. //id引用转行代号引用
  613. idBase.forEach(base => {
  614. let id = base.match(/[^@]+/)[0];
  615. let theNode = tenderDetail.mainTree.getNodeByID(id),
  616. rowCode = theNode ? `F${theNode.serialNo() + 1}` : '';
  617. if (!rowCode) {
  618. illegal = true;
  619. return;
  620. }
  621. expr = expr.replace(new RegExp(base, 'g'), rowCode);
  622. });
  623. //不合法
  624. // 在我们软件中的基数无法找到映射代号的情况下
  625. // 导出招标、控制价时,基数为空
  626. // 导出投标时,基数=综合合价/费率
  627. if (illegal) {
  628. if (exportKind === EXPORT_KIND.Bid || exportKind === EXPORT_KIND.Control) {
  629. return '';
  630. } else {
  631. let totalFee = getFee(node.data.fees, 'common.totalFee'),
  632. feeRate = node.data.feeRate;
  633. return +feeRate ? scMathUtil.roundTo(totalFee / (feeRate / 100), -2) : totalFee
  634. }
  635. }
  636. return expr;
  637. }
  638. }
  639. // 转换基数说明,根据转换后的基数处理
  640. //1.行引用转换为对应行的名称
  641. //2.基数字典转换为中文
  642. function transformCalcBaseState(tenderDetail, expr, CalcStateMap) {
  643. if (!expr) {
  644. return '';
  645. }
  646. expr = String(expr);
  647. //提取基数
  648. let bases = expr.split(/[\+\-\*\/]/g);
  649. //提取操作符
  650. let oprs = expr.match(/[\+\-\*\/]/g);
  651. //转换后的基数
  652. let newBase = [];
  653. let illegal = false;
  654. for (let base of bases) {
  655. //行引用转换为名称.
  656. if (/F\d+/.test(base)) {
  657. let rowCode = base.match(/\d+/)[0],
  658. node = tenderDetail.mainTree.items[rowCode - 1];
  659. if (!node || !node.data.name) {
  660. illegal = true;
  661. break;
  662. }
  663. newBase.push(node && node.data.name ? node.data.name : '');
  664. } else if (CalcStateMap[base]) { //字典转换为中文
  665. newBase.push(CalcStateMap[base]);
  666. } else if (/^\d+(\.\d+)?$/.test(base)) { //金额
  667. newBase.push(base);
  668. } else {
  669. illegal = true;
  670. break;
  671. }
  672. }
  673. if (illegal) {
  674. return '';
  675. }
  676. let newExpr = '';
  677. for (let i = 0; i < newBase.length; i++) {
  678. newExpr += newBase[i];
  679. if (oprs && oprs[i]) {
  680. newExpr += oprs[i];
  681. }
  682. }
  683. return newExpr;
  684. }
  685. // 获取工程编号表格相关数据(导出需要弹出工程编号让用户选择)
  686. function getCodeSheetData(projectData) {
  687. let curCode = '0';
  688. let sheetData = [];
  689. sheetData.push(getObj(projectData));
  690. projectData.children.forEach(eng => {
  691. sheetData.push(getObj(eng));
  692. eng.children.forEach(tender => {
  693. sheetData.push(getObj(tender));
  694. });
  695. });
  696. //建设项目父ID设置为-1
  697. if (sheetData.length) {
  698. sheetData[0].ParentID = -1;
  699. sheetData[0].code = '';
  700. }
  701. return sheetData;
  702. function getObj(data) {
  703. return {
  704. collapsed: false,
  705. ID: data.ID,
  706. ParentID: data.ParentID,
  707. NextSiblingID: data.NextSiblingID,
  708. name: data.name,
  709. code: data.code || String(curCode++)
  710. };
  711. }
  712. }
  713. // 从srcEle节点中获取元素名为eleName的元素
  714. function getElementFromSrc(srcEle, eleName) {
  715. if (!srcEle || !srcEle.children || !srcEle.children.length) {
  716. return [];
  717. }
  718. return srcEle.children.filter(ele => ele.name === eleName);
  719. }
  720. /*
  721. * 设置完工程编号后,更新原始数据的工程编号
  722. * 更新原始数据前需要将编号里的特殊字符进行转换
  723. * @param {Array}exportData 提取出来的需要导出的数据
  724. * {Array}codes 工程编号表中填写的工程编号
  725. * {String}EngineeringName 单项工程元素的名称
  726. * {String}tenderName 单位工程元素的名称
  727. * {String}codeName 编号属性的名称
  728. * @return {void}
  729. * */
  730. function setupCode(exportData, codes, EngineeringName, tenderName, codeName) {
  731. // 转换xml实体字符
  732. let parsedCodes = getParsedData(codes);
  733. // 给导出数据里的单项工程、单位工程填上用户设置的工程编号
  734. exportData.forEach(orgData => {
  735. let curIdx = 0;
  736. let engs = getElementFromSrc(orgData.data, EngineeringName);
  737. engs.forEach(eng => {
  738. eng.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  739. let tenders = getElementFromSrc(eng, tenderName);
  740. tenders.forEach(tender => {
  741. tender.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  742. });
  743. });
  744. });
  745. }
  746. /**
  747. * 弱自检自检,有错误非强制不可导的自检
  748. * failList里存的是导出规定属性时,不符合标准规定的错误,存在这种错误就不允许导出
  749. * 这里的错误是业务上的提示错误,与标准文件规定无关,存在这种错误是允许导出的
  750. * @return {Array} - 提示信息数组
  751. */
  752. function softCheck() {
  753. const tenderDetailMap = _cache.tenderDetailMap;
  754. // 检查清单综合单价是否大于最高限价,大于则提示
  755. function checkMaxPrice(tenderDetail) {
  756. return tenderDetail.mainTree.items
  757. .filter(node => calcTools.unitFeeGTMaxPrice(node, 'common.unitFee'))
  758. .map(node => {
  759. const code = node.data.code || '';
  760. const name = node.data.name || '';
  761. return `第${node.serialNo()}行“${code + name}”,清单综合单价 > 最高限价`;
  762. });
  763. }
  764. const infos = [];
  765. // 按照获取顺序serialNo(根据树结构)排序
  766. Object.values(tenderDetailMap)
  767. .sort((a, b) => a.serialNo - b.serialNo)
  768. .forEach(tenderDetail => {
  769. const maxPriceInfos = checkMaxPrice(tenderDetail);
  770. if (!maxPriceInfos.length) {
  771. return;
  772. }
  773. infos.push(`<span style="font-weight: bold">单位工程“${tenderDetail.projectInfo.name}”下:</span>`);
  774. infos.push(...maxPriceInfos);
  775. });
  776. return infos;
  777. }
  778. const UTIL = Object.freeze({
  779. deWeightHints,
  780. isDef,
  781. hasValue,
  782. setTimeoutSync,
  783. getFee,
  784. getAggregateFee,
  785. getFeeByFlag,
  786. getPlainAttrs,
  787. getValueByKey,
  788. getRelGLJ,
  789. generateHardwareId,
  790. arrayToObj,
  791. validDepth,
  792. checkUnique,
  793. sortByNext,
  794. getTenderDetail,
  795. getProjectByGranularity,
  796. getNormalBase,
  797. getIDBase,
  798. transformCalcBase,
  799. transformCalcBaseState,
  800. getCodeSheetData,
  801. getElementFromSrc,
  802. getParsedData,
  803. setupCode,
  804. softCheck
  805. });
  806. // 开始标签
  807. function _startTag(ele) {
  808. let rst = `<${ele.name}`;
  809. for (let attr of ele.attrs) {
  810. rst += ` ${attr.name}="${attr.value}"`;
  811. }
  812. rst += ele.children.length > 0 ? '>' : '/>';
  813. return rst;
  814. }
  815. // 结束标签
  816. function _endTag(ele) {
  817. return `</${ele.name}>`;
  818. }
  819. // 拼接成xml字符串
  820. function _toXMLStr(eles) {
  821. let rst = '';
  822. for (let ele of eles) {
  823. rst += _startTag(ele);
  824. if (ele.children.length > 0) {
  825. rst += _toXMLStr(ele.children);
  826. rst += _endTag(ele);
  827. }
  828. }
  829. return rst;
  830. }
  831. //格式化xml字符串
  832. function _formatXml(text) {
  833. //去掉多余的空格
  834. text = '\n' + text.replace(/>\s*?</g, ">\n<");
  835. //调整格式
  836. let rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  837. let nodeStack = [];
  838. let output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
  839. let isClosed = (isCloseFull1 === '/') || (isCloseFull2 === '/') || (isFull1 === '/') || (isFull2 === '/');
  840. let prefix = '';
  841. if (isBegin === '!') {
  842. prefix = getPrefix(nodeStack.length);
  843. } else {
  844. if (isBegin !== '/') {
  845. prefix = getPrefix(nodeStack.length);
  846. if (!isClosed) {
  847. nodeStack.push(name);
  848. }
  849. } else {
  850. nodeStack.pop();
  851. prefix = getPrefix(nodeStack.length);
  852. }
  853. }
  854. let ret = '\n' + prefix + all;
  855. return ret;
  856. });
  857. let outputText = output.substring(1);
  858. return outputText;
  859. function getPrefix(prefixIndex) {
  860. let span = ' ';
  861. let output = [];
  862. for (let i = 0; i < prefixIndex; ++i) {
  863. output.push(span);
  864. }
  865. return output.join('');
  866. }
  867. }
  868. /*
  869. * 根据各自费用定额的文件结构,导出文件
  870. * 每个费用定额可能导出的结果文件都不同
  871. * 比如广东18需要将一个建设项目文件,多个单位工程文件打包成一个zip文件。重庆18就没这种要求
  872. * @param {Array}codes 工程编号数据
  873. * {Array}extractData 提取的数据
  874. * {Function}setCodeFunc 各自费用定额的导出前重设用户输入的工程编号方法
  875. * {Function}saveAsFunc 各自费用定额的导出方法
  876. * @return {void}
  877. * */
  878. async function exportFile(codes, extractData, setCodeFunc, saveAsFunc) {
  879. // 编号重置后将会被导出,需要将编号进行xml字符实体转换
  880. codes = getParsedData(codes);
  881. setCodeFunc(codes, extractData);
  882. // 获取文件数据
  883. let fileData = extractData.map(extractObj => {
  884. // 转换成xml字符串
  885. let xmlStr = _toXMLStr([extractObj.data]);
  886. // 加上xml声明
  887. xmlStr = `<?xml version="1.0" encoding="utf-8"?>${xmlStr}`;
  888. // 格式化
  889. xmlStr = _formatXml(xmlStr);
  890. let blob = new Blob([xmlStr], { type: 'text/plain;charset=utf-8' });
  891. return {
  892. blob: blob,
  893. exportKind: extractObj.exportKind,
  894. fileName: extractObj.fileName
  895. };
  896. });
  897. // 导出
  898. await saveAsFunc(fileData);
  899. }
  900. return {
  901. CONFIG,
  902. CACHE,
  903. UTIL,
  904. Element,
  905. extractExportData,
  906. exportFile
  907. };
  908. })();