exportStdInterfaceBase.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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. * 根据key获取对应的基本信息、工程特征数据
  341. * @param {Array}data
  342. * {String}key
  343. * @return {String}
  344. * @example getValueByKey(source.basicInformation, 'projectScale')
  345. * */
  346. function getValueByKey(data, key) {
  347. for (let d of data) {
  348. if (d.key === key) {
  349. return d.value;
  350. }
  351. if (d.items && d.items.length > 0) {
  352. let findData = d.items.find(x => x.key === key);
  353. if (findData) {
  354. return findData.value;
  355. }
  356. }
  357. }
  358. return '';
  359. }
  360. // 获取关联材料
  361. function getRelGLJ(allGLJs, gljId) {
  362. return allGLJs.find(glj => glj.id === gljId);
  363. }
  364. // 随机生成机器信息码:CPU信息;硬盘序列号;mac地址;
  365. // 保存在localStorage中
  366. function generateHardwareId() {
  367. const hardwareCacheId = window.localStorage.getItem('hardwareId');
  368. if (hardwareCacheId) {
  369. return hardwareCacheId;
  370. }
  371. const charList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  372. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  373. 'V', 'W', 'X', 'Y', 'Z'];
  374. function generateCpuId() {
  375. let id = '';
  376. let count = 16;
  377. while (count--) {
  378. const randomIdx = parseInt(Math.random() * 16);
  379. id += charList[randomIdx];
  380. }
  381. return id;
  382. }
  383. function generateDiskId() {
  384. let id = '';
  385. let count = 8;
  386. while (count--) {
  387. const randomIdx = parseInt(Math.random() * 36);
  388. id += charList[randomIdx];
  389. }
  390. return id;
  391. }
  392. function generateMacId() {
  393. const idList = [];
  394. let outerCount = 6;
  395. while (outerCount--) {
  396. let tempId = '';
  397. let innerCount = 2;
  398. while (innerCount--) {
  399. const randomIdx = parseInt(Math.random() * 16);
  400. tempId += charList[randomIdx];
  401. }
  402. idList.push(tempId);
  403. }
  404. return idList.join('-');
  405. }
  406. const cpuId = generateCpuId();
  407. const diskId = generateDiskId();
  408. const macId = generateMacId();
  409. const hardwareId = [cpuId, diskId, macId].join(';');
  410. window.localStorage.setItem('hardwareId', hardwareId);
  411. return hardwareId;
  412. }
  413. // 数组打平成对象
  414. function arrayToObj(arr) {
  415. let rst = {};
  416. for (let data of arr) {
  417. rst[data.key] = data.value;
  418. }
  419. return rst;
  420. }
  421. /*
  422. * 检测层数
  423. * @param {Number}maxDepth(最大深度)
  424. * {Object}node(需要检测的清单树节点)
  425. * @return {Boolean}
  426. * */
  427. function validDepth(maxDepth, node) {
  428. let nodeDepth = node.depth();
  429. let allNodes = node.getPosterity();
  430. //检测相对深度
  431. for (let n of allNodes) {
  432. let relativeDepth = n.depth() - nodeDepth;
  433. if (relativeDepth > maxDepth) {
  434. return false;
  435. }
  436. }
  437. return true;
  438. }
  439. /*
  440. * 检测唯一性,有些属性在规定的数据范围内唯一
  441. * @param {Object}constraints(约束池)
  442. * {All}data(检测的数据)
  443. * {String}hint(提示已存在的内容)
  444. * {String}subHint(额外提示,有额外提示时,不用data提示)
  445. * @return {void}
  446. * */
  447. function checkUnique(constraints, data, hint, subHint) {
  448. if (constraints.includes(data)) {
  449. let failHint = subHint
  450. ? `${hint}“${subHint}”已存在`
  451. : `${hint}“${data}”已存在`;
  452. _cache.failList.push(failHint);
  453. } else if (data) {
  454. constraints.push(data);
  455. }
  456. }
  457. //根据数据的NextSiblingID进行排序,返回排序后的数组
  458. function sortByNext(datas) {
  459. let target = [],
  460. temp = {};
  461. for (let data of datas) {
  462. temp[data.ID] = { me: data, next: null, prev: null };
  463. }
  464. for (let data of datas) {
  465. let next = temp[data.NextSiblingID] || null;
  466. temp[data.ID].next = next;
  467. if (next) {
  468. next.prev = temp[data.ID];
  469. }
  470. }
  471. let first = null;
  472. for (let data of datas) {
  473. let me = temp[data.ID];
  474. if (!me.prev) {
  475. first = me;
  476. }
  477. }
  478. if (!first) {
  479. return datas;
  480. }
  481. while (first) {
  482. target.push(first.me);
  483. first = first.next;
  484. }
  485. return target;
  486. }
  487. /*
  488. * 根据粒度获取项目(不包含详细数据)数据
  489. * @param {Number}granularity 导出粒度
  490. * {Number}tenderID 单位工程ID
  491. * {String}userID 用户ID
  492. * @return {Object} 返回的数据结构:{children: [{children: []}]} 最外层为建设项目,中间为单项工程,最底层为单位工程
  493. * */
  494. async function getProjectByGranularity(granularity, tenderID, userID) {
  495. let projectData = _cache.projectData;
  496. // 没有数据,需要拉取
  497. if (!Object.keys(projectData).length) {
  498. projectData = await ajaxPost('/pm/api/getProjectByGranularity', { user_id: userID, tenderID: tenderID, granularity: granularity });
  499. _cache.projectData = projectData;
  500. }
  501. return projectData;
  502. }
  503. /*
  504. * 通过getData接口获取单位工程详细数据
  505. * @param {Number}tenderID 单位工程ID
  506. * {String}userID 用户ID
  507. * @return {Object} 跟projectObj.project的数据结构一致
  508. * */
  509. async function getTenderDetail(tenderID, userID) {
  510. // 获取单位工程详细数据
  511. let tenderDetail = _cache.tenderDetailMap[tenderID];
  512. if (!tenderDetail) {
  513. tenderDetail = PROJECT.createNew(tenderID, userID);
  514. await tenderDetail.loadDataSync();
  515. // 标记序号
  516. const count = Object.keys(_cache.tenderDetailMap).length;
  517. tenderDetail.serialNo = count + 1;
  518. _cache.tenderDetailMap[tenderID] = tenderDetail;
  519. }
  520. return tenderDetail;
  521. }
  522. /*
  523. * 提取要导出的数据
  524. * @param {Function}entryFunc 提取数据的入口方法
  525. * {Number}granularity 导出粒度: 1-建设项目、2-单项工程、3-单位工程
  526. * {Number}exportKind 导出的文件类型:1-投标、2-招标、3-控制价
  527. * {Number}tenderID 单位工程ID
  528. * {String}userID 用户ID
  529. * @return {Array} 数据结构为:[{data: Object, exportKind: Number, fileName: String}]
  530. * */
  531. async function extractExportData(entryFunc, granularity, exportKind, tenderID, userID) {
  532. // 默认导出建设项目
  533. if (!granularity || ![1, 2, 3].includes(granularity)) {
  534. granularity = GRANULARITY.PROJECT;
  535. }
  536. // 默认导出投标文件
  537. if (!exportKind || ![1, 2, 3].includes(exportKind)) {
  538. exportKind = EXPORT_KIND.Tender;
  539. }
  540. // 拉取标段数据:建设项目、单项工程、单位工程数据
  541. let projectData = await getProjectByGranularity(granularity, tenderID, userID);
  542. if (!projectData) {
  543. throw '获取项目数据错误';
  544. }
  545. // 单项工程、单位工程按照树结构数据进行排序
  546. projectData.children = sortByNext(projectData.children);
  547. for (let engData of projectData.children) {
  548. engData.children = sortByNext(engData.children);
  549. }
  550. // 提取相关项目的详细导出数据
  551. return await entryFunc(userID, exportKind, projectData);
  552. }
  553. // 转换基数表达式
  554. // 1.有子项,则取固定清单对应基数
  555. // 2.无子项,有基数,a.优先转换为行代号(不可自身) b.不能转换为行代号则找对应字典
  556. // 3.基数中有无法转换的,根据导出类型决定
  557. function transformCalcBase(exportKind, tenderDetail, node, { CalcBaseMap, FlagCalcBaseMap }) {
  558. let expr = node.data.calcBase || '';
  559. if (node.children.length) {
  560. let flag = node.getFlag();
  561. return FlagCalcBaseMap[flag] || '';
  562. }
  563. if (expr) {
  564. let illegal = false;
  565. let normalBase = _getNormalBase(expr),
  566. idBase = _getIDBase(expr);
  567. //普通基数转基数字典
  568. normalBase.forEach(base => {
  569. let replaceStr = CalcBaseMap[base];
  570. //转换成行代号的优先级比较高,进行清单匹配
  571. let flag = FlagCalcBaseMap[base];
  572. if (flag) {
  573. let flagNode = tenderDetail.mainTree.items.find(mNode => mNode.getFlag() === flag);
  574. //匹配到了 普通基数转换成行引用
  575. if (flagNode) {
  576. replaceStr = `F${flagNode.serialNo() + 1}`;
  577. }
  578. }
  579. //存在无法处理的基数
  580. if (!replaceStr) {
  581. illegal = true;
  582. return;
  583. }
  584. expr = expr.replace(new RegExp(base, 'g'), replaceStr);
  585. });
  586. //id引用转行代号引用
  587. idBase.forEach(base => {
  588. let id = base.match(/[^@]+/)[0];
  589. let theNode = tenderDetail.mainTree.getNodeByID(id),
  590. rowCode = theNode ? `F${theNode.serialNo() + 1}` : '';
  591. if (!rowCode) {
  592. illegal = true;
  593. return;
  594. }
  595. expr = expr.replace(new RegExp(base, 'g'), rowCode);
  596. });
  597. //不合法
  598. // 在我们软件中的基数无法找到映射代号的情况下
  599. // 导出招标、控制价时,基数为空
  600. // 导出投标时,基数=综合合价/费率
  601. if (illegal) {
  602. if (exportKind === EXPORT_KIND.Bid || exportKind === EXPORT_KIND.Control) {
  603. return '';
  604. } else {
  605. let totalFee = getFee(node.data.fees, 'common.totalFee'),
  606. feeRate = node.data.feeRate;
  607. return +feeRate ? scMathUtil.roundTo(totalFee / (feeRate / 100), -2) : totalFee
  608. }
  609. }
  610. return expr;
  611. }
  612. //获取普通基数: {xxx}
  613. function _getNormalBase(str) {
  614. let reg = /{.+?}/g,
  615. matchs = str.match(reg);
  616. return matchs || [];
  617. }
  618. //获取id引用基数: @xxx-xxx-xx
  619. function _getIDBase(str) {
  620. let reg = /@.{36}/g,
  621. matchs = str.match(reg);
  622. return matchs || [];
  623. }
  624. }
  625. // 转换基数说明,根据转换后的基数处理
  626. //1.行引用转换为对应行的名称
  627. //2.基数字典转换为中文
  628. function transformCalcBaseState(tenderDetail, expr, CalcStateMap) {
  629. if (!expr) {
  630. return '';
  631. }
  632. expr = String(expr);
  633. //提取基数
  634. let bases = expr.split(/[\+\-\*\/]/g);
  635. //提取操作符
  636. let oprs = expr.match(/[\+\-\*\/]/g);
  637. //转换后的基数
  638. let newBase = [];
  639. let illegal = false;
  640. for (let base of bases) {
  641. //行引用转换为名称.
  642. if (/F\d+/.test(base)) {
  643. let rowCode = base.match(/\d+/)[0],
  644. node = tenderDetail.mainTree.items[rowCode - 1];
  645. if (!node || !node.data.name) {
  646. illegal = true;
  647. break;
  648. }
  649. newBase.push(node && node.data.name ? node.data.name : '');
  650. } else if (CalcStateMap[base]) { //字典转换为中文
  651. newBase.push(CalcStateMap[base]);
  652. } else if (/^\d+(\.\d+)?$/.test(base)) { //金额
  653. newBase.push(base);
  654. } else {
  655. illegal = true;
  656. break;
  657. }
  658. }
  659. if (illegal) {
  660. return '';
  661. }
  662. let newExpr = '';
  663. for (let i = 0; i < newBase.length; i++) {
  664. newExpr += newBase[i];
  665. if (oprs && oprs[i]) {
  666. newExpr += oprs[i];
  667. }
  668. }
  669. return newExpr;
  670. }
  671. // 获取工程编号表格相关数据(导出需要弹出工程编号让用户选择)
  672. function getCodeSheetData(projectData) {
  673. let curCode = '0';
  674. let sheetData = [];
  675. sheetData.push(getObj(projectData));
  676. projectData.children.forEach(eng => {
  677. sheetData.push(getObj(eng));
  678. eng.children.forEach(tender => {
  679. sheetData.push(getObj(tender));
  680. });
  681. });
  682. //建设项目父ID设置为-1
  683. if (sheetData.length) {
  684. sheetData[0].ParentID = -1;
  685. sheetData[0].code = '';
  686. }
  687. return sheetData;
  688. function getObj(data) {
  689. return {
  690. collapsed: false,
  691. ID: data.ID,
  692. ParentID: data.ParentID,
  693. NextSiblingID: data.NextSiblingID,
  694. name: data.name,
  695. code: data.code || String(curCode++)
  696. };
  697. }
  698. }
  699. // 从srcEle节点中获取元素名为eleName的元素
  700. function getElementFromSrc(srcEle, eleName) {
  701. if (!srcEle || !srcEle.children || !srcEle.children.length) {
  702. return [];
  703. }
  704. return srcEle.children.filter(ele => ele.name === eleName);
  705. }
  706. /*
  707. * 设置完工程编号后,更新原始数据的工程编号
  708. * 更新原始数据前需要将编号里的特殊字符进行转换
  709. * @param {Array}exportData 提取出来的需要导出的数据
  710. * {Array}codes 工程编号表中填写的工程编号
  711. * {String}EngineeringName 单项工程元素的名称
  712. * {String}tenderName 单位工程元素的名称
  713. * {String}codeName 编号属性的名称
  714. * @return {void}
  715. * */
  716. function setupCode(exportData, codes, EngineeringName, tenderName, codeName) {
  717. // 转换xml实体字符
  718. let parsedCodes = getParsedData(codes);
  719. // 给导出数据里的单项工程、单位工程填上用户设置的工程编号
  720. exportData.forEach(orgData => {
  721. let curIdx = 0;
  722. let engs = getElementFromSrc(orgData.data, EngineeringName);
  723. engs.forEach(eng => {
  724. eng.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  725. let tenders = getElementFromSrc(eng, tenderName);
  726. tenders.forEach(tender => {
  727. tender.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  728. });
  729. });
  730. });
  731. }
  732. /**
  733. * 弱自检自检,有错误非强制不可导的自检
  734. * failList里存的是导出规定属性时,不符合标准规定的错误,存在这种错误就不允许导出
  735. * 这里的错误是业务上的提示错误,与标准文件规定无关,存在这种错误是允许导出的
  736. * @return {Array} - 提示信息数组
  737. */
  738. function softCheck() {
  739. const tenderDetailMap = _cache.tenderDetailMap;
  740. // 检查清单综合单价是否大于最高限价,大于则提示
  741. function checkMaxPrice(tenderDetail) {
  742. return tenderDetail.mainTree.items
  743. .filter(node => calcTools.unitFeeGTMaxPrice(node, 'common.unitFee'))
  744. .map(node => {
  745. const code = node.data.code || '';
  746. const name = node.data.name || '';
  747. return `第${node.serialNo()}行“${code + name}”,清单综合单价 > 最高限价`;
  748. });
  749. }
  750. const infos = [];
  751. // 按照获取顺序serialNo(根据树结构)排序
  752. Object.values(tenderDetailMap)
  753. .sort((a, b) => a.serialNo - b.serialNo)
  754. .forEach(tenderDetail => {
  755. const maxPriceInfos = checkMaxPrice(tenderDetail);
  756. if (!maxPriceInfos.length) {
  757. return;
  758. }
  759. infos.push(`<span style="font-weight: bold">单位工程“${tenderDetail.projectInfo.name}”下:</span>`);
  760. infos.push(...maxPriceInfos);
  761. });
  762. return infos;
  763. }
  764. const UTIL = Object.freeze({
  765. deWeightHints,
  766. isDef,
  767. hasValue,
  768. setTimeoutSync,
  769. getFee,
  770. getPlainAttrs,
  771. getValueByKey,
  772. getRelGLJ,
  773. generateHardwareId,
  774. arrayToObj,
  775. validDepth,
  776. checkUnique,
  777. sortByNext,
  778. getTenderDetail,
  779. getProjectByGranularity,
  780. transformCalcBase,
  781. transformCalcBaseState,
  782. getCodeSheetData,
  783. getElementFromSrc,
  784. getParsedData,
  785. setupCode,
  786. softCheck
  787. });
  788. // 开始标签
  789. function _startTag(ele) {
  790. let rst = `<${ele.name}`;
  791. for (let attr of ele.attrs) {
  792. rst += ` ${attr.name}="${attr.value}"`;
  793. }
  794. rst += ele.children.length > 0 ? '>' : '/>';
  795. return rst;
  796. }
  797. // 结束标签
  798. function _endTag(ele) {
  799. return `</${ele.name}>`;
  800. }
  801. // 拼接成xml字符串
  802. function _toXMLStr(eles) {
  803. let rst = '';
  804. for (let ele of eles) {
  805. rst += _startTag(ele);
  806. if (ele.children.length > 0) {
  807. rst += _toXMLStr(ele.children);
  808. rst += _endTag(ele);
  809. }
  810. }
  811. return rst;
  812. }
  813. //格式化xml字符串
  814. function _formatXml(text) {
  815. //去掉多余的空格
  816. text = '\n' + text.replace(/>\s*?</g, ">\n<");
  817. //调整格式
  818. let rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  819. let nodeStack = [];
  820. let output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
  821. let isClosed = (isCloseFull1 === '/') || (isCloseFull2 === '/') || (isFull1 === '/') || (isFull2 === '/');
  822. let prefix = '';
  823. if (isBegin === '!') {
  824. prefix = getPrefix(nodeStack.length);
  825. } else {
  826. if (isBegin !== '/') {
  827. prefix = getPrefix(nodeStack.length);
  828. if (!isClosed) {
  829. nodeStack.push(name);
  830. }
  831. } else {
  832. nodeStack.pop();
  833. prefix = getPrefix(nodeStack.length);
  834. }
  835. }
  836. let ret = '\n' + prefix + all;
  837. return ret;
  838. });
  839. let outputText = output.substring(1);
  840. return outputText;
  841. function getPrefix(prefixIndex) {
  842. let span = ' ';
  843. let output = [];
  844. for (let i = 0; i < prefixIndex; ++i) {
  845. output.push(span);
  846. }
  847. return output.join('');
  848. }
  849. }
  850. /*
  851. * 根据各自费用定额的文件结构,导出文件
  852. * 每个费用定额可能导出的结果文件都不同
  853. * 比如广东18需要将一个建设项目文件,多个单位工程文件打包成一个zip文件。重庆18就没这种要求
  854. * @param {Array}codes 工程编号数据
  855. * {Array}extractData 提取的数据
  856. * {Function}setCodeFunc 各自费用定额的导出前重设用户输入的工程编号方法
  857. * {Function}saveAsFunc 各自费用定额的导出方法
  858. * @return {void}
  859. * */
  860. async function exportFile(codes, extractData, setCodeFunc, saveAsFunc) {
  861. // 编号重置后将会被导出,需要将编号进行xml字符实体转换
  862. codes = getParsedData(codes);
  863. setCodeFunc(codes, extractData);
  864. // 获取文件数据
  865. let fileData = extractData.map(extractObj => {
  866. // 转换成xml字符串
  867. let xmlStr = _toXMLStr([extractObj.data]);
  868. // 加上xml声明
  869. xmlStr = `<?xml version="1.0" encoding="utf-8"?>${xmlStr}`;
  870. // 格式化
  871. xmlStr = _formatXml(xmlStr);
  872. let blob = new Blob([xmlStr], { type: 'text/plain;charset=utf-8' });
  873. return {
  874. blob: blob,
  875. exportKind: extractObj.exportKind,
  876. fileName: extractObj.fileName
  877. };
  878. });
  879. // 导出
  880. await saveAsFunc(fileData);
  881. }
  882. return {
  883. CONFIG,
  884. CACHE,
  885. UTIL,
  886. Element,
  887. extractExportData,
  888. exportFile
  889. };
  890. })();