base.js 29 KB

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