base.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /**
  2. * @author Zhong
  3. * @date 2019/6/20
  4. * @version
  5. */
  6. const INTERFACE_EXPORT_BASE = (() => {
  7. 'use strict';
  8. const {
  9. hasValue,
  10. isHan
  11. } = window.commonUtil;
  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 ADJUST_TYPE = {
  34. info: 'priceInfo', // 造价信息差额调整法
  35. coe: 'priceCoe' // 价格指数调整法
  36. };
  37. // 加载数据间隔,减少服务器压力
  38. const TIMEOUT_TIME = 400;
  39. const {
  40. GRANULARITY,
  41. EXPORT_KIND
  42. } = window.commonConstants;
  43. /* const EXPORT_KIND_NAME = {
  44. 1: '招标',
  45. 2: '投标',
  46. 3: '控制价'
  47. }; */
  48. // 配置项
  49. const CONFIG = Object.freeze({
  50. TYPE,
  51. WHITE_SPACE,
  52. ADJUST_TYPE,
  53. TIMEOUT_TIME,
  54. });
  55. // 缓存项 不需要的时候需要清空
  56. const _cache = {
  57. // 项目数据(不包含详细数据,项目管理数据)
  58. projectData: {},
  59. // 当前导出类型,默认投标
  60. exportKind: EXPORT_KIND.BID_SUBMISSION,
  61. // 记录拉取的单位工程项目详细数据,导出的时候,可能会导出多个文件,只有导出第一个文件的时候需要请求数据
  62. tenderDetailMap: {}
  63. };
  64. // 返回缓存项
  65. function getItem(key) {
  66. return _cache[key] || null;
  67. }
  68. // 设置缓存项
  69. function setItem(key, value) {
  70. // 与原数据是同类型的数据才可设置成功
  71. if (_cache[key] &&
  72. Object.prototype.toString.call(_cache[key]) ===
  73. Object.prototype.toString.call(value)) {
  74. _cache[key] = value;
  75. }
  76. }
  77. // 清空缓存项
  78. function clear() {
  79. _cache.projectData = {};
  80. _cache.exportKind = EXPORT_KIND.BID_SUBMISSION;
  81. _cache.tenderDetailMap = {};
  82. }
  83. const CACHE = Object.freeze({
  84. getItem,
  85. setItem,
  86. clear
  87. });
  88. /*
  89. * 定义不设置一个Node方法统一进入的原因:模板化比较直观,不分开定义节点的话,调用传参也很麻烦而且不直观。
  90. * 一个节点对应一个构造方法,方便调整配置、方便其他版本开发、接手的人看起来更直观
  91. * @param {String}name 节点名
  92. * {Array}attrs 节点属性数据
  93. * @return {void}
  94. * */
  95. function Element(name, attrs = []) {
  96. this.name = name;
  97. this.attrs = attrs;
  98. check(this.attrs);
  99. handleXMLEntity(this.attrs);
  100. this.children = [];
  101. }
  102. /*
  103. * xml字符实体的处理,这些特殊字符不处理会导致xml文件格式出错:""、<>、&
  104. * 要先处理&amp
  105. * */
  106. const _xmlEntity = {
  107. '&': '&amp;',
  108. '\n': '&#xA;',
  109. '"': '&quot;',
  110. '\'': '&apos;',
  111. '<': '&lt;',
  112. '>': '&gt;'
  113. };
  114. // 对每个元素的所有属性值进行特殊字符处理
  115. function handleXMLEntity(attrs) {
  116. for (const attr of attrs) {
  117. if (!attr.value) {
  118. continue;
  119. }
  120. for (const [key, value] of Object.entries(_xmlEntity)) {
  121. attr.value = attr.value.replace(new RegExp(key, 'g'), value);
  122. }
  123. }
  124. }
  125. // 获取处理实体字符后的数据
  126. function getParsedData(arr) {
  127. return arr.map(data => {
  128. for (const [key, value] of Object.entries(_xmlEntity)) {
  129. data = data.replace(new RegExp(key, 'g'), value);
  130. }
  131. return data;
  132. });
  133. }
  134. // 获取Date类型默认值
  135. function getDateTypeDefaultValue(date) {
  136. const month = String(date.getMonth() + 1);
  137. const formattedMonth = month.length === 1 ? `0${month}` : month;
  138. const day = String(date.getDate());
  139. const formattedDay = day.length === 1 ? `0${day}` : day;
  140. return `${date.getFullYear()}-${formattedMonth}-${formattedDay}`;
  141. }
  142. /*
  143. * 检查
  144. * 创建节点时检查节点的数据(原本是用于自检,现在来处理默认值)
  145. * @param {Array}datas 需要检查的属性数据
  146. * @return {void}
  147. * */
  148. function check(datas) {
  149. for (const data of datas) {
  150. const isHasValue = hasValue(data.value);
  151. // 值统一转换成String,并且处理各类型属性空值时的默认取值
  152. data.value = !isHasValue ?
  153. DEFAULT_VALUE[data.type] ?
  154. DEFAULT_VALUE[data.type] :
  155. '' :
  156. String(data.value);
  157. // 如果有限定最少长度,则当长度不够时,自动凑
  158. const autoStr = '1';
  159. if (data.minLen && data.value.length < data.minLen) {
  160. let diff = data.minLen - data.value.length;
  161. while (diff--) {
  162. data.value += autoStr;
  163. }
  164. }
  165. if (data.whiteSpace && data.whiteSpace === WHITE_SPACE.COLLAPSE) { //处理空格相关
  166. data.value = data.value.replace(/[\r\n\t]/g, ' ');
  167. data.value = data.value.trim();
  168. data.value = data.value.replace(/\s{1,}/g, ' ');
  169. }
  170. // 类型对应得值不正确时,赋类型对应默认值
  171. if (!data.type) {
  172. continue;
  173. }
  174. const 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])))/;
  175. if (data.type === TYPE.DATE && !dateReg.test(data.value)) {
  176. data.value = getDateTypeDefaultValue(new Date());
  177. } else if (data.type === TYPE.INT && !Number.isInteger(parseFloat(data.value))) {
  178. data.value = DEFAULT_VALUE[TYPE.INT];
  179. } else if (data.type === TYPE.DECIMAL && isNaN(parseFloat(data.value))) {
  180. data.value = DEFAULT_VALUE[TYPE.DECIMAL];
  181. } else if (data.type === TYPE.NUM2) {
  182. data.value = DEFAULT_VALUE[TYPE.NUM2];
  183. } else if (data.type === TYPE.BOOL && !['true', 'false'].includes(String(data.value))) {
  184. data.value = DEFAULT_VALUE[TYPE.BOOL];
  185. }
  186. }
  187. }
  188. // 等待一段时间
  189. function setTimeoutSync(handle, time) {
  190. return new Promise((resolve, reject) => {
  191. setTimeout(() => {
  192. if (handle && typeof handle === 'function') {
  193. handle();
  194. }
  195. resolve();
  196. }, time);
  197. });
  198. }
  199. /*
  200. * 将节点属性数据(attr数组)转换成简单key-value数据
  201. * @param {Object}ele 元素节点数据Element实例
  202. * @return {Object}
  203. * */
  204. function getPlainAttrs(ele) {
  205. const obj = {};
  206. ele.attrs.forEach(attr => obj[attr.name] = attr.value);
  207. return obj;
  208. }
  209. /*
  210. * 从fees数组中获取相关费用
  211. * @param {Array}fees 费用数组
  212. * {String}feeFields 费用字段
  213. * @return {Number}
  214. * @example getFee(source.fees, 'common.totalFee')
  215. * */
  216. function getFee(fees, feeFields) {
  217. if (!Array.isArray(fees)) {
  218. return 0;
  219. }
  220. const fields = feeFields.split('.');
  221. const fee = fees.find(data => data.fieldName === fields[0]);
  222. if (!fee) {
  223. return 0;
  224. }
  225. return fee[fields[1]] || 0;
  226. }
  227. // 获取节点的汇总价格
  228. function getAggregateFee(nodes) {
  229. const total = nodes.reduce((acc, node) => {
  230. const price = getFee(node.data.fees, 'common.totalFee');
  231. return acc += price;
  232. }, 0);
  233. return scMathUtil.roundTo(total, -2);
  234. }
  235. // 获取固定类别行的费用
  236. function getFeeByFlag(items, flag, feeFields) {
  237. const node = items.find(node => node.getFlag() === flag);
  238. return node ? getFee(node.data.fees, feeFields) : '0';
  239. }
  240. /*
  241. * 根据key获取对应的基本信息、工程特征数据
  242. * @param {Array}data
  243. * {String}key
  244. * @return {String}
  245. * @example getValueByKey(source.basicInformation, 'projectScale')
  246. * */
  247. function getValueByKey(items, key) {
  248. for (const item of items) {
  249. if (item.key === key) {
  250. return item.value;
  251. }
  252. if (item.items && item.items.length) {
  253. const value = getValueByKey(item.items, key);
  254. if (value) {
  255. return value;
  256. }
  257. }
  258. }
  259. return '';
  260. }
  261. //获取当前日期,格式YYYY-MM-DD
  262. function getNowFormatDay(nowDate) {
  263. var char = "-";
  264. if (nowDate == null) {
  265. nowDate = new Date();
  266. }
  267. var day = nowDate.getDate();
  268. var month = nowDate.getMonth() + 1; //注意月份需要+1
  269. var year = nowDate.getFullYear();
  270. //补全0,并拼接
  271. return year + char + completeDate(month) + char + completeDate(day);
  272. }
  273. //获取当前时间,格式YYYY-MM-DD HH:mm
  274. function getNowFormatTime() {
  275. var nowDate = new Date();
  276. var colon = ":";
  277. var h = nowDate.getHours();
  278. var m = nowDate.getMinutes();
  279. var s = nowDate.getSeconds();
  280. //补全0,并拼接
  281. return getNowFormatDay(nowDate) + " " + completeDate(h) + colon + completeDate(m);
  282. }
  283. //补全0
  284. function completeDate(value) {
  285. return value < 10 ? "0" + value : value;
  286. }
  287. // 获取关联材料
  288. function getRelGLJ(allGLJs, gljId) {
  289. return allGLJs.find(glj => glj.id === gljId);
  290. }
  291. // 随机生成机器信息码:CPU信息;硬盘序列号;mac地址;
  292. // 保存在localStorage中
  293. function generateHardwareId() {
  294. const hardwareCacheId = window.localStorage.getItem('hardwareId');
  295. if (hardwareCacheId) {
  296. return hardwareCacheId;
  297. }
  298. const charList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  299. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  300. 'V', 'W', 'X', 'Y', 'Z'
  301. ];
  302. function generateCpuId() {
  303. let id = '';
  304. let count = 16;
  305. while (count--) {
  306. const randomIdx = parseInt(Math.random() * 16);
  307. id += charList[randomIdx];
  308. }
  309. return id;
  310. }
  311. function generateDiskId() {
  312. let id = '';
  313. let count = 8;
  314. while (count--) {
  315. const randomIdx = parseInt(Math.random() * 36);
  316. id += charList[randomIdx];
  317. }
  318. return id;
  319. }
  320. function generateMacId() {
  321. const idList = [];
  322. let outerCount = 6;
  323. while (outerCount--) {
  324. let tempId = '';
  325. let innerCount = 2;
  326. while (innerCount--) {
  327. const randomIdx = parseInt(Math.random() * 16);
  328. tempId += charList[randomIdx];
  329. }
  330. idList.push(tempId);
  331. }
  332. return idList.join('-');
  333. }
  334. const cpuId = generateCpuId();
  335. const diskId = generateDiskId();
  336. const macId = generateMacId();
  337. const hardwareId = [cpuId, diskId, macId].join(';');
  338. window.localStorage.setItem('hardwareId', hardwareId);
  339. return hardwareId;
  340. }
  341. // 数组打平成对象
  342. function arrayToObj(arr) {
  343. const rst = {};
  344. for (const data of arr) {
  345. rst[data.key] = data.value;
  346. }
  347. return rst;
  348. }
  349. /*
  350. * 检测层数是否有效
  351. * @param {Number}maxDepth(最大深度)
  352. * {Object}node(需要检测的清单树节点)
  353. * @return {Boolean}
  354. * */
  355. function validDepth(maxDepth, node) {
  356. const nodeDepth = node.depth();
  357. const allNodes = node.getPosterity();
  358. //检测相对深度
  359. for (const n of allNodes) {
  360. const relativeDepth = n.depth() - nodeDepth;
  361. if (relativeDepth > maxDepth) {
  362. return false;
  363. }
  364. }
  365. return true;
  366. }
  367. // 根据数据的NextSiblingID进行排序,返回排序后的数组
  368. function sortByNext(datas) {
  369. const target = [];
  370. const temp = {};
  371. for (const data of datas) {
  372. temp[data.ID] = {
  373. me: data,
  374. next: null,
  375. prev: null
  376. };
  377. }
  378. for (const data of datas) {
  379. const next = temp[data.NextSiblingID] || null;
  380. temp[data.ID].next = next;
  381. if (next) {
  382. next.prev = temp[data.ID];
  383. }
  384. }
  385. let first = null;
  386. for (const data of datas) {
  387. const me = temp[data.ID];
  388. if (!me.prev) {
  389. first = me;
  390. }
  391. }
  392. if (!first) {
  393. return datas;
  394. }
  395. while (first) {
  396. target.push(first.me);
  397. first = first.next;
  398. }
  399. return target;
  400. }
  401. /*
  402. * 根据粒度获取项目(不包含详细数据)数据
  403. * @param {Number}granularity 导出粒度
  404. * {Object}requestForSummaryInfo 项目表级汇总字段(建设项目、单位工程汇总)
  405. * {Number}tenderID 单位工程ID
  406. * {String}userID 用户ID
  407. * @return {Object} 返回的数据结构:{children: [{children: []}]} 最外层为建设项目,中间为单项工程,最底层为单位工程
  408. * */
  409. async function getProjectByGranularity(granularity, requestForSummaryInfo, tenderID, userID) {
  410. let projectData = _cache.projectData;
  411. // 没有数据,需要拉取
  412. if (!Object.keys(projectData).length) {
  413. projectData = await ajaxPost('/pm/api/getProjectByGranularity', {
  414. user_id: userID,
  415. tenderID,
  416. granularity,
  417. requestForSummaryInfo
  418. });
  419. _cache.projectData = projectData;
  420. }
  421. return projectData;
  422. }
  423. /*
  424. * 通过getData接口获取单位工程详细数据(带缓存功能)
  425. * @param {Number}tenderID 单位工程ID
  426. * {String}userID 用户ID
  427. * @return {Object} 跟projectObj.project的数据结构一致
  428. * */
  429. async function getTenderDetail(tenderID, userID) {
  430. // 获取单位工程详细数据
  431. let tenderDetail = _cache.tenderDetailMap[tenderID];
  432. if (!tenderDetail) {
  433. tenderDetail = PROJECT.createNew(tenderID, userID);
  434. await tenderDetail.loadDataSync();
  435. // 标记序号
  436. const count = Object.keys(_cache.tenderDetailMap).length;
  437. tenderDetail.serialNo = count + 1;
  438. _cache.tenderDetailMap[tenderID] = tenderDetail;
  439. }
  440. return tenderDetail;
  441. }
  442. // 获取普通基数: {xxx}
  443. function getNormalBase(str) {
  444. const reg = /{.+?}/g;
  445. const matchs = str.match(reg);
  446. return matchs || [];
  447. }
  448. // 获取id引用基数: @xxx-xxx-xx
  449. function getIDBase(str) {
  450. const reg = /@.{36}/g;
  451. const matchs = str.match(reg);
  452. return matchs || [];
  453. }
  454. // 转换基数表达式
  455. // 1.有子项,则取固定清单对应基数
  456. // 2.无子项,有基数,a.优先转换为行代号(不可自身) b.不能转换为行代号则找对应字典
  457. // 3.基数中有无法转换的,根据导出类型决定
  458. function transformCalcBase(exportKind, tenderDetail, node, {
  459. CalcBaseMap,
  460. FlagCalcBaseMap
  461. }) {
  462. let expr = node.data.calcBase || '';
  463. if (node.children.length) {
  464. const flag = node.getFlag();
  465. return FlagCalcBaseMap[flag] || '';
  466. }
  467. if (expr) {
  468. let illegal = false;
  469. const normalBase = getNormalBase(expr);
  470. const idBase = getIDBase(expr);
  471. // 普通基数转基数字典
  472. normalBase.forEach(base => {
  473. let replaceStr = CalcBaseMap[base];
  474. // 转换成行代号的优先级比较高,进行清单匹配
  475. const flag = FlagCalcBaseMap[base];
  476. if (flag) {
  477. const flagNode = tenderDetail.mainTree.items.find(mNode => mNode.getFlag() === flag);
  478. // 匹配到了 普通基数转换成行引用
  479. if (flagNode) {
  480. replaceStr = `F${flagNode.serialNo() + 1}`;
  481. }
  482. }
  483. // 存在无法处理的基数
  484. if (!replaceStr) {
  485. illegal = true;
  486. return;
  487. }
  488. expr = expr.replace(new RegExp(base, 'g'), replaceStr);
  489. });
  490. // id引用转行代号引用
  491. idBase.forEach(base => {
  492. const id = base.match(/[^@]+/)[0];
  493. const theNode = tenderDetail.mainTree.getNodeByID(id);
  494. const rowCode = theNode ? `F${theNode.serialNo() + 1}` : '';
  495. if (!rowCode) {
  496. illegal = true;
  497. return;
  498. }
  499. expr = expr.replace(new RegExp(base, 'g'), rowCode);
  500. });
  501. // 不合法
  502. // 在我们软件中的基数无法找到映射代号的情况下
  503. // 导出招标、控制价时,基数为空
  504. // 导出投标时,基数=综合合价/费率
  505. if (illegal) {
  506. if (exportKind === EXPORT_KIND.BID_INVITATION || exportKind === EXPORT_KIND.CONTROL) {
  507. return '';
  508. } else {
  509. const totalFee = getFee(node.data.fees, 'common.totalFee');
  510. const feeRate = node.data.feeRate;
  511. return +feeRate ? scMathUtil.roundTo(totalFee / (feeRate / 100), -2) : totalFee
  512. }
  513. }
  514. return expr;
  515. }
  516. }
  517. // 转换基数说明,根据转换后的基数处理
  518. // 1.行引用转换为对应行的名称
  519. // 2.基数字典转换为中文
  520. function transformCalcBaseState(tenderDetail, expr, CalcStateMap) {
  521. if (!expr) {
  522. return '';
  523. }
  524. expr = String(expr);
  525. // 提取基数
  526. const bases = expr.split(/[\+\-\*\/]/g);
  527. // 提取操作符
  528. const oprs = expr.match(/[\+\-\*\/]/g);
  529. // 转换后的基数
  530. const newBase = [];
  531. let illegal = false;
  532. for (const base of bases) {
  533. // 行引用转换为名称.
  534. if (/F\d+/.test(base)) {
  535. const rowCode = base.match(/\d+/)[0];
  536. const node = tenderDetail.mainTree.items[rowCode - 1];
  537. if (!node || !node.data.name) {
  538. illegal = true;
  539. break;
  540. }
  541. newBase.push(node && node.data.name ? node.data.name : '');
  542. } else if (CalcStateMap[base]) { // 字典转换为中文
  543. newBase.push(CalcStateMap[base]);
  544. } else if (/^\d+(\.\d+)?$/.test(base)) { // 金额
  545. newBase.push(base);
  546. } else {
  547. illegal = true;
  548. break;
  549. }
  550. }
  551. if (illegal) {
  552. return '';
  553. }
  554. let newExpr = '';
  555. for (let i = 0; i < newBase.length; i++) {
  556. newExpr += newBase[i];
  557. if (oprs && oprs[i]) {
  558. newExpr += oprs[i];
  559. }
  560. }
  561. return newExpr;
  562. }
  563. // 获取节点的某属性
  564. function getAttr(ele, name) {
  565. return (ele.attrs.find(attr => attr.name === name) || {}).value;
  566. }
  567. // 设置节点的某属性
  568. function setAttr(ele, name, value) {
  569. const attr = ele.attrs.find(attr => attr.name === name);
  570. if (attr) {
  571. attr.value = value;
  572. }
  573. }
  574. // 从srcEle节点中获取元素名为eleName的元素
  575. function getElementFromSrc(srcEle, eleName) {
  576. if (!srcEle || !srcEle.children || !srcEle.children.length) {
  577. return [];
  578. }
  579. return srcEle.children.filter(ele => ele.name === eleName);
  580. }
  581. /*
  582. * 设置完工程编号后,更新原始数据的工程编号
  583. * 更新原始数据前需要将编号里的特殊字符进行转换
  584. * @param {Array}exportData 提取出来的需要导出的数据
  585. * {Array}codes 工程编号表中填写的工程编号
  586. * {String}EngineeringName 单项工程元素的名称
  587. * {String}tenderName 单位工程元素的名称
  588. * {String}codeName 编号属性的名称
  589. * @return {void}
  590. * */
  591. function setupCode(exportData, codes, EngineeringName, tenderName, codeName) {
  592. // 转换xml实体字符
  593. let parsedCodes = getParsedData(codes);
  594. // 给导出数据里的单项工程、单位工程填上用户设置的工程编号
  595. exportData.forEach(orgData => {
  596. let curIdx = 0;
  597. let engs = getElementFromSrc(orgData.data, EngineeringName);
  598. engs.forEach(eng => {
  599. eng.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  600. let tenders = getElementFromSrc(eng, tenderName);
  601. tenders.forEach(tender => {
  602. tender.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  603. });
  604. });
  605. });
  606. }
  607. // 将文本的中文提取出来
  608. function getHan(str) {
  609. if (!str) {
  610. return '';
  611. }
  612. return str
  613. .split('')
  614. .reduce((acc, cur) => {
  615. if (isHan(cur)) {
  616. acc.push(cur);
  617. }
  618. return acc;
  619. }, [])
  620. .join('');
  621. }
  622. const UTIL = Object.freeze({
  623. hasValue,
  624. setTimeoutSync,
  625. getFee,
  626. getAggregateFee,
  627. getFeeByFlag,
  628. getPlainAttrs,
  629. getValueByKey,
  630. getRelGLJ,
  631. generateHardwareId,
  632. arrayToObj,
  633. validDepth,
  634. sortByNext,
  635. getTenderDetail,
  636. getProjectByGranularity,
  637. getNormalBase,
  638. getIDBase,
  639. transformCalcBase,
  640. transformCalcBaseState,
  641. getElementFromSrc,
  642. getAttr,
  643. setAttr,
  644. getParsedData,
  645. setupCode,
  646. getHan,
  647. getNowFormatTime
  648. });
  649. // 开始标签
  650. function _startTag(ele) {
  651. let rst = `<${ele.name}`;
  652. for (const attr of ele.attrs) {
  653. rst += ` ${attr.name}="${attr.value}"`;
  654. }
  655. rst += ele.children.length > 0 ? '>' : '/>';
  656. return rst;
  657. }
  658. // 结束标签
  659. function _endTag(ele) {
  660. return `</${ele.name}>`;
  661. }
  662. // 拼接成xml字符串
  663. function _toXMLStr(eles) {
  664. let rst = '';
  665. for (const ele of eles) {
  666. rst += _startTag(ele);
  667. if (ele.children.length > 0) {
  668. rst += _toXMLStr(ele.children);
  669. rst += _endTag(ele);
  670. }
  671. }
  672. return rst;
  673. }
  674. // 格式化xml字符串
  675. function _formatXml(text) {
  676. // 去掉多余的空格
  677. text = '\n' + text.replace(/>\s*?</g, ">\n<");
  678. // 调整格式
  679. const reg = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  680. const nodeStack = [];
  681. const output = text.replace(reg, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
  682. const isClosed = (isCloseFull1 === '/') || (isCloseFull2 === '/') || (isFull1 === '/') || (isFull2 === '/');
  683. let prefix = '';
  684. if (isBegin === '!') {
  685. prefix = getPrefix(nodeStack.length);
  686. } else {
  687. if (isBegin !== '/') {
  688. prefix = getPrefix(nodeStack.length);
  689. if (!isClosed) {
  690. nodeStack.push(name);
  691. }
  692. } else {
  693. nodeStack.pop();
  694. prefix = getPrefix(nodeStack.length);
  695. }
  696. }
  697. return '\n' + prefix + all;
  698. });
  699. return output.substring(1);
  700. function getPrefix(prefixIndex) {
  701. const span = ' ';
  702. const output = [];
  703. for (let i = 0; i < prefixIndex; i++) {
  704. output.push(span);
  705. }
  706. return output.join('');
  707. }
  708. }
  709. /**
  710. * 提取要导出的数据
  711. * @param {Function} entryFunc - 提取数据的入口方法
  712. * @param {Object} requestForSummaryInfo - 项目表级汇总字段(建设项目、单位工程汇总)
  713. * @param {Number} exportKind - 导出的文件类型:1-招标、2-投标、3-控制价
  714. * @param {String} areaKey - 地区标识,如:'安徽@马鞍山'
  715. * @param {Number} tenderID - 单位工程ID
  716. * @param {String} userID - 用户ID
  717. * @return {Promise<Array>} - [{data: Object, exportKind: Number, fileName: String}]
  718. */
  719. async function extractExportData(entryFunc, requestForSummaryInfo, exportKind, areaKey, tenderID, userID) {
  720. // 默认导出投标文件
  721. if (!exportKind || ![1, 2, 3].includes(exportKind)) {
  722. exportKind = EXPORT_KIND.BID_SUBMISSION;
  723. }
  724. // 拉取标段数据:建设项目、单位工程数据(projects表数据)
  725. const projectData = await getProjectByGranularity(GRANULARITY.PROJECT, requestForSummaryInfo, tenderID, userID);
  726. if (!projectData) {
  727. throw '获取项目数据错误';
  728. }
  729. // 单位工程按照树结构数据进行排序,这样导出才的单位工程顺序才是对的
  730. projectData.children = sortByNext(projectData.children);
  731. // 先获取需要导出的单位工程的详细数据
  732. const tenderDetailMap = getItem('tenderDetailMap');
  733. for (const tenderItem of projectData.children) {
  734. if (!tenderDetailMap[tenderItem.ID]) {
  735. await setTimeoutSync(() => { }, TIMEOUT_TIME); // 需要请求项目详细数据的时候,间隔一段时间再初始单位工程数据,减少服务器压力
  736. }
  737. // 获取单位工程详细数据
  738. const detail = await getTenderDetail(tenderItem.ID, userID);
  739. tenderDetailPretreatment(detail);
  740. console.log(detail);
  741. }
  742. // 提取相关项目的详细导出数据
  743. return await entryFunc(areaKey, exportKind, projectData, tenderDetailMap);
  744. }
  745. // 对getData返回的数据进行一些通用预处理,方便各接口直接取值、处理
  746. function tenderDetailPretreatment(tenderDetail) {
  747. const bidEvaluationList = tenderDetail.bid_evaluation_list.datas;
  748. const evaluateList = tenderDetail.evaluate_list.datas;
  749. const decimalInfo = tenderDetail.projectInfo.property.decimal;
  750. // 项目人材机汇总排序
  751. tenderDetail.projectGLJ.datas.gljList = gljUtil.sortRationGLJ(tenderDetail.projectGLJ.datas.gljList);
  752. const projectGLJList = tenderDetail.projectGLJ.datas.gljList;
  753. // 计算人材机总消耗量,否则projectGLJ.datas.gljList里的数据不会有消耗量数据
  754. gljUtil.calcProjectGLJQuantity(tenderDetail.projectGLJ.datas, tenderDetail.ration_glj.datas, tenderDetail.Ration.datas, tenderDetail.Bills.datas, tenderDetail.property.decimal.glj.quantity, _, scMathUtil);
  755. const connectKeyMap = {};
  756. const projectGLJIDMap = {};
  757. projectGLJList.forEach(glj => {
  758. connectKeyMap[gljUtil.getIndex(glj, gljKeyArray)] = glj.id; // 为了方便后续导出处理,给组成物数据设置上对应项目人材机ID
  759. projectGLJIDMap[glj.id] = glj;
  760. // 项目人材机设置价格信息,否则projectGLJ.datas.gljList里的数据不会有相关价格信息
  761. // 价格信息存在新的priceInfo字段,以免对一些方法造成影响
  762. glj.priceInfo = gljUtil.getGLJPrice(glj, tenderDetail.projectGLJ.datas, tenderDetail.property.calcOptions, tenderDetail.labourCoe.datas, decimalInfo, false, _, scMathUtil, {}, tenderDetail.projectGLJ.getTenderPriceCoe(glj, tenderDetail.property));
  763. // 计算合价:人材料总消耗量*预算价
  764. glj.priceInfo.totalPrice = scMathUtil.roundForObj(glj.priceInfo.tenderPrice * glj.tenderQuantity, 2);
  765. });
  766. const ratiosArr = Object.values(tenderDetail.projectGLJ.datas.mixRatioMap);
  767. ratiosArr.forEach(ratios => {
  768. ratios.forEach(ratio => {
  769. const ratioKey = gljUtil.getIndex(ratio, gljKeyArray);
  770. const projectGLJID = connectKeyMap[ratioKey];
  771. if (projectGLJID) {
  772. ratio.projectGLJID = projectGLJID;
  773. }
  774. });
  775. });
  776. // 处理定额人材机,将定额人材机挂到定额的rationGLJList字段中,同时将定额人材机进行排序、计算调价消耗量
  777. tenderDetail.Ration.datas.forEach(ration => {
  778. ration.rationGLJList = tenderDetail.ration_glj.datas.filter(glj => {
  779. const pGLJ = projectGLJIDMap[glj.projectGLJID];
  780. glj.tenderQuantity = gljUtil.getRationGLJTenderQuantity(glj, ration, decimalInfo.glj.quantity, scMathUtil, pGLJ);
  781. return glj.rationID === ration.ID;
  782. });
  783. ration.rationGLJList = gljUtil.sortRationGLJ(ration.rationGLJList);
  784. });
  785. // 获取暂估价材料数据,getData原始数据evaluate_list.datas里的数据缺少一些价格数据,需要调用额外接口
  786. tenderDetail.evaluateMaterialData = configMaterialObj.getEvaluateMaterialDatas(projectGLJList, evaluateList, decimalInfo);
  787. // 获取评标材料数据
  788. tenderDetail.bidMaterialData = configMaterialObj.getBidMaterialDatas(projectGLJList, bidEvaluationList, decimalInfo);
  789. }
  790. /**
  791. * 根据各自费用定额的文件结构,导出文件
  792. * 每个费用定额可能导出的结果文件都不同
  793. * 比如广东18需要将一个建设项目文件,多个单位工程文件打包成一个zip文件。重庆18就没这种要求
  794. * @param {Array} extractData - 提取的数据
  795. * @param {Function} saveAsFunc - 各自费用定额的导出方法,适应不同接口需要不同的最终文件形式
  796. */
  797. async function exportFile(extractData, saveAsFunc) {
  798. // 获取文件数据
  799. const fileData = extractData.map(extractObj => {
  800. // 转换成xml字符串
  801. let xmlStr = _toXMLStr([extractObj.data]);
  802. // 加上xml声明
  803. xmlStr = `<?xml version="1.0" encoding="utf-8"?>${xmlStr}`;
  804. // 格式化
  805. xmlStr = _formatXml(xmlStr);
  806. const blob = new Blob([xmlStr], {
  807. type: 'text/plain;charset=utf-8'
  808. });
  809. return {
  810. blob: blob,
  811. exportKind: extractObj.exportKind,
  812. fileName: extractObj.fileName
  813. };
  814. });
  815. if (!saveAsFunc) {
  816. return fileData;
  817. }
  818. // 导出
  819. await saveAsFunc(fileData);
  820. }
  821. /**
  822. * 默认的通用导出文件方法:一个文件数据对应一个xml文件(变更后缀)
  823. * @param {Array} fileData - 默认的通用导出文件方法:一个文件数据对应一个xml文件(变更后缀)
  824. * @return {Void}
  825. */
  826. async function defaultSaveAs(fileData) {
  827. fileData.forEach(fileItem => saveAs(fileItem.blob, fileItem.fileName));
  828. }
  829. return {
  830. CONFIG,
  831. CACHE,
  832. UTIL,
  833. Element,
  834. extractExportData,
  835. defaultSaveAs,
  836. exportFile,
  837. };
  838. })();